PackageManagerService.java revision 9f013fe71ecf03c9c9696599ba82715d84e45365
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    /** Special library name that skips shared libraries check during compilation. */
502    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
503
504    final ServiceThread mHandlerThread;
505
506    final PackageHandler mHandler;
507
508    private final ProcessLoggingHandler mProcessLoggingHandler;
509
510    /**
511     * Messages for {@link #mHandler} that need to wait for system ready before
512     * being dispatched.
513     */
514    private ArrayList<Message> mPostSystemReadyMessages;
515
516    final int mSdkVersion = Build.VERSION.SDK_INT;
517
518    final Context mContext;
519    final boolean mFactoryTest;
520    final boolean mOnlyCore;
521    final DisplayMetrics mMetrics;
522    final int mDefParseFlags;
523    final String[] mSeparateProcesses;
524    final boolean mIsUpgrade;
525    final boolean mIsPreNUpgrade;
526
527    /** The location for ASEC container files on internal storage. */
528    final String mAsecInternalPath;
529
530    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
531    // LOCK HELD.  Can be called with mInstallLock held.
532    @GuardedBy("mInstallLock")
533    final Installer mInstaller;
534
535    /** Directory where installed third-party apps stored */
536    final File mAppInstallDir;
537    final File mEphemeralInstallDir;
538
539    /**
540     * Directory to which applications installed internally have their
541     * 32 bit native libraries copied.
542     */
543    private File mAppLib32InstallDir;
544
545    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
546    // apps.
547    final File mDrmAppPrivateInstallDir;
548
549    // ----------------------------------------------------------------
550
551    // Lock for state used when installing and doing other long running
552    // operations.  Methods that must be called with this lock held have
553    // the suffix "LI".
554    final Object mInstallLock = new Object();
555
556    // ----------------------------------------------------------------
557
558    // Keys are String (package name), values are Package.  This also serves
559    // as the lock for the global state.  Methods that must be called with
560    // this lock held have the prefix "LP".
561    @GuardedBy("mPackages")
562    final ArrayMap<String, PackageParser.Package> mPackages =
563            new ArrayMap<String, PackageParser.Package>();
564
565    final ArrayMap<String, Set<String>> mKnownCodebase =
566            new ArrayMap<String, Set<String>>();
567
568    // Tracks available target package names -> overlay package paths.
569    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
570        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
571
572    /**
573     * Tracks new system packages [received in an OTA] that we expect to
574     * find updated user-installed versions. Keys are package name, values
575     * are package location.
576     */
577    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
578    /**
579     * Tracks high priority intent filters for protected actions. During boot, certain
580     * filter actions are protected and should never be allowed to have a high priority
581     * intent filter for them. However, there is one, and only one exception -- the
582     * setup wizard. It must be able to define a high priority intent filter for these
583     * actions to ensure there are no escapes from the wizard. We need to delay processing
584     * of these during boot as we need to look at all of the system packages in order
585     * to know which component is the setup wizard.
586     */
587    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
588    /**
589     * Whether or not processing protected filters should be deferred.
590     */
591    private boolean mDeferProtectedFilters = true;
592
593    /**
594     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
595     */
596    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
597    /**
598     * Whether or not system app permissions should be promoted from install to runtime.
599     */
600    boolean mPromoteSystemApps;
601
602    @GuardedBy("mPackages")
603    final Settings mSettings;
604
605    /**
606     * Set of package names that are currently "frozen", which means active
607     * surgery is being done on the code/data for that package. The platform
608     * will refuse to launch frozen packages to avoid race conditions.
609     *
610     * @see PackageFreezer
611     */
612    @GuardedBy("mPackages")
613    final ArraySet<String> mFrozenPackages = new ArraySet<>();
614
615    boolean mRestoredSettings;
616
617    // System configuration read by SystemConfig.
618    final int[] mGlobalGids;
619    final SparseArray<ArraySet<String>> mSystemPermissions;
620    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
621
622    // If mac_permissions.xml was found for seinfo labeling.
623    boolean mFoundPolicyFile;
624
625    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
626
627    public static final class SharedLibraryEntry {
628        public final String path;
629        public final String apk;
630
631        SharedLibraryEntry(String _path, String _apk) {
632            path = _path;
633            apk = _apk;
634        }
635    }
636
637    // Currently known shared libraries.
638    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
639            new ArrayMap<String, SharedLibraryEntry>();
640
641    // All available activities, for your resolving pleasure.
642    final ActivityIntentResolver mActivities =
643            new ActivityIntentResolver();
644
645    // All available receivers, for your resolving pleasure.
646    final ActivityIntentResolver mReceivers =
647            new ActivityIntentResolver();
648
649    // All available services, for your resolving pleasure.
650    final ServiceIntentResolver mServices = new ServiceIntentResolver();
651
652    // All available providers, for your resolving pleasure.
653    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
654
655    // Mapping from provider base names (first directory in content URI codePath)
656    // to the provider information.
657    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
658            new ArrayMap<String, PackageParser.Provider>();
659
660    // Mapping from instrumentation class names to info about them.
661    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
662            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
663
664    // Mapping from permission names to info about them.
665    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
666            new ArrayMap<String, PackageParser.PermissionGroup>();
667
668    // Packages whose data we have transfered into another package, thus
669    // should no longer exist.
670    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
671
672    // Broadcast actions that are only available to the system.
673    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
674
675    /** List of packages waiting for verification. */
676    final SparseArray<PackageVerificationState> mPendingVerification
677            = new SparseArray<PackageVerificationState>();
678
679    /** Set of packages associated with each app op permission. */
680    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
681
682    final PackageInstallerService mInstallerService;
683
684    private final PackageDexOptimizer mPackageDexOptimizer;
685
686    private AtomicInteger mNextMoveId = new AtomicInteger();
687    private final MoveCallbacks mMoveCallbacks;
688
689    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
690
691    // Cache of users who need badging.
692    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
693
694    /** Token for keys in mPendingVerification. */
695    private int mPendingVerificationToken = 0;
696
697    volatile boolean mSystemReady;
698    volatile boolean mSafeMode;
699    volatile boolean mHasSystemUidErrors;
700
701    ApplicationInfo mAndroidApplication;
702    final ActivityInfo mResolveActivity = new ActivityInfo();
703    final ResolveInfo mResolveInfo = new ResolveInfo();
704    ComponentName mResolveComponentName;
705    PackageParser.Package mPlatformPackage;
706    ComponentName mCustomResolverComponentName;
707
708    boolean mResolverReplaced = false;
709
710    private final @Nullable ComponentName mIntentFilterVerifierComponent;
711    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
712
713    private int mIntentFilterVerificationToken = 0;
714
715    /** Component that knows whether or not an ephemeral application exists */
716    final ComponentName mEphemeralResolverComponent;
717    /** The service connection to the ephemeral resolver */
718    final EphemeralResolverConnection mEphemeralResolverConnection;
719
720    /** Component used to install ephemeral applications */
721    final ComponentName mEphemeralInstallerComponent;
722    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
723    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
724
725    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
726            = new SparseArray<IntentFilterVerificationState>();
727
728    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
729            new DefaultPermissionGrantPolicy(this);
730
731    // List of packages names to keep cached, even if they are uninstalled for all users
732    private List<String> mKeepUninstalledPackages;
733
734    private static class IFVerificationParams {
735        PackageParser.Package pkg;
736        boolean replacing;
737        int userId;
738        int verifierUid;
739
740        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
741                int _userId, int _verifierUid) {
742            pkg = _pkg;
743            replacing = _replacing;
744            userId = _userId;
745            replacing = _replacing;
746            verifierUid = _verifierUid;
747        }
748    }
749
750    private interface IntentFilterVerifier<T extends IntentFilter> {
751        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
752                                               T filter, String packageName);
753        void startVerifications(int userId);
754        void receiveVerificationResponse(int verificationId);
755    }
756
757    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
758        private Context mContext;
759        private ComponentName mIntentFilterVerifierComponent;
760        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
761
762        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
763            mContext = context;
764            mIntentFilterVerifierComponent = verifierComponent;
765        }
766
767        private String getDefaultScheme() {
768            return IntentFilter.SCHEME_HTTPS;
769        }
770
771        @Override
772        public void startVerifications(int userId) {
773            // Launch verifications requests
774            int count = mCurrentIntentFilterVerifications.size();
775            for (int n=0; n<count; n++) {
776                int verificationId = mCurrentIntentFilterVerifications.get(n);
777                final IntentFilterVerificationState ivs =
778                        mIntentFilterVerificationStates.get(verificationId);
779
780                String packageName = ivs.getPackageName();
781
782                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
783                final int filterCount = filters.size();
784                ArraySet<String> domainsSet = new ArraySet<>();
785                for (int m=0; m<filterCount; m++) {
786                    PackageParser.ActivityIntentInfo filter = filters.get(m);
787                    domainsSet.addAll(filter.getHostsList());
788                }
789                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
790                synchronized (mPackages) {
791                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
792                            packageName, domainsList) != null) {
793                        scheduleWriteSettingsLocked();
794                    }
795                }
796                sendVerificationRequest(userId, verificationId, ivs);
797            }
798            mCurrentIntentFilterVerifications.clear();
799        }
800
801        private void sendVerificationRequest(int userId, int verificationId,
802                IntentFilterVerificationState ivs) {
803
804            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
805            verificationIntent.putExtra(
806                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
807                    verificationId);
808            verificationIntent.putExtra(
809                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
810                    getDefaultScheme());
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
813                    ivs.getHostsString());
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
816                    ivs.getPackageName());
817            verificationIntent.setComponent(mIntentFilterVerifierComponent);
818            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
819
820            UserHandle user = new UserHandle(userId);
821            mContext.sendBroadcastAsUser(verificationIntent, user);
822            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
823                    "Sending IntentFilter verification broadcast");
824        }
825
826        public void receiveVerificationResponse(int verificationId) {
827            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
828
829            final boolean verified = ivs.isVerified();
830
831            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
832            final int count = filters.size();
833            if (DEBUG_DOMAIN_VERIFICATION) {
834                Slog.i(TAG, "Received verification response " + verificationId
835                        + " for " + count + " filters, verified=" + verified);
836            }
837            for (int n=0; n<count; n++) {
838                PackageParser.ActivityIntentInfo filter = filters.get(n);
839                filter.setVerified(verified);
840
841                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
842                        + " verified with result:" + verified + " and hosts:"
843                        + ivs.getHostsString());
844            }
845
846            mIntentFilterVerificationStates.remove(verificationId);
847
848            final String packageName = ivs.getPackageName();
849            IntentFilterVerificationInfo ivi = null;
850
851            synchronized (mPackages) {
852                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
853            }
854            if (ivi == null) {
855                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
856                        + verificationId + " packageName:" + packageName);
857                return;
858            }
859            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
860                    "Updating IntentFilterVerificationInfo for package " + packageName
861                            +" verificationId:" + verificationId);
862
863            synchronized (mPackages) {
864                if (verified) {
865                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
866                } else {
867                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
868                }
869                scheduleWriteSettingsLocked();
870
871                final int userId = ivs.getUserId();
872                if (userId != UserHandle.USER_ALL) {
873                    final int userStatus =
874                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
875
876                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
877                    boolean needUpdate = false;
878
879                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
880                    // already been set by the User thru the Disambiguation dialog
881                    switch (userStatus) {
882                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
883                            if (verified) {
884                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
885                            } else {
886                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
887                            }
888                            needUpdate = true;
889                            break;
890
891                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
892                            if (verified) {
893                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
894                                needUpdate = true;
895                            }
896                            break;
897
898                        default:
899                            // Nothing to do
900                    }
901
902                    if (needUpdate) {
903                        mSettings.updateIntentFilterVerificationStatusLPw(
904                                packageName, updatedStatus, userId);
905                        scheduleWritePackageRestrictionsLocked(userId);
906                    }
907                }
908            }
909        }
910
911        @Override
912        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
913                    ActivityIntentInfo filter, String packageName) {
914            if (!hasValidDomains(filter)) {
915                return false;
916            }
917            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
918            if (ivs == null) {
919                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
920                        packageName);
921            }
922            if (DEBUG_DOMAIN_VERIFICATION) {
923                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
924            }
925            ivs.addFilter(filter);
926            return true;
927        }
928
929        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
930                int userId, int verificationId, String packageName) {
931            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
932                    verifierUid, userId, packageName);
933            ivs.setPendingState();
934            synchronized (mPackages) {
935                mIntentFilterVerificationStates.append(verificationId, ivs);
936                mCurrentIntentFilterVerifications.add(verificationId);
937            }
938            return ivs;
939        }
940    }
941
942    private static boolean hasValidDomains(ActivityIntentInfo filter) {
943        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
944                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
945                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
946    }
947
948    // Set of pending broadcasts for aggregating enable/disable of components.
949    static class PendingPackageBroadcasts {
950        // for each user id, a map of <package name -> components within that package>
951        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
952
953        public PendingPackageBroadcasts() {
954            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
955        }
956
957        public ArrayList<String> get(int userId, String packageName) {
958            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
959            return packages.get(packageName);
960        }
961
962        public void put(int userId, String packageName, ArrayList<String> components) {
963            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
964            packages.put(packageName, components);
965        }
966
967        public void remove(int userId, String packageName) {
968            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
969            if (packages != null) {
970                packages.remove(packageName);
971            }
972        }
973
974        public void remove(int userId) {
975            mUidMap.remove(userId);
976        }
977
978        public int userIdCount() {
979            return mUidMap.size();
980        }
981
982        public int userIdAt(int n) {
983            return mUidMap.keyAt(n);
984        }
985
986        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
987            return mUidMap.get(userId);
988        }
989
990        public int size() {
991            // total number of pending broadcast entries across all userIds
992            int num = 0;
993            for (int i = 0; i< mUidMap.size(); i++) {
994                num += mUidMap.valueAt(i).size();
995            }
996            return num;
997        }
998
999        public void clear() {
1000            mUidMap.clear();
1001        }
1002
1003        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1004            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1005            if (map == null) {
1006                map = new ArrayMap<String, ArrayList<String>>();
1007                mUidMap.put(userId, map);
1008            }
1009            return map;
1010        }
1011    }
1012    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1013
1014    // Service Connection to remote media container service to copy
1015    // package uri's from external media onto secure containers
1016    // or internal storage.
1017    private IMediaContainerService mContainerService = null;
1018
1019    static final int SEND_PENDING_BROADCAST = 1;
1020    static final int MCS_BOUND = 3;
1021    static final int END_COPY = 4;
1022    static final int INIT_COPY = 5;
1023    static final int MCS_UNBIND = 6;
1024    static final int START_CLEANING_PACKAGE = 7;
1025    static final int FIND_INSTALL_LOC = 8;
1026    static final int POST_INSTALL = 9;
1027    static final int MCS_RECONNECT = 10;
1028    static final int MCS_GIVE_UP = 11;
1029    static final int UPDATED_MEDIA_STATUS = 12;
1030    static final int WRITE_SETTINGS = 13;
1031    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1032    static final int PACKAGE_VERIFIED = 15;
1033    static final int CHECK_PENDING_VERIFICATION = 16;
1034    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1035    static final int INTENT_FILTER_VERIFIED = 18;
1036
1037    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1038
1039    // Delay time in millisecs
1040    static final int BROADCAST_DELAY = 10 * 1000;
1041
1042    static UserManagerService sUserManager;
1043
1044    // Stores a list of users whose package restrictions file needs to be updated
1045    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1046
1047    final private DefaultContainerConnection mDefContainerConn =
1048            new DefaultContainerConnection();
1049    class DefaultContainerConnection implements ServiceConnection {
1050        public void onServiceConnected(ComponentName name, IBinder service) {
1051            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1052            IMediaContainerService imcs =
1053                IMediaContainerService.Stub.asInterface(service);
1054            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1055        }
1056
1057        public void onServiceDisconnected(ComponentName name) {
1058            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1059        }
1060    }
1061
1062    // Recordkeeping of restore-after-install operations that are currently in flight
1063    // between the Package Manager and the Backup Manager
1064    static class PostInstallData {
1065        public InstallArgs args;
1066        public PackageInstalledInfo res;
1067
1068        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1069            args = _a;
1070            res = _r;
1071        }
1072    }
1073
1074    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1075    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1076
1077    // XML tags for backup/restore of various bits of state
1078    private static final String TAG_PREFERRED_BACKUP = "pa";
1079    private static final String TAG_DEFAULT_APPS = "da";
1080    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1081
1082    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1083    private static final String TAG_ALL_GRANTS = "rt-grants";
1084    private static final String TAG_GRANT = "grant";
1085    private static final String ATTR_PACKAGE_NAME = "pkg";
1086
1087    private static final String TAG_PERMISSION = "perm";
1088    private static final String ATTR_PERMISSION_NAME = "name";
1089    private static final String ATTR_IS_GRANTED = "g";
1090    private static final String ATTR_USER_SET = "set";
1091    private static final String ATTR_USER_FIXED = "fixed";
1092    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1093
1094    // System/policy permission grants are not backed up
1095    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1096            FLAG_PERMISSION_POLICY_FIXED
1097            | FLAG_PERMISSION_SYSTEM_FIXED
1098            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1099
1100    // And we back up these user-adjusted states
1101    private static final int USER_RUNTIME_GRANT_MASK =
1102            FLAG_PERMISSION_USER_SET
1103            | FLAG_PERMISSION_USER_FIXED
1104            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1105
1106    final @Nullable String mRequiredVerifierPackage;
1107    final @NonNull String mRequiredInstallerPackage;
1108    final @Nullable String mSetupWizardPackage;
1109    final @NonNull String mServicesSystemSharedLibraryPackageName;
1110    final @NonNull String mSharedSystemSharedLibraryPackageName;
1111
1112    private final PackageUsage mPackageUsage = new PackageUsage();
1113
1114    private class PackageUsage {
1115        private static final int WRITE_INTERVAL
1116            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1117
1118        private final Object mFileLock = new Object();
1119        private final AtomicLong mLastWritten = new AtomicLong(0);
1120        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1121
1122        private boolean mIsHistoricalPackageUsageAvailable = true;
1123
1124        boolean isHistoricalPackageUsageAvailable() {
1125            return mIsHistoricalPackageUsageAvailable;
1126        }
1127
1128        void write(boolean force) {
1129            if (force) {
1130                writeInternal();
1131                return;
1132            }
1133            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1134                && !DEBUG_DEXOPT) {
1135                return;
1136            }
1137            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1138                new Thread("PackageUsage_DiskWriter") {
1139                    @Override
1140                    public void run() {
1141                        try {
1142                            writeInternal();
1143                        } finally {
1144                            mBackgroundWriteRunning.set(false);
1145                        }
1146                    }
1147                }.start();
1148            }
1149        }
1150
1151        private void writeInternal() {
1152            synchronized (mPackages) {
1153                synchronized (mFileLock) {
1154                    AtomicFile file = getFile();
1155                    FileOutputStream f = null;
1156                    try {
1157                        f = file.startWrite();
1158                        BufferedOutputStream out = new BufferedOutputStream(f);
1159                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1160                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1161                        StringBuilder sb = new StringBuilder();
1162
1163                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1164                        sb.append('\n');
1165                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1166
1167                        for (PackageParser.Package pkg : mPackages.values()) {
1168                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1169                                continue;
1170                            }
1171                            sb.setLength(0);
1172                            sb.append(pkg.packageName);
1173                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1174                                sb.append(' ');
1175                                sb.append(usageTimeInMillis);
1176                            }
1177                            sb.append('\n');
1178                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1179                        }
1180                        out.flush();
1181                        file.finishWrite(f);
1182                    } catch (IOException e) {
1183                        if (f != null) {
1184                            file.failWrite(f);
1185                        }
1186                        Log.e(TAG, "Failed to write package usage times", e);
1187                    }
1188                }
1189            }
1190            mLastWritten.set(SystemClock.elapsedRealtime());
1191        }
1192
1193        void readLP() {
1194            synchronized (mFileLock) {
1195                AtomicFile file = getFile();
1196                BufferedInputStream in = null;
1197                try {
1198                    in = new BufferedInputStream(file.openRead());
1199                    StringBuffer sb = new StringBuffer();
1200
1201                    String firstLine = readLine(in, sb);
1202                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1203                        readVersion1LP(in, sb);
1204                    } else {
1205                        readVersion0LP(in, sb, firstLine);
1206                    }
1207                } catch (FileNotFoundException expected) {
1208                    mIsHistoricalPackageUsageAvailable = false;
1209                } catch (IOException e) {
1210                    Log.w(TAG, "Failed to read package usage times", e);
1211                } finally {
1212                    IoUtils.closeQuietly(in);
1213                }
1214            }
1215            mLastWritten.set(SystemClock.elapsedRealtime());
1216        }
1217
1218        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1219                throws IOException {
1220            // Initial version of the file had no version number and stored one
1221            // package-timestamp pair per line.
1222            // Note that the first line has already been read from the InputStream.
1223            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1224                String[] tokens = line.split(" ");
1225                if (tokens.length != 2) {
1226                    throw new IOException("Failed to parse " + line +
1227                            " as package-timestamp pair.");
1228                }
1229
1230                String packageName = tokens[0];
1231                PackageParser.Package pkg = mPackages.get(packageName);
1232                if (pkg == null) {
1233                    continue;
1234                }
1235
1236                long timestamp = parseAsLong(tokens[1]);
1237                for (int reason = 0;
1238                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1239                        reason++) {
1240                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1241                }
1242            }
1243        }
1244
1245        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1246            // Version 1 of the file started with the corresponding version
1247            // number and then stored a package name and eight timestamps per line.
1248            String line;
1249            while ((line = readLine(in, sb)) != null) {
1250                String[] tokens = line.split(" ");
1251                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1252                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1253                }
1254
1255                String packageName = tokens[0];
1256                PackageParser.Package pkg = mPackages.get(packageName);
1257                if (pkg == null) {
1258                    continue;
1259                }
1260
1261                for (int reason = 0;
1262                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1263                        reason++) {
1264                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1265                }
1266            }
1267        }
1268
1269        private long parseAsLong(String token) throws IOException {
1270            try {
1271                return Long.parseLong(token);
1272            } catch (NumberFormatException e) {
1273                throw new IOException("Failed to parse " + token + " as a long.", e);
1274            }
1275        }
1276
1277        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1278            return readToken(in, sb, '\n');
1279        }
1280
1281        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1282                throws IOException {
1283            sb.setLength(0);
1284            while (true) {
1285                int ch = in.read();
1286                if (ch == -1) {
1287                    if (sb.length() == 0) {
1288                        return null;
1289                    }
1290                    throw new IOException("Unexpected EOF");
1291                }
1292                if (ch == endOfToken) {
1293                    return sb.toString();
1294                }
1295                sb.append((char)ch);
1296            }
1297        }
1298
1299        private AtomicFile getFile() {
1300            File dataDir = Environment.getDataDirectory();
1301            File systemDir = new File(dataDir, "system");
1302            File fname = new File(systemDir, "package-usage.list");
1303            return new AtomicFile(fname);
1304        }
1305
1306        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1307        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1308    }
1309
1310    class PackageHandler extends Handler {
1311        private boolean mBound = false;
1312        final ArrayList<HandlerParams> mPendingInstalls =
1313            new ArrayList<HandlerParams>();
1314
1315        private boolean connectToService() {
1316            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1317                    " DefaultContainerService");
1318            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1319            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1320            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1321                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1322                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1323                mBound = true;
1324                return true;
1325            }
1326            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1327            return false;
1328        }
1329
1330        private void disconnectService() {
1331            mContainerService = null;
1332            mBound = false;
1333            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1334            mContext.unbindService(mDefContainerConn);
1335            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336        }
1337
1338        PackageHandler(Looper looper) {
1339            super(looper);
1340        }
1341
1342        public void handleMessage(Message msg) {
1343            try {
1344                doHandleMessage(msg);
1345            } finally {
1346                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1347            }
1348        }
1349
1350        void doHandleMessage(Message msg) {
1351            switch (msg.what) {
1352                case INIT_COPY: {
1353                    HandlerParams params = (HandlerParams) msg.obj;
1354                    int idx = mPendingInstalls.size();
1355                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1356                    // If a bind was already initiated we dont really
1357                    // need to do anything. The pending install
1358                    // will be processed later on.
1359                    if (!mBound) {
1360                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1361                                System.identityHashCode(mHandler));
1362                        // If this is the only one pending we might
1363                        // have to bind to the service again.
1364                        if (!connectToService()) {
1365                            Slog.e(TAG, "Failed to bind to media container service");
1366                            params.serviceError();
1367                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1368                                    System.identityHashCode(mHandler));
1369                            if (params.traceMethod != null) {
1370                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1371                                        params.traceCookie);
1372                            }
1373                            return;
1374                        } else {
1375                            // Once we bind to the service, the first
1376                            // pending request will be processed.
1377                            mPendingInstalls.add(idx, params);
1378                        }
1379                    } else {
1380                        mPendingInstalls.add(idx, params);
1381                        // Already bound to the service. Just make
1382                        // sure we trigger off processing the first request.
1383                        if (idx == 0) {
1384                            mHandler.sendEmptyMessage(MCS_BOUND);
1385                        }
1386                    }
1387                    break;
1388                }
1389                case MCS_BOUND: {
1390                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1391                    if (msg.obj != null) {
1392                        mContainerService = (IMediaContainerService) msg.obj;
1393                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1394                                System.identityHashCode(mHandler));
1395                    }
1396                    if (mContainerService == null) {
1397                        if (!mBound) {
1398                            // Something seriously wrong since we are not bound and we are not
1399                            // waiting for connection. Bail out.
1400                            Slog.e(TAG, "Cannot bind to media container service");
1401                            for (HandlerParams params : mPendingInstalls) {
1402                                // Indicate service bind error
1403                                params.serviceError();
1404                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1405                                        System.identityHashCode(params));
1406                                if (params.traceMethod != null) {
1407                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1408                                            params.traceMethod, params.traceCookie);
1409                                }
1410                                return;
1411                            }
1412                            mPendingInstalls.clear();
1413                        } else {
1414                            Slog.w(TAG, "Waiting to connect to media container service");
1415                        }
1416                    } else if (mPendingInstalls.size() > 0) {
1417                        HandlerParams params = mPendingInstalls.get(0);
1418                        if (params != null) {
1419                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1420                                    System.identityHashCode(params));
1421                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1422                            if (params.startCopy()) {
1423                                // We are done...  look for more work or to
1424                                // go idle.
1425                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1426                                        "Checking for more work or unbind...");
1427                                // Delete pending install
1428                                if (mPendingInstalls.size() > 0) {
1429                                    mPendingInstalls.remove(0);
1430                                }
1431                                if (mPendingInstalls.size() == 0) {
1432                                    if (mBound) {
1433                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1434                                                "Posting delayed MCS_UNBIND");
1435                                        removeMessages(MCS_UNBIND);
1436                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1437                                        // Unbind after a little delay, to avoid
1438                                        // continual thrashing.
1439                                        sendMessageDelayed(ubmsg, 10000);
1440                                    }
1441                                } else {
1442                                    // There are more pending requests in queue.
1443                                    // Just post MCS_BOUND message to trigger processing
1444                                    // of next pending install.
1445                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1446                                            "Posting MCS_BOUND for next work");
1447                                    mHandler.sendEmptyMessage(MCS_BOUND);
1448                                }
1449                            }
1450                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1451                        }
1452                    } else {
1453                        // Should never happen ideally.
1454                        Slog.w(TAG, "Empty queue");
1455                    }
1456                    break;
1457                }
1458                case MCS_RECONNECT: {
1459                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1460                    if (mPendingInstalls.size() > 0) {
1461                        if (mBound) {
1462                            disconnectService();
1463                        }
1464                        if (!connectToService()) {
1465                            Slog.e(TAG, "Failed to bind to media container service");
1466                            for (HandlerParams params : mPendingInstalls) {
1467                                // Indicate service bind error
1468                                params.serviceError();
1469                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1470                                        System.identityHashCode(params));
1471                            }
1472                            mPendingInstalls.clear();
1473                        }
1474                    }
1475                    break;
1476                }
1477                case MCS_UNBIND: {
1478                    // If there is no actual work left, then time to unbind.
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1480
1481                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1482                        if (mBound) {
1483                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1484
1485                            disconnectService();
1486                        }
1487                    } else if (mPendingInstalls.size() > 0) {
1488                        // There are more pending requests in queue.
1489                        // Just post MCS_BOUND message to trigger processing
1490                        // of next pending install.
1491                        mHandler.sendEmptyMessage(MCS_BOUND);
1492                    }
1493
1494                    break;
1495                }
1496                case MCS_GIVE_UP: {
1497                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1498                    HandlerParams params = mPendingInstalls.remove(0);
1499                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1500                            System.identityHashCode(params));
1501                    break;
1502                }
1503                case SEND_PENDING_BROADCAST: {
1504                    String packages[];
1505                    ArrayList<String> components[];
1506                    int size = 0;
1507                    int uids[];
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1509                    synchronized (mPackages) {
1510                        if (mPendingBroadcasts == null) {
1511                            return;
1512                        }
1513                        size = mPendingBroadcasts.size();
1514                        if (size <= 0) {
1515                            // Nothing to be done. Just return
1516                            return;
1517                        }
1518                        packages = new String[size];
1519                        components = new ArrayList[size];
1520                        uids = new int[size];
1521                        int i = 0;  // filling out the above arrays
1522
1523                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1524                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1525                            Iterator<Map.Entry<String, ArrayList<String>>> it
1526                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1527                                            .entrySet().iterator();
1528                            while (it.hasNext() && i < size) {
1529                                Map.Entry<String, ArrayList<String>> ent = it.next();
1530                                packages[i] = ent.getKey();
1531                                components[i] = ent.getValue();
1532                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1533                                uids[i] = (ps != null)
1534                                        ? UserHandle.getUid(packageUserId, ps.appId)
1535                                        : -1;
1536                                i++;
1537                            }
1538                        }
1539                        size = i;
1540                        mPendingBroadcasts.clear();
1541                    }
1542                    // Send broadcasts
1543                    for (int i = 0; i < size; i++) {
1544                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1545                    }
1546                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1547                    break;
1548                }
1549                case START_CLEANING_PACKAGE: {
1550                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1551                    final String packageName = (String)msg.obj;
1552                    final int userId = msg.arg1;
1553                    final boolean andCode = msg.arg2 != 0;
1554                    synchronized (mPackages) {
1555                        if (userId == UserHandle.USER_ALL) {
1556                            int[] users = sUserManager.getUserIds();
1557                            for (int user : users) {
1558                                mSettings.addPackageToCleanLPw(
1559                                        new PackageCleanItem(user, packageName, andCode));
1560                            }
1561                        } else {
1562                            mSettings.addPackageToCleanLPw(
1563                                    new PackageCleanItem(userId, packageName, andCode));
1564                        }
1565                    }
1566                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1567                    startCleaningPackages();
1568                } break;
1569                case POST_INSTALL: {
1570                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1571
1572                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1573                    final boolean didRestore = (msg.arg2 != 0);
1574                    mRunningInstalls.delete(msg.arg1);
1575
1576                    if (data != null) {
1577                        InstallArgs args = data.args;
1578                        PackageInstalledInfo parentRes = data.res;
1579
1580                        final boolean grantPermissions = (args.installFlags
1581                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1582                        final boolean killApp = (args.installFlags
1583                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1584                        final String[] grantedPermissions = args.installGrantPermissions;
1585
1586                        // Handle the parent package
1587                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1588                                grantedPermissions, didRestore, args.installerPackageName,
1589                                args.observer);
1590
1591                        // Handle the child packages
1592                        final int childCount = (parentRes.addedChildPackages != null)
1593                                ? parentRes.addedChildPackages.size() : 0;
1594                        for (int i = 0; i < childCount; i++) {
1595                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1596                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1597                                    grantedPermissions, false, args.installerPackageName,
1598                                    args.observer);
1599                        }
1600
1601                        // Log tracing if needed
1602                        if (args.traceMethod != null) {
1603                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1604                                    args.traceCookie);
1605                        }
1606                    } else {
1607                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1608                    }
1609
1610                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1611                } break;
1612                case UPDATED_MEDIA_STATUS: {
1613                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1614                    boolean reportStatus = msg.arg1 == 1;
1615                    boolean doGc = msg.arg2 == 1;
1616                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1617                    if (doGc) {
1618                        // Force a gc to clear up stale containers.
1619                        Runtime.getRuntime().gc();
1620                    }
1621                    if (msg.obj != null) {
1622                        @SuppressWarnings("unchecked")
1623                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1624                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1625                        // Unload containers
1626                        unloadAllContainers(args);
1627                    }
1628                    if (reportStatus) {
1629                        try {
1630                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1631                            PackageHelper.getMountService().finishMediaUpdate();
1632                        } catch (RemoteException e) {
1633                            Log.e(TAG, "MountService not running?");
1634                        }
1635                    }
1636                } break;
1637                case WRITE_SETTINGS: {
1638                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1639                    synchronized (mPackages) {
1640                        removeMessages(WRITE_SETTINGS);
1641                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1642                        mSettings.writeLPr();
1643                        mDirtyUsers.clear();
1644                    }
1645                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1646                } break;
1647                case WRITE_PACKAGE_RESTRICTIONS: {
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1649                    synchronized (mPackages) {
1650                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1651                        for (int userId : mDirtyUsers) {
1652                            mSettings.writePackageRestrictionsLPr(userId);
1653                        }
1654                        mDirtyUsers.clear();
1655                    }
1656                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657                } break;
1658                case CHECK_PENDING_VERIFICATION: {
1659                    final int verificationId = msg.arg1;
1660                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1661
1662                    if ((state != null) && !state.timeoutExtended()) {
1663                        final InstallArgs args = state.getInstallArgs();
1664                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1665
1666                        Slog.i(TAG, "Verification timed out for " + originUri);
1667                        mPendingVerification.remove(verificationId);
1668
1669                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1670
1671                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1672                            Slog.i(TAG, "Continuing with installation of " + originUri);
1673                            state.setVerifierResponse(Binder.getCallingUid(),
1674                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1675                            broadcastPackageVerified(verificationId, originUri,
1676                                    PackageManager.VERIFICATION_ALLOW,
1677                                    state.getInstallArgs().getUser());
1678                            try {
1679                                ret = args.copyApk(mContainerService, true);
1680                            } catch (RemoteException e) {
1681                                Slog.e(TAG, "Could not contact the ContainerService");
1682                            }
1683                        } else {
1684                            broadcastPackageVerified(verificationId, originUri,
1685                                    PackageManager.VERIFICATION_REJECT,
1686                                    state.getInstallArgs().getUser());
1687                        }
1688
1689                        Trace.asyncTraceEnd(
1690                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1691
1692                        processPendingInstall(args, ret);
1693                        mHandler.sendEmptyMessage(MCS_UNBIND);
1694                    }
1695                    break;
1696                }
1697                case PACKAGE_VERIFIED: {
1698                    final int verificationId = msg.arg1;
1699
1700                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1701                    if (state == null) {
1702                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1703                        break;
1704                    }
1705
1706                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1707
1708                    state.setVerifierResponse(response.callerUid, response.code);
1709
1710                    if (state.isVerificationComplete()) {
1711                        mPendingVerification.remove(verificationId);
1712
1713                        final InstallArgs args = state.getInstallArgs();
1714                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1715
1716                        int ret;
1717                        if (state.isInstallAllowed()) {
1718                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1719                            broadcastPackageVerified(verificationId, originUri,
1720                                    response.code, state.getInstallArgs().getUser());
1721                            try {
1722                                ret = args.copyApk(mContainerService, true);
1723                            } catch (RemoteException e) {
1724                                Slog.e(TAG, "Could not contact the ContainerService");
1725                            }
1726                        } else {
1727                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1728                        }
1729
1730                        Trace.asyncTraceEnd(
1731                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1732
1733                        processPendingInstall(args, ret);
1734                        mHandler.sendEmptyMessage(MCS_UNBIND);
1735                    }
1736
1737                    break;
1738                }
1739                case START_INTENT_FILTER_VERIFICATIONS: {
1740                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1741                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1742                            params.replacing, params.pkg);
1743                    break;
1744                }
1745                case INTENT_FILTER_VERIFIED: {
1746                    final int verificationId = msg.arg1;
1747
1748                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1749                            verificationId);
1750                    if (state == null) {
1751                        Slog.w(TAG, "Invalid IntentFilter verification token "
1752                                + verificationId + " received");
1753                        break;
1754                    }
1755
1756                    final int userId = state.getUserId();
1757
1758                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1759                            "Processing IntentFilter verification with token:"
1760                            + verificationId + " and userId:" + userId);
1761
1762                    final IntentFilterVerificationResponse response =
1763                            (IntentFilterVerificationResponse) msg.obj;
1764
1765                    state.setVerifierResponse(response.callerUid, response.code);
1766
1767                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1768                            "IntentFilter verification with token:" + verificationId
1769                            + " and userId:" + userId
1770                            + " is settings verifier response with response code:"
1771                            + response.code);
1772
1773                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1774                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1775                                + response.getFailedDomainsString());
1776                    }
1777
1778                    if (state.isVerificationComplete()) {
1779                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1780                    } else {
1781                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1782                                "IntentFilter verification with token:" + verificationId
1783                                + " was not said to be complete");
1784                    }
1785
1786                    break;
1787                }
1788            }
1789        }
1790    }
1791
1792    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1793            boolean killApp, String[] grantedPermissions,
1794            boolean launchedForRestore, String installerPackage,
1795            IPackageInstallObserver2 installObserver) {
1796        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1797            // Send the removed broadcasts
1798            if (res.removedInfo != null) {
1799                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1800            }
1801
1802            // Now that we successfully installed the package, grant runtime
1803            // permissions if requested before broadcasting the install.
1804            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1805                    >= Build.VERSION_CODES.M) {
1806                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1807            }
1808
1809            final boolean update = res.removedInfo != null
1810                    && res.removedInfo.removedPackage != null;
1811
1812            // If this is the first time we have child packages for a disabled privileged
1813            // app that had no children, we grant requested runtime permissions to the new
1814            // children if the parent on the system image had them already granted.
1815            if (res.pkg.parentPackage != null) {
1816                synchronized (mPackages) {
1817                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1818                }
1819            }
1820
1821            synchronized (mPackages) {
1822                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1823            }
1824
1825            final String packageName = res.pkg.applicationInfo.packageName;
1826            Bundle extras = new Bundle(1);
1827            extras.putInt(Intent.EXTRA_UID, res.uid);
1828
1829            // Determine the set of users who are adding this package for
1830            // the first time vs. those who are seeing an update.
1831            int[] firstUsers = EMPTY_INT_ARRAY;
1832            int[] updateUsers = EMPTY_INT_ARRAY;
1833            if (res.origUsers == null || res.origUsers.length == 0) {
1834                firstUsers = res.newUsers;
1835            } else {
1836                for (int newUser : res.newUsers) {
1837                    boolean isNew = true;
1838                    for (int origUser : res.origUsers) {
1839                        if (origUser == newUser) {
1840                            isNew = false;
1841                            break;
1842                        }
1843                    }
1844                    if (isNew) {
1845                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1846                    } else {
1847                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1848                    }
1849                }
1850            }
1851
1852            // Send installed broadcasts if the install/update is not ephemeral
1853            if (!isEphemeral(res.pkg)) {
1854                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1855
1856                // Send added for users that see the package for the first time
1857                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1858                        extras, 0 /*flags*/, null /*targetPackage*/,
1859                        null /*finishedReceiver*/, firstUsers);
1860
1861                // Send added for users that don't see the package for the first time
1862                if (update) {
1863                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1864                }
1865                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1866                        extras, 0 /*flags*/, null /*targetPackage*/,
1867                        null /*finishedReceiver*/, updateUsers);
1868
1869                // Send replaced for users that don't see the package for the first time
1870                if (update) {
1871                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1872                            packageName, extras, 0 /*flags*/,
1873                            null /*targetPackage*/, null /*finishedReceiver*/,
1874                            updateUsers);
1875                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1876                            null /*package*/, null /*extras*/, 0 /*flags*/,
1877                            packageName /*targetPackage*/,
1878                            null /*finishedReceiver*/, updateUsers);
1879                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1880                    // First-install and we did a restore, so we're responsible for the
1881                    // first-launch broadcast.
1882                    if (DEBUG_BACKUP) {
1883                        Slog.i(TAG, "Post-restore of " + packageName
1884                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1885                    }
1886                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1887                }
1888
1889                // Send broadcast package appeared if forward locked/external for all users
1890                // treat asec-hosted packages like removable media on upgrade
1891                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1892                    if (DEBUG_INSTALL) {
1893                        Slog.i(TAG, "upgrading pkg " + res.pkg
1894                                + " is ASEC-hosted -> AVAILABLE");
1895                    }
1896                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1897                    ArrayList<String> pkgList = new ArrayList<>(1);
1898                    pkgList.add(packageName);
1899                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1900                }
1901            }
1902
1903            // Work that needs to happen on first install within each user
1904            if (firstUsers != null && firstUsers.length > 0) {
1905                synchronized (mPackages) {
1906                    for (int userId : firstUsers) {
1907                        // If this app is a browser and it's newly-installed for some
1908                        // users, clear any default-browser state in those users. The
1909                        // app's nature doesn't depend on the user, so we can just check
1910                        // its browser nature in any user and generalize.
1911                        if (packageIsBrowser(packageName, userId)) {
1912                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1913                        }
1914
1915                        // We may also need to apply pending (restored) runtime
1916                        // permission grants within these users.
1917                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1918                    }
1919                }
1920            }
1921
1922            // Log current value of "unknown sources" setting
1923            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1924                    getUnknownSourcesSettings());
1925
1926            // Force a gc to clear up things
1927            Runtime.getRuntime().gc();
1928
1929            // Remove the replaced package's older resources safely now
1930            // We delete after a gc for applications  on sdcard.
1931            if (res.removedInfo != null && res.removedInfo.args != null) {
1932                synchronized (mInstallLock) {
1933                    res.removedInfo.args.doPostDeleteLI(true);
1934                }
1935            }
1936        }
1937
1938        // If someone is watching installs - notify them
1939        if (installObserver != null) {
1940            try {
1941                Bundle extras = extrasForInstallResult(res);
1942                installObserver.onPackageInstalled(res.name, res.returnCode,
1943                        res.returnMsg, extras);
1944            } catch (RemoteException e) {
1945                Slog.i(TAG, "Observer no longer exists.");
1946            }
1947        }
1948    }
1949
1950    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1951            PackageParser.Package pkg) {
1952        if (pkg.parentPackage == null) {
1953            return;
1954        }
1955        if (pkg.requestedPermissions == null) {
1956            return;
1957        }
1958        final PackageSetting disabledSysParentPs = mSettings
1959                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1960        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1961                || !disabledSysParentPs.isPrivileged()
1962                || (disabledSysParentPs.childPackageNames != null
1963                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1964            return;
1965        }
1966        final int[] allUserIds = sUserManager.getUserIds();
1967        final int permCount = pkg.requestedPermissions.size();
1968        for (int i = 0; i < permCount; i++) {
1969            String permission = pkg.requestedPermissions.get(i);
1970            BasePermission bp = mSettings.mPermissions.get(permission);
1971            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1972                continue;
1973            }
1974            for (int userId : allUserIds) {
1975                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1976                        permission, userId)) {
1977                    grantRuntimePermission(pkg.packageName, permission, userId);
1978                }
1979            }
1980        }
1981    }
1982
1983    private StorageEventListener mStorageListener = new StorageEventListener() {
1984        @Override
1985        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1986            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1987                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1988                    final String volumeUuid = vol.getFsUuid();
1989
1990                    // Clean up any users or apps that were removed or recreated
1991                    // while this volume was missing
1992                    reconcileUsers(volumeUuid);
1993                    reconcileApps(volumeUuid);
1994
1995                    // Clean up any install sessions that expired or were
1996                    // cancelled while this volume was missing
1997                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1998
1999                    loadPrivatePackages(vol);
2000
2001                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2002                    unloadPrivatePackages(vol);
2003                }
2004            }
2005
2006            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2007                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2008                    updateExternalMediaStatus(true, false);
2009                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2010                    updateExternalMediaStatus(false, false);
2011                }
2012            }
2013        }
2014
2015        @Override
2016        public void onVolumeForgotten(String fsUuid) {
2017            if (TextUtils.isEmpty(fsUuid)) {
2018                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2019                return;
2020            }
2021
2022            // Remove any apps installed on the forgotten volume
2023            synchronized (mPackages) {
2024                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2025                for (PackageSetting ps : packages) {
2026                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2027                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2028                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2029                }
2030
2031                mSettings.onVolumeForgotten(fsUuid);
2032                mSettings.writeLPr();
2033            }
2034        }
2035    };
2036
2037    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2038            String[] grantedPermissions) {
2039        for (int userId : userIds) {
2040            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2041        }
2042
2043        // We could have touched GID membership, so flush out packages.list
2044        synchronized (mPackages) {
2045            mSettings.writePackageListLPr();
2046        }
2047    }
2048
2049    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2050            String[] grantedPermissions) {
2051        SettingBase sb = (SettingBase) pkg.mExtras;
2052        if (sb == null) {
2053            return;
2054        }
2055
2056        PermissionsState permissionsState = sb.getPermissionsState();
2057
2058        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2059                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2060
2061        for (String permission : pkg.requestedPermissions) {
2062            final BasePermission bp;
2063            synchronized (mPackages) {
2064                bp = mSettings.mPermissions.get(permission);
2065            }
2066            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2067                    && (grantedPermissions == null
2068                           || ArrayUtils.contains(grantedPermissions, permission))) {
2069                final int flags = permissionsState.getPermissionFlags(permission, userId);
2070                // Installer cannot change immutable permissions.
2071                if ((flags & immutableFlags) == 0) {
2072                    grantRuntimePermission(pkg.packageName, permission, userId);
2073                }
2074            }
2075        }
2076    }
2077
2078    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2079        Bundle extras = null;
2080        switch (res.returnCode) {
2081            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2082                extras = new Bundle();
2083                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2084                        res.origPermission);
2085                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2086                        res.origPackage);
2087                break;
2088            }
2089            case PackageManager.INSTALL_SUCCEEDED: {
2090                extras = new Bundle();
2091                extras.putBoolean(Intent.EXTRA_REPLACING,
2092                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2093                break;
2094            }
2095        }
2096        return extras;
2097    }
2098
2099    void scheduleWriteSettingsLocked() {
2100        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2101            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2102        }
2103    }
2104
2105    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2106        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2107        scheduleWritePackageRestrictionsLocked(userId);
2108    }
2109
2110    void scheduleWritePackageRestrictionsLocked(int userId) {
2111        final int[] userIds = (userId == UserHandle.USER_ALL)
2112                ? sUserManager.getUserIds() : new int[]{userId};
2113        for (int nextUserId : userIds) {
2114            if (!sUserManager.exists(nextUserId)) return;
2115            mDirtyUsers.add(nextUserId);
2116            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2117                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2118            }
2119        }
2120    }
2121
2122    public static PackageManagerService main(Context context, Installer installer,
2123            boolean factoryTest, boolean onlyCore) {
2124        // Self-check for initial settings.
2125        PackageManagerServiceCompilerMapping.checkProperties();
2126
2127        PackageManagerService m = new PackageManagerService(context, installer,
2128                factoryTest, onlyCore);
2129        m.enableSystemUserPackages();
2130        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2131        // disabled after already being started.
2132        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2133                UserHandle.USER_SYSTEM);
2134        ServiceManager.addService("package", m);
2135        return m;
2136    }
2137
2138    private void enableSystemUserPackages() {
2139        if (!UserManager.isSplitSystemUser()) {
2140            return;
2141        }
2142        // For system user, enable apps based on the following conditions:
2143        // - app is whitelisted or belong to one of these groups:
2144        //   -- system app which has no launcher icons
2145        //   -- system app which has INTERACT_ACROSS_USERS permission
2146        //   -- system IME app
2147        // - app is not in the blacklist
2148        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2149        Set<String> enableApps = new ArraySet<>();
2150        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2151                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2152                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2153        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2154        enableApps.addAll(wlApps);
2155        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2156                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2157        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2158        enableApps.removeAll(blApps);
2159        Log.i(TAG, "Applications installed for system user: " + enableApps);
2160        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2161                UserHandle.SYSTEM);
2162        final int allAppsSize = allAps.size();
2163        synchronized (mPackages) {
2164            for (int i = 0; i < allAppsSize; i++) {
2165                String pName = allAps.get(i);
2166                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2167                // Should not happen, but we shouldn't be failing if it does
2168                if (pkgSetting == null) {
2169                    continue;
2170                }
2171                boolean install = enableApps.contains(pName);
2172                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2173                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2174                            + " for system user");
2175                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2176                }
2177            }
2178        }
2179    }
2180
2181    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2182        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2183                Context.DISPLAY_SERVICE);
2184        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2185    }
2186
2187    public PackageManagerService(Context context, Installer installer,
2188            boolean factoryTest, boolean onlyCore) {
2189        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2190                SystemClock.uptimeMillis());
2191
2192        if (mSdkVersion <= 0) {
2193            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2194        }
2195
2196        mContext = context;
2197        mFactoryTest = factoryTest;
2198        mOnlyCore = onlyCore;
2199        mMetrics = new DisplayMetrics();
2200        mSettings = new Settings(mPackages);
2201        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2202                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2203        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2204                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2205        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2206                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2207        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2208                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2209        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2210                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2211        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2212                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2213
2214        String separateProcesses = SystemProperties.get("debug.separate_processes");
2215        if (separateProcesses != null && separateProcesses.length() > 0) {
2216            if ("*".equals(separateProcesses)) {
2217                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2218                mSeparateProcesses = null;
2219                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2220            } else {
2221                mDefParseFlags = 0;
2222                mSeparateProcesses = separateProcesses.split(",");
2223                Slog.w(TAG, "Running with debug.separate_processes: "
2224                        + separateProcesses);
2225            }
2226        } else {
2227            mDefParseFlags = 0;
2228            mSeparateProcesses = null;
2229        }
2230
2231        mInstaller = installer;
2232        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2233                "*dexopt*");
2234        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2235
2236        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2237                FgThread.get().getLooper());
2238
2239        getDefaultDisplayMetrics(context, mMetrics);
2240
2241        SystemConfig systemConfig = SystemConfig.getInstance();
2242        mGlobalGids = systemConfig.getGlobalGids();
2243        mSystemPermissions = systemConfig.getSystemPermissions();
2244        mAvailableFeatures = systemConfig.getAvailableFeatures();
2245
2246        synchronized (mInstallLock) {
2247        // writer
2248        synchronized (mPackages) {
2249            mHandlerThread = new ServiceThread(TAG,
2250                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2251            mHandlerThread.start();
2252            mHandler = new PackageHandler(mHandlerThread.getLooper());
2253            mProcessLoggingHandler = new ProcessLoggingHandler();
2254            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2255
2256            File dataDir = Environment.getDataDirectory();
2257            mAppInstallDir = new File(dataDir, "app");
2258            mAppLib32InstallDir = new File(dataDir, "app-lib");
2259            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2260            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2261            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2262
2263            sUserManager = new UserManagerService(context, this, mPackages);
2264
2265            // Propagate permission configuration in to package manager.
2266            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2267                    = systemConfig.getPermissions();
2268            for (int i=0; i<permConfig.size(); i++) {
2269                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2270                BasePermission bp = mSettings.mPermissions.get(perm.name);
2271                if (bp == null) {
2272                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2273                    mSettings.mPermissions.put(perm.name, bp);
2274                }
2275                if (perm.gids != null) {
2276                    bp.setGids(perm.gids, perm.perUser);
2277                }
2278            }
2279
2280            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2281            for (int i=0; i<libConfig.size(); i++) {
2282                mSharedLibraries.put(libConfig.keyAt(i),
2283                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2284            }
2285
2286            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2287
2288            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2289
2290            String customResolverActivity = Resources.getSystem().getString(
2291                    R.string.config_customResolverActivity);
2292            if (TextUtils.isEmpty(customResolverActivity)) {
2293                customResolverActivity = null;
2294            } else {
2295                mCustomResolverComponentName = ComponentName.unflattenFromString(
2296                        customResolverActivity);
2297            }
2298
2299            long startTime = SystemClock.uptimeMillis();
2300
2301            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2302                    startTime);
2303
2304            // Set flag to monitor and not change apk file paths when
2305            // scanning install directories.
2306            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2307
2308            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2309            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2310
2311            if (bootClassPath == null) {
2312                Slog.w(TAG, "No BOOTCLASSPATH found!");
2313            }
2314
2315            if (systemServerClassPath == null) {
2316                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2317            }
2318
2319            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2320            final String[] dexCodeInstructionSets =
2321                    getDexCodeInstructionSets(
2322                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2323
2324            /**
2325             * Ensure all external libraries have had dexopt run on them.
2326             */
2327            if (mSharedLibraries.size() > 0) {
2328                // NOTE: For now, we're compiling these system "shared libraries"
2329                // (and framework jars) into all available architectures. It's possible
2330                // to compile them only when we come across an app that uses them (there's
2331                // already logic for that in scanPackageLI) but that adds some complexity.
2332                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2333                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2334                        final String lib = libEntry.path;
2335                        if (lib == null) {
2336                            continue;
2337                        }
2338
2339                        try {
2340                            // Shared libraries do not have profiles so we perform a full
2341                            // AOT compilation (if needed).
2342                            int dexoptNeeded = DexFile.getDexOptNeeded(
2343                                    lib, dexCodeInstructionSet,
2344                                    getCompilerFilterForReason(REASON_SHARED_APK),
2345                                    false /* newProfile */);
2346                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2347                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2348                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2349                                        getCompilerFilterForReason(REASON_SHARED_APK),
2350                                        StorageManager.UUID_PRIVATE_INTERNAL,
2351                                        SKIP_SHARED_LIBRARY_CHECK);
2352                            }
2353                        } catch (FileNotFoundException e) {
2354                            Slog.w(TAG, "Library not found: " + lib);
2355                        } catch (IOException | InstallerException e) {
2356                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2357                                    + e.getMessage());
2358                        }
2359                    }
2360                }
2361            }
2362
2363            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2364
2365            final VersionInfo ver = mSettings.getInternalVersion();
2366            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2367
2368            // when upgrading from pre-M, promote system app permissions from install to runtime
2369            mPromoteSystemApps =
2370                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2371
2372            // save off the names of pre-existing system packages prior to scanning; we don't
2373            // want to automatically grant runtime permissions for new system apps
2374            if (mPromoteSystemApps) {
2375                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2376                while (pkgSettingIter.hasNext()) {
2377                    PackageSetting ps = pkgSettingIter.next();
2378                    if (isSystemApp(ps)) {
2379                        mExistingSystemPackages.add(ps.name);
2380                    }
2381                }
2382            }
2383
2384            // When upgrading from pre-N, we need to handle package extraction like first boot,
2385            // as there is no profiling data available.
2386            mIsPreNUpgrade = !mSettings.isNWorkDone();
2387            mSettings.setNWorkDone();
2388
2389            // Collect vendor overlay packages.
2390            // (Do this before scanning any apps.)
2391            // For security and version matching reason, only consider
2392            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2393            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2394            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2395                    | PackageParser.PARSE_IS_SYSTEM
2396                    | PackageParser.PARSE_IS_SYSTEM_DIR
2397                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2398
2399            // Find base frameworks (resource packages without code).
2400            scanDirTracedLI(frameworkDir, mDefParseFlags
2401                    | PackageParser.PARSE_IS_SYSTEM
2402                    | PackageParser.PARSE_IS_SYSTEM_DIR
2403                    | PackageParser.PARSE_IS_PRIVILEGED,
2404                    scanFlags | SCAN_NO_DEX, 0);
2405
2406            // Collected privileged system packages.
2407            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2408            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2409                    | PackageParser.PARSE_IS_SYSTEM
2410                    | PackageParser.PARSE_IS_SYSTEM_DIR
2411                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2412
2413            // Collect ordinary system packages.
2414            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2415            scanDirTracedLI(systemAppDir, mDefParseFlags
2416                    | PackageParser.PARSE_IS_SYSTEM
2417                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2418
2419            // Collect all vendor packages.
2420            File vendorAppDir = new File("/vendor/app");
2421            try {
2422                vendorAppDir = vendorAppDir.getCanonicalFile();
2423            } catch (IOException e) {
2424                // failed to look up canonical path, continue with original one
2425            }
2426            scanDirTracedLI(vendorAppDir, mDefParseFlags
2427                    | PackageParser.PARSE_IS_SYSTEM
2428                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2429
2430            // Collect all OEM packages.
2431            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2432            scanDirTracedLI(oemAppDir, mDefParseFlags
2433                    | PackageParser.PARSE_IS_SYSTEM
2434                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2435
2436            // Prune any system packages that no longer exist.
2437            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2438            if (!mOnlyCore) {
2439                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2440                while (psit.hasNext()) {
2441                    PackageSetting ps = psit.next();
2442
2443                    /*
2444                     * If this is not a system app, it can't be a
2445                     * disable system app.
2446                     */
2447                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2448                        continue;
2449                    }
2450
2451                    /*
2452                     * If the package is scanned, it's not erased.
2453                     */
2454                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2455                    if (scannedPkg != null) {
2456                        /*
2457                         * If the system app is both scanned and in the
2458                         * disabled packages list, then it must have been
2459                         * added via OTA. Remove it from the currently
2460                         * scanned package so the previously user-installed
2461                         * application can be scanned.
2462                         */
2463                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2464                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2465                                    + ps.name + "; removing system app.  Last known codePath="
2466                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2467                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2468                                    + scannedPkg.mVersionCode);
2469                            removePackageLI(scannedPkg, true);
2470                            mExpectingBetter.put(ps.name, ps.codePath);
2471                        }
2472
2473                        continue;
2474                    }
2475
2476                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2477                        psit.remove();
2478                        logCriticalInfo(Log.WARN, "System package " + ps.name
2479                                + " no longer exists; it's data will be wiped");
2480                        // Actual deletion of code and data will be handled by later
2481                        // reconciliation step
2482                    } else {
2483                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2484                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2485                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2486                        }
2487                    }
2488                }
2489            }
2490
2491            //look for any incomplete package installations
2492            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2493            for (int i = 0; i < deletePkgsList.size(); i++) {
2494                // Actual deletion of code and data will be handled by later
2495                // reconciliation step
2496                final String packageName = deletePkgsList.get(i).name;
2497                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2498                synchronized (mPackages) {
2499                    mSettings.removePackageLPw(packageName);
2500                }
2501            }
2502
2503            //delete tmp files
2504            deleteTempPackageFiles();
2505
2506            // Remove any shared userIDs that have no associated packages
2507            mSettings.pruneSharedUsersLPw();
2508
2509            if (!mOnlyCore) {
2510                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2511                        SystemClock.uptimeMillis());
2512                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2513
2514                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2515                        | PackageParser.PARSE_FORWARD_LOCK,
2516                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2517
2518                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2519                        | PackageParser.PARSE_IS_EPHEMERAL,
2520                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2521
2522                /**
2523                 * Remove disable package settings for any updated system
2524                 * apps that were removed via an OTA. If they're not a
2525                 * previously-updated app, remove them completely.
2526                 * Otherwise, just revoke their system-level permissions.
2527                 */
2528                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2529                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2530                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2531
2532                    String msg;
2533                    if (deletedPkg == null) {
2534                        msg = "Updated system package " + deletedAppName
2535                                + " no longer exists; it's data will be wiped";
2536                        // Actual deletion of code and data will be handled by later
2537                        // reconciliation step
2538                    } else {
2539                        msg = "Updated system app + " + deletedAppName
2540                                + " no longer present; removing system privileges for "
2541                                + deletedAppName;
2542
2543                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2544
2545                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2546                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2547                    }
2548                    logCriticalInfo(Log.WARN, msg);
2549                }
2550
2551                /**
2552                 * Make sure all system apps that we expected to appear on
2553                 * the userdata partition actually showed up. If they never
2554                 * appeared, crawl back and revive the system version.
2555                 */
2556                for (int i = 0; i < mExpectingBetter.size(); i++) {
2557                    final String packageName = mExpectingBetter.keyAt(i);
2558                    if (!mPackages.containsKey(packageName)) {
2559                        final File scanFile = mExpectingBetter.valueAt(i);
2560
2561                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2562                                + " but never showed up; reverting to system");
2563
2564                        int reparseFlags = mDefParseFlags;
2565                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2566                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2567                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2568                                    | PackageParser.PARSE_IS_PRIVILEGED;
2569                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2570                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2571                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2572                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2573                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2574                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2575                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2576                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2577                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2578                        } else {
2579                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2580                            continue;
2581                        }
2582
2583                        mSettings.enableSystemPackageLPw(packageName);
2584
2585                        try {
2586                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2587                        } catch (PackageManagerException e) {
2588                            Slog.e(TAG, "Failed to parse original system package: "
2589                                    + e.getMessage());
2590                        }
2591                    }
2592                }
2593            }
2594            mExpectingBetter.clear();
2595
2596            // Resolve protected action filters. Only the setup wizard is allowed to
2597            // have a high priority filter for these actions.
2598            mSetupWizardPackage = getSetupWizardPackageName();
2599            if (mProtectedFilters.size() > 0) {
2600                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2601                    Slog.i(TAG, "No setup wizard;"
2602                        + " All protected intents capped to priority 0");
2603                }
2604                for (ActivityIntentInfo filter : mProtectedFilters) {
2605                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2606                        if (DEBUG_FILTERS) {
2607                            Slog.i(TAG, "Found setup wizard;"
2608                                + " allow priority " + filter.getPriority() + ";"
2609                                + " package: " + filter.activity.info.packageName
2610                                + " activity: " + filter.activity.className
2611                                + " priority: " + filter.getPriority());
2612                        }
2613                        // skip setup wizard; allow it to keep the high priority filter
2614                        continue;
2615                    }
2616                    Slog.w(TAG, "Protected action; cap priority to 0;"
2617                            + " package: " + filter.activity.info.packageName
2618                            + " activity: " + filter.activity.className
2619                            + " origPrio: " + filter.getPriority());
2620                    filter.setPriority(0);
2621                }
2622            }
2623            mDeferProtectedFilters = false;
2624            mProtectedFilters.clear();
2625
2626            // Now that we know all of the shared libraries, update all clients to have
2627            // the correct library paths.
2628            updateAllSharedLibrariesLPw();
2629
2630            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2631                // NOTE: We ignore potential failures here during a system scan (like
2632                // the rest of the commands above) because there's precious little we
2633                // can do about it. A settings error is reported, though.
2634                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2635                        false /* boot complete */);
2636            }
2637
2638            // Now that we know all the packages we are keeping,
2639            // read and update their last usage times.
2640            mPackageUsage.readLP();
2641
2642            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2643                    SystemClock.uptimeMillis());
2644            Slog.i(TAG, "Time to scan packages: "
2645                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2646                    + " seconds");
2647
2648            // If the platform SDK has changed since the last time we booted,
2649            // we need to re-grant app permission to catch any new ones that
2650            // appear.  This is really a hack, and means that apps can in some
2651            // cases get permissions that the user didn't initially explicitly
2652            // allow...  it would be nice to have some better way to handle
2653            // this situation.
2654            int updateFlags = UPDATE_PERMISSIONS_ALL;
2655            if (ver.sdkVersion != mSdkVersion) {
2656                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2657                        + mSdkVersion + "; regranting permissions for internal storage");
2658                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2659            }
2660            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2661            ver.sdkVersion = mSdkVersion;
2662
2663            // If this is the first boot or an update from pre-M, and it is a normal
2664            // boot, then we need to initialize the default preferred apps across
2665            // all defined users.
2666            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2667                for (UserInfo user : sUserManager.getUsers(true)) {
2668                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2669                    applyFactoryDefaultBrowserLPw(user.id);
2670                    primeDomainVerificationsLPw(user.id);
2671                }
2672            }
2673
2674            // Prepare storage for system user really early during boot,
2675            // since core system apps like SettingsProvider and SystemUI
2676            // can't wait for user to start
2677            final int storageFlags;
2678            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2679                storageFlags = StorageManager.FLAG_STORAGE_DE;
2680            } else {
2681                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2682            }
2683            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2684                    storageFlags);
2685
2686            // If this is first boot after an OTA, and a normal boot, then
2687            // we need to clear code cache directories.
2688            if (mIsUpgrade && !onlyCore) {
2689                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2690                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2691                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2692                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2693                        // No apps are running this early, so no need to freeze
2694                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2695                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2696                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2697                    }
2698                    clearAppProfilesLIF(ps.pkg);
2699                }
2700                ver.fingerprint = Build.FINGERPRINT;
2701            }
2702
2703            checkDefaultBrowser();
2704
2705            // clear only after permissions and other defaults have been updated
2706            mExistingSystemPackages.clear();
2707            mPromoteSystemApps = false;
2708
2709            // All the changes are done during package scanning.
2710            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2711
2712            // can downgrade to reader
2713            mSettings.writeLPr();
2714
2715            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2716                    SystemClock.uptimeMillis());
2717
2718            if (!mOnlyCore) {
2719                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2720                mRequiredInstallerPackage = getRequiredInstallerLPr();
2721                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2722                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2723                        mIntentFilterVerifierComponent);
2724                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2725                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2726                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2727                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2728            } else {
2729                mRequiredVerifierPackage = null;
2730                mRequiredInstallerPackage = null;
2731                mIntentFilterVerifierComponent = null;
2732                mIntentFilterVerifier = null;
2733                mServicesSystemSharedLibraryPackageName = null;
2734                mSharedSystemSharedLibraryPackageName = null;
2735            }
2736
2737            mInstallerService = new PackageInstallerService(context, this);
2738
2739            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2740            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2741            // both the installer and resolver must be present to enable ephemeral
2742            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2743                if (DEBUG_EPHEMERAL) {
2744                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2745                            + " installer:" + ephemeralInstallerComponent);
2746                }
2747                mEphemeralResolverComponent = ephemeralResolverComponent;
2748                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2749                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2750                mEphemeralResolverConnection =
2751                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2752            } else {
2753                if (DEBUG_EPHEMERAL) {
2754                    final String missingComponent =
2755                            (ephemeralResolverComponent == null)
2756                            ? (ephemeralInstallerComponent == null)
2757                                    ? "resolver and installer"
2758                                    : "resolver"
2759                            : "installer";
2760                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2761                }
2762                mEphemeralResolverComponent = null;
2763                mEphemeralInstallerComponent = null;
2764                mEphemeralResolverConnection = null;
2765            }
2766
2767            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2768        } // synchronized (mPackages)
2769        } // synchronized (mInstallLock)
2770
2771        // Now after opening every single application zip, make sure they
2772        // are all flushed.  Not really needed, but keeps things nice and
2773        // tidy.
2774        Runtime.getRuntime().gc();
2775
2776        // The initial scanning above does many calls into installd while
2777        // holding the mPackages lock, but we're mostly interested in yelling
2778        // once we have a booted system.
2779        mInstaller.setWarnIfHeld(mPackages);
2780
2781        // Expose private service for system components to use.
2782        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2783    }
2784
2785    @Override
2786    public boolean isFirstBoot() {
2787        return !mRestoredSettings;
2788    }
2789
2790    @Override
2791    public boolean isOnlyCoreApps() {
2792        return mOnlyCore;
2793    }
2794
2795    @Override
2796    public boolean isUpgrade() {
2797        return mIsUpgrade;
2798    }
2799
2800    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2801        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2802
2803        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2804                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2805                UserHandle.USER_SYSTEM);
2806        if (matches.size() == 1) {
2807            return matches.get(0).getComponentInfo().packageName;
2808        } else {
2809            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2810            return null;
2811        }
2812    }
2813
2814    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2815        synchronized (mPackages) {
2816            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2817            if (libraryEntry == null) {
2818                throw new IllegalStateException("Missing required shared library:" + libraryName);
2819            }
2820            return libraryEntry.apk;
2821        }
2822    }
2823
2824    private @NonNull String getRequiredInstallerLPr() {
2825        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2826        intent.addCategory(Intent.CATEGORY_DEFAULT);
2827        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2828
2829        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2830                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2831                UserHandle.USER_SYSTEM);
2832        if (matches.size() == 1) {
2833            ResolveInfo resolveInfo = matches.get(0);
2834            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2835                throw new RuntimeException("The installer must be a privileged app");
2836            }
2837            return matches.get(0).getComponentInfo().packageName;
2838        } else {
2839            throw new RuntimeException("There must be exactly one installer; found " + matches);
2840        }
2841    }
2842
2843    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2844        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2845
2846        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2847                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2848                UserHandle.USER_SYSTEM);
2849        ResolveInfo best = null;
2850        final int N = matches.size();
2851        for (int i = 0; i < N; i++) {
2852            final ResolveInfo cur = matches.get(i);
2853            final String packageName = cur.getComponentInfo().packageName;
2854            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2855                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2856                continue;
2857            }
2858
2859            if (best == null || cur.priority > best.priority) {
2860                best = cur;
2861            }
2862        }
2863
2864        if (best != null) {
2865            return best.getComponentInfo().getComponentName();
2866        } else {
2867            throw new RuntimeException("There must be at least one intent filter verifier");
2868        }
2869    }
2870
2871    private @Nullable ComponentName getEphemeralResolverLPr() {
2872        final String[] packageArray =
2873                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2874        if (packageArray.length == 0) {
2875            if (DEBUG_EPHEMERAL) {
2876                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2877            }
2878            return null;
2879        }
2880
2881        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2882        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2883                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2884                UserHandle.USER_SYSTEM);
2885
2886        final int N = resolvers.size();
2887        if (N == 0) {
2888            if (DEBUG_EPHEMERAL) {
2889                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2890            }
2891            return null;
2892        }
2893
2894        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2895        for (int i = 0; i < N; i++) {
2896            final ResolveInfo info = resolvers.get(i);
2897
2898            if (info.serviceInfo == null) {
2899                continue;
2900            }
2901
2902            final String packageName = info.serviceInfo.packageName;
2903            if (!possiblePackages.contains(packageName)) {
2904                if (DEBUG_EPHEMERAL) {
2905                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2906                            + " pkg: " + packageName + ", info:" + info);
2907                }
2908                continue;
2909            }
2910
2911            if (DEBUG_EPHEMERAL) {
2912                Slog.v(TAG, "Ephemeral resolver found;"
2913                        + " pkg: " + packageName + ", info:" + info);
2914            }
2915            return new ComponentName(packageName, info.serviceInfo.name);
2916        }
2917        if (DEBUG_EPHEMERAL) {
2918            Slog.v(TAG, "Ephemeral resolver NOT found");
2919        }
2920        return null;
2921    }
2922
2923    private @Nullable ComponentName getEphemeralInstallerLPr() {
2924        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2925        intent.addCategory(Intent.CATEGORY_DEFAULT);
2926        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2927
2928        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2929                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2930                UserHandle.USER_SYSTEM);
2931        if (matches.size() == 0) {
2932            return null;
2933        } else if (matches.size() == 1) {
2934            return matches.get(0).getComponentInfo().getComponentName();
2935        } else {
2936            throw new RuntimeException(
2937                    "There must be at most one ephemeral installer; found " + matches);
2938        }
2939    }
2940
2941    private void primeDomainVerificationsLPw(int userId) {
2942        if (DEBUG_DOMAIN_VERIFICATION) {
2943            Slog.d(TAG, "Priming domain verifications in user " + userId);
2944        }
2945
2946        SystemConfig systemConfig = SystemConfig.getInstance();
2947        ArraySet<String> packages = systemConfig.getLinkedApps();
2948        ArraySet<String> domains = new ArraySet<String>();
2949
2950        for (String packageName : packages) {
2951            PackageParser.Package pkg = mPackages.get(packageName);
2952            if (pkg != null) {
2953                if (!pkg.isSystemApp()) {
2954                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2955                    continue;
2956                }
2957
2958                domains.clear();
2959                for (PackageParser.Activity a : pkg.activities) {
2960                    for (ActivityIntentInfo filter : a.intents) {
2961                        if (hasValidDomains(filter)) {
2962                            domains.addAll(filter.getHostsList());
2963                        }
2964                    }
2965                }
2966
2967                if (domains.size() > 0) {
2968                    if (DEBUG_DOMAIN_VERIFICATION) {
2969                        Slog.v(TAG, "      + " + packageName);
2970                    }
2971                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2972                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2973                    // and then 'always' in the per-user state actually used for intent resolution.
2974                    final IntentFilterVerificationInfo ivi;
2975                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2976                            new ArrayList<String>(domains));
2977                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2978                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2979                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2980                } else {
2981                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2982                            + "' does not handle web links");
2983                }
2984            } else {
2985                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2986            }
2987        }
2988
2989        scheduleWritePackageRestrictionsLocked(userId);
2990        scheduleWriteSettingsLocked();
2991    }
2992
2993    private void applyFactoryDefaultBrowserLPw(int userId) {
2994        // The default browser app's package name is stored in a string resource,
2995        // with a product-specific overlay used for vendor customization.
2996        String browserPkg = mContext.getResources().getString(
2997                com.android.internal.R.string.default_browser);
2998        if (!TextUtils.isEmpty(browserPkg)) {
2999            // non-empty string => required to be a known package
3000            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3001            if (ps == null) {
3002                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3003                browserPkg = null;
3004            } else {
3005                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3006            }
3007        }
3008
3009        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3010        // default.  If there's more than one, just leave everything alone.
3011        if (browserPkg == null) {
3012            calculateDefaultBrowserLPw(userId);
3013        }
3014    }
3015
3016    private void calculateDefaultBrowserLPw(int userId) {
3017        List<String> allBrowsers = resolveAllBrowserApps(userId);
3018        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3019        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3020    }
3021
3022    private List<String> resolveAllBrowserApps(int userId) {
3023        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3024        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3025                PackageManager.MATCH_ALL, userId);
3026
3027        final int count = list.size();
3028        List<String> result = new ArrayList<String>(count);
3029        for (int i=0; i<count; i++) {
3030            ResolveInfo info = list.get(i);
3031            if (info.activityInfo == null
3032                    || !info.handleAllWebDataURI
3033                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3034                    || result.contains(info.activityInfo.packageName)) {
3035                continue;
3036            }
3037            result.add(info.activityInfo.packageName);
3038        }
3039
3040        return result;
3041    }
3042
3043    private boolean packageIsBrowser(String packageName, int userId) {
3044        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3045                PackageManager.MATCH_ALL, userId);
3046        final int N = list.size();
3047        for (int i = 0; i < N; i++) {
3048            ResolveInfo info = list.get(i);
3049            if (packageName.equals(info.activityInfo.packageName)) {
3050                return true;
3051            }
3052        }
3053        return false;
3054    }
3055
3056    private void checkDefaultBrowser() {
3057        final int myUserId = UserHandle.myUserId();
3058        final String packageName = getDefaultBrowserPackageName(myUserId);
3059        if (packageName != null) {
3060            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3061            if (info == null) {
3062                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3063                synchronized (mPackages) {
3064                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3065                }
3066            }
3067        }
3068    }
3069
3070    @Override
3071    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3072            throws RemoteException {
3073        try {
3074            return super.onTransact(code, data, reply, flags);
3075        } catch (RuntimeException e) {
3076            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3077                Slog.wtf(TAG, "Package Manager Crash", e);
3078            }
3079            throw e;
3080        }
3081    }
3082
3083    static int[] appendInts(int[] cur, int[] add) {
3084        if (add == null) return cur;
3085        if (cur == null) return add;
3086        final int N = add.length;
3087        for (int i=0; i<N; i++) {
3088            cur = appendInt(cur, add[i]);
3089        }
3090        return cur;
3091    }
3092
3093    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3094        if (!sUserManager.exists(userId)) return null;
3095        if (ps == null) {
3096            return null;
3097        }
3098        final PackageParser.Package p = ps.pkg;
3099        if (p == null) {
3100            return null;
3101        }
3102
3103        final PermissionsState permissionsState = ps.getPermissionsState();
3104
3105        final int[] gids = permissionsState.computeGids(userId);
3106        final Set<String> permissions = permissionsState.getPermissions(userId);
3107        final PackageUserState state = ps.readUserState(userId);
3108
3109        return PackageParser.generatePackageInfo(p, gids, flags,
3110                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3111    }
3112
3113    @Override
3114    public void checkPackageStartable(String packageName, int userId) {
3115        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3116
3117        synchronized (mPackages) {
3118            final PackageSetting ps = mSettings.mPackages.get(packageName);
3119            if (ps == null) {
3120                throw new SecurityException("Package " + packageName + " was not found!");
3121            }
3122
3123            if (!ps.getInstalled(userId)) {
3124                throw new SecurityException(
3125                        "Package " + packageName + " was not installed for user " + userId + "!");
3126            }
3127
3128            if (mSafeMode && !ps.isSystem()) {
3129                throw new SecurityException("Package " + packageName + " not a system app!");
3130            }
3131
3132            if (mFrozenPackages.contains(packageName)) {
3133                throw new SecurityException("Package " + packageName + " is currently frozen!");
3134            }
3135
3136            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3137                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3138                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3139            }
3140        }
3141    }
3142
3143    @Override
3144    public boolean isPackageAvailable(String packageName, int userId) {
3145        if (!sUserManager.exists(userId)) return false;
3146        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3147                false /* requireFullPermission */, false /* checkShell */, "is package available");
3148        synchronized (mPackages) {
3149            PackageParser.Package p = mPackages.get(packageName);
3150            if (p != null) {
3151                final PackageSetting ps = (PackageSetting) p.mExtras;
3152                if (ps != null) {
3153                    final PackageUserState state = ps.readUserState(userId);
3154                    if (state != null) {
3155                        return PackageParser.isAvailable(state);
3156                    }
3157                }
3158            }
3159        }
3160        return false;
3161    }
3162
3163    @Override
3164    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3165        if (!sUserManager.exists(userId)) return null;
3166        flags = updateFlagsForPackage(flags, userId, packageName);
3167        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3168                false /* requireFullPermission */, false /* checkShell */, "get package info");
3169        // reader
3170        synchronized (mPackages) {
3171            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3172            PackageParser.Package p = null;
3173            if (matchFactoryOnly) {
3174                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3175                if (ps != null) {
3176                    return generatePackageInfo(ps, flags, userId);
3177                }
3178            }
3179            if (p == null) {
3180                p = mPackages.get(packageName);
3181                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3182                    return null;
3183                }
3184            }
3185            if (DEBUG_PACKAGE_INFO)
3186                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3187            if (p != null) {
3188                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3189            }
3190            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3191                final PackageSetting ps = mSettings.mPackages.get(packageName);
3192                return generatePackageInfo(ps, flags, userId);
3193            }
3194        }
3195        return null;
3196    }
3197
3198    @Override
3199    public String[] currentToCanonicalPackageNames(String[] names) {
3200        String[] out = new String[names.length];
3201        // reader
3202        synchronized (mPackages) {
3203            for (int i=names.length-1; i>=0; i--) {
3204                PackageSetting ps = mSettings.mPackages.get(names[i]);
3205                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3206            }
3207        }
3208        return out;
3209    }
3210
3211    @Override
3212    public String[] canonicalToCurrentPackageNames(String[] names) {
3213        String[] out = new String[names.length];
3214        // reader
3215        synchronized (mPackages) {
3216            for (int i=names.length-1; i>=0; i--) {
3217                String cur = mSettings.mRenamedPackages.get(names[i]);
3218                out[i] = cur != null ? cur : names[i];
3219            }
3220        }
3221        return out;
3222    }
3223
3224    @Override
3225    public int getPackageUid(String packageName, int flags, int userId) {
3226        if (!sUserManager.exists(userId)) return -1;
3227        flags = updateFlagsForPackage(flags, userId, packageName);
3228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3229                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3230
3231        // reader
3232        synchronized (mPackages) {
3233            final PackageParser.Package p = mPackages.get(packageName);
3234            if (p != null && p.isMatch(flags)) {
3235                return UserHandle.getUid(userId, p.applicationInfo.uid);
3236            }
3237            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3238                final PackageSetting ps = mSettings.mPackages.get(packageName);
3239                if (ps != null && ps.isMatch(flags)) {
3240                    return UserHandle.getUid(userId, ps.appId);
3241                }
3242            }
3243        }
3244
3245        return -1;
3246    }
3247
3248    @Override
3249    public int[] getPackageGids(String packageName, int flags, int userId) {
3250        if (!sUserManager.exists(userId)) return null;
3251        flags = updateFlagsForPackage(flags, userId, packageName);
3252        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3253                false /* requireFullPermission */, false /* checkShell */,
3254                "getPackageGids");
3255
3256        // reader
3257        synchronized (mPackages) {
3258            final PackageParser.Package p = mPackages.get(packageName);
3259            if (p != null && p.isMatch(flags)) {
3260                PackageSetting ps = (PackageSetting) p.mExtras;
3261                return ps.getPermissionsState().computeGids(userId);
3262            }
3263            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3264                final PackageSetting ps = mSettings.mPackages.get(packageName);
3265                if (ps != null && ps.isMatch(flags)) {
3266                    return ps.getPermissionsState().computeGids(userId);
3267                }
3268            }
3269        }
3270
3271        return null;
3272    }
3273
3274    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3275        if (bp.perm != null) {
3276            return PackageParser.generatePermissionInfo(bp.perm, flags);
3277        }
3278        PermissionInfo pi = new PermissionInfo();
3279        pi.name = bp.name;
3280        pi.packageName = bp.sourcePackage;
3281        pi.nonLocalizedLabel = bp.name;
3282        pi.protectionLevel = bp.protectionLevel;
3283        return pi;
3284    }
3285
3286    @Override
3287    public PermissionInfo getPermissionInfo(String name, int flags) {
3288        // reader
3289        synchronized (mPackages) {
3290            final BasePermission p = mSettings.mPermissions.get(name);
3291            if (p != null) {
3292                return generatePermissionInfo(p, flags);
3293            }
3294            return null;
3295        }
3296    }
3297
3298    @Override
3299    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3300            int flags) {
3301        // reader
3302        synchronized (mPackages) {
3303            if (group != null && !mPermissionGroups.containsKey(group)) {
3304                // This is thrown as NameNotFoundException
3305                return null;
3306            }
3307
3308            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3309            for (BasePermission p : mSettings.mPermissions.values()) {
3310                if (group == null) {
3311                    if (p.perm == null || p.perm.info.group == null) {
3312                        out.add(generatePermissionInfo(p, flags));
3313                    }
3314                } else {
3315                    if (p.perm != null && group.equals(p.perm.info.group)) {
3316                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3317                    }
3318                }
3319            }
3320            return new ParceledListSlice<>(out);
3321        }
3322    }
3323
3324    @Override
3325    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3326        // reader
3327        synchronized (mPackages) {
3328            return PackageParser.generatePermissionGroupInfo(
3329                    mPermissionGroups.get(name), flags);
3330        }
3331    }
3332
3333    @Override
3334    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3335        // reader
3336        synchronized (mPackages) {
3337            final int N = mPermissionGroups.size();
3338            ArrayList<PermissionGroupInfo> out
3339                    = new ArrayList<PermissionGroupInfo>(N);
3340            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3341                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3342            }
3343            return new ParceledListSlice<>(out);
3344        }
3345    }
3346
3347    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3348            int userId) {
3349        if (!sUserManager.exists(userId)) return null;
3350        PackageSetting ps = mSettings.mPackages.get(packageName);
3351        if (ps != null) {
3352            if (ps.pkg == null) {
3353                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3354                if (pInfo != null) {
3355                    return pInfo.applicationInfo;
3356                }
3357                return null;
3358            }
3359            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3360                    ps.readUserState(userId), userId);
3361        }
3362        return null;
3363    }
3364
3365    @Override
3366    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3367        if (!sUserManager.exists(userId)) return null;
3368        flags = updateFlagsForApplication(flags, userId, packageName);
3369        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3370                false /* requireFullPermission */, false /* checkShell */, "get application info");
3371        // writer
3372        synchronized (mPackages) {
3373            PackageParser.Package p = mPackages.get(packageName);
3374            if (DEBUG_PACKAGE_INFO) Log.v(
3375                    TAG, "getApplicationInfo " + packageName
3376                    + ": " + p);
3377            if (p != null) {
3378                PackageSetting ps = mSettings.mPackages.get(packageName);
3379                if (ps == null) return null;
3380                // Note: isEnabledLP() does not apply here - always return info
3381                return PackageParser.generateApplicationInfo(
3382                        p, flags, ps.readUserState(userId), userId);
3383            }
3384            if ("android".equals(packageName)||"system".equals(packageName)) {
3385                return mAndroidApplication;
3386            }
3387            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3388                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3389            }
3390        }
3391        return null;
3392    }
3393
3394    @Override
3395    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3396            final IPackageDataObserver observer) {
3397        mContext.enforceCallingOrSelfPermission(
3398                android.Manifest.permission.CLEAR_APP_CACHE, null);
3399        // Queue up an async operation since clearing cache may take a little while.
3400        mHandler.post(new Runnable() {
3401            public void run() {
3402                mHandler.removeCallbacks(this);
3403                boolean success = true;
3404                synchronized (mInstallLock) {
3405                    try {
3406                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3407                    } catch (InstallerException e) {
3408                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3409                        success = false;
3410                    }
3411                }
3412                if (observer != null) {
3413                    try {
3414                        observer.onRemoveCompleted(null, success);
3415                    } catch (RemoteException e) {
3416                        Slog.w(TAG, "RemoveException when invoking call back");
3417                    }
3418                }
3419            }
3420        });
3421    }
3422
3423    @Override
3424    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3425            final IntentSender pi) {
3426        mContext.enforceCallingOrSelfPermission(
3427                android.Manifest.permission.CLEAR_APP_CACHE, null);
3428        // Queue up an async operation since clearing cache may take a little while.
3429        mHandler.post(new Runnable() {
3430            public void run() {
3431                mHandler.removeCallbacks(this);
3432                boolean success = true;
3433                synchronized (mInstallLock) {
3434                    try {
3435                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3436                    } catch (InstallerException e) {
3437                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3438                        success = false;
3439                    }
3440                }
3441                if(pi != null) {
3442                    try {
3443                        // Callback via pending intent
3444                        int code = success ? 1 : 0;
3445                        pi.sendIntent(null, code, null,
3446                                null, null);
3447                    } catch (SendIntentException e1) {
3448                        Slog.i(TAG, "Failed to send pending intent");
3449                    }
3450                }
3451            }
3452        });
3453    }
3454
3455    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3456        synchronized (mInstallLock) {
3457            try {
3458                mInstaller.freeCache(volumeUuid, freeStorageSize);
3459            } catch (InstallerException e) {
3460                throw new IOException("Failed to free enough space", e);
3461            }
3462        }
3463    }
3464
3465    /**
3466     * Return if the user key is currently unlocked.
3467     */
3468    private boolean isUserKeyUnlocked(int userId) {
3469        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3470            final IMountService mount = IMountService.Stub
3471                    .asInterface(ServiceManager.getService("mount"));
3472            if (mount == null) {
3473                Slog.w(TAG, "Early during boot, assuming locked");
3474                return false;
3475            }
3476            final long token = Binder.clearCallingIdentity();
3477            try {
3478                return mount.isUserKeyUnlocked(userId);
3479            } catch (RemoteException e) {
3480                throw e.rethrowAsRuntimeException();
3481            } finally {
3482                Binder.restoreCallingIdentity(token);
3483            }
3484        } else {
3485            return true;
3486        }
3487    }
3488
3489    /**
3490     * Update given flags based on encryption status of current user.
3491     */
3492    private int updateFlags(int flags, int userId) {
3493        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3494                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3495            // Caller expressed an explicit opinion about what encryption
3496            // aware/unaware components they want to see, so fall through and
3497            // give them what they want
3498        } else {
3499            // Caller expressed no opinion, so match based on user state
3500            if (isUserKeyUnlocked(userId)) {
3501                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3502            } else {
3503                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3504            }
3505        }
3506        return flags;
3507    }
3508
3509    /**
3510     * Update given flags when being used to request {@link PackageInfo}.
3511     */
3512    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3513        boolean triaged = true;
3514        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3515                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3516            // Caller is asking for component details, so they'd better be
3517            // asking for specific encryption matching behavior, or be triaged
3518            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3519                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3520                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3521                triaged = false;
3522            }
3523        }
3524        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3525                | PackageManager.MATCH_SYSTEM_ONLY
3526                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3527            triaged = false;
3528        }
3529        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3530            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3531                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3532        }
3533        return updateFlags(flags, userId);
3534    }
3535
3536    /**
3537     * Update given flags when being used to request {@link ApplicationInfo}.
3538     */
3539    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3540        return updateFlagsForPackage(flags, userId, cookie);
3541    }
3542
3543    /**
3544     * Update given flags when being used to request {@link ComponentInfo}.
3545     */
3546    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3547        if (cookie instanceof Intent) {
3548            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3549                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3550            }
3551        }
3552
3553        boolean triaged = true;
3554        // Caller is asking for component details, so they'd better be
3555        // asking for specific encryption matching behavior, or be triaged
3556        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3557                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3558                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3559            triaged = false;
3560        }
3561        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3562            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3563                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3564        }
3565
3566        return updateFlags(flags, userId);
3567    }
3568
3569    /**
3570     * Update given flags when being used to request {@link ResolveInfo}.
3571     */
3572    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3573        // Safe mode means we shouldn't match any third-party components
3574        if (mSafeMode) {
3575            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3576        }
3577
3578        return updateFlagsForComponent(flags, userId, cookie);
3579    }
3580
3581    @Override
3582    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3583        if (!sUserManager.exists(userId)) return null;
3584        flags = updateFlagsForComponent(flags, userId, component);
3585        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3586                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3587        synchronized (mPackages) {
3588            PackageParser.Activity a = mActivities.mActivities.get(component);
3589
3590            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3591            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3592                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3593                if (ps == null) return null;
3594                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3595                        userId);
3596            }
3597            if (mResolveComponentName.equals(component)) {
3598                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3599                        new PackageUserState(), userId);
3600            }
3601        }
3602        return null;
3603    }
3604
3605    @Override
3606    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3607            String resolvedType) {
3608        synchronized (mPackages) {
3609            if (component.equals(mResolveComponentName)) {
3610                // The resolver supports EVERYTHING!
3611                return true;
3612            }
3613            PackageParser.Activity a = mActivities.mActivities.get(component);
3614            if (a == null) {
3615                return false;
3616            }
3617            for (int i=0; i<a.intents.size(); i++) {
3618                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3619                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3620                    return true;
3621                }
3622            }
3623            return false;
3624        }
3625    }
3626
3627    @Override
3628    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3629        if (!sUserManager.exists(userId)) return null;
3630        flags = updateFlagsForComponent(flags, userId, component);
3631        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3632                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3633        synchronized (mPackages) {
3634            PackageParser.Activity a = mReceivers.mActivities.get(component);
3635            if (DEBUG_PACKAGE_INFO) Log.v(
3636                TAG, "getReceiverInfo " + component + ": " + a);
3637            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3638                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3639                if (ps == null) return null;
3640                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3641                        userId);
3642            }
3643        }
3644        return null;
3645    }
3646
3647    @Override
3648    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3649        if (!sUserManager.exists(userId)) return null;
3650        flags = updateFlagsForComponent(flags, userId, component);
3651        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3652                false /* requireFullPermission */, false /* checkShell */, "get service info");
3653        synchronized (mPackages) {
3654            PackageParser.Service s = mServices.mServices.get(component);
3655            if (DEBUG_PACKAGE_INFO) Log.v(
3656                TAG, "getServiceInfo " + component + ": " + s);
3657            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3658                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3659                if (ps == null) return null;
3660                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3661                        userId);
3662            }
3663        }
3664        return null;
3665    }
3666
3667    @Override
3668    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3669        if (!sUserManager.exists(userId)) return null;
3670        flags = updateFlagsForComponent(flags, userId, component);
3671        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3672                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3673        synchronized (mPackages) {
3674            PackageParser.Provider p = mProviders.mProviders.get(component);
3675            if (DEBUG_PACKAGE_INFO) Log.v(
3676                TAG, "getProviderInfo " + component + ": " + p);
3677            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3678                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3679                if (ps == null) return null;
3680                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3681                        userId);
3682            }
3683        }
3684        return null;
3685    }
3686
3687    @Override
3688    public String[] getSystemSharedLibraryNames() {
3689        Set<String> libSet;
3690        synchronized (mPackages) {
3691            libSet = mSharedLibraries.keySet();
3692            int size = libSet.size();
3693            if (size > 0) {
3694                String[] libs = new String[size];
3695                libSet.toArray(libs);
3696                return libs;
3697            }
3698        }
3699        return null;
3700    }
3701
3702    @Override
3703    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3704        synchronized (mPackages) {
3705            return mServicesSystemSharedLibraryPackageName;
3706        }
3707    }
3708
3709    @Override
3710    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3711        synchronized (mPackages) {
3712            return mSharedSystemSharedLibraryPackageName;
3713        }
3714    }
3715
3716    @Override
3717    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3718        synchronized (mPackages) {
3719            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3720
3721            final FeatureInfo fi = new FeatureInfo();
3722            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3723                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3724            res.add(fi);
3725
3726            return new ParceledListSlice<>(res);
3727        }
3728    }
3729
3730    @Override
3731    public boolean hasSystemFeature(String name, int version) {
3732        synchronized (mPackages) {
3733            final FeatureInfo feat = mAvailableFeatures.get(name);
3734            if (feat == null) {
3735                return false;
3736            } else {
3737                return feat.version >= version;
3738            }
3739        }
3740    }
3741
3742    @Override
3743    public int checkPermission(String permName, String pkgName, int userId) {
3744        if (!sUserManager.exists(userId)) {
3745            return PackageManager.PERMISSION_DENIED;
3746        }
3747
3748        synchronized (mPackages) {
3749            final PackageParser.Package p = mPackages.get(pkgName);
3750            if (p != null && p.mExtras != null) {
3751                final PackageSetting ps = (PackageSetting) p.mExtras;
3752                final PermissionsState permissionsState = ps.getPermissionsState();
3753                if (permissionsState.hasPermission(permName, userId)) {
3754                    return PackageManager.PERMISSION_GRANTED;
3755                }
3756                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3757                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3758                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3759                    return PackageManager.PERMISSION_GRANTED;
3760                }
3761            }
3762        }
3763
3764        return PackageManager.PERMISSION_DENIED;
3765    }
3766
3767    @Override
3768    public int checkUidPermission(String permName, int uid) {
3769        final int userId = UserHandle.getUserId(uid);
3770
3771        if (!sUserManager.exists(userId)) {
3772            return PackageManager.PERMISSION_DENIED;
3773        }
3774
3775        synchronized (mPackages) {
3776            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3777            if (obj != null) {
3778                final SettingBase ps = (SettingBase) obj;
3779                final PermissionsState permissionsState = ps.getPermissionsState();
3780                if (permissionsState.hasPermission(permName, userId)) {
3781                    return PackageManager.PERMISSION_GRANTED;
3782                }
3783                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3784                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3785                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3786                    return PackageManager.PERMISSION_GRANTED;
3787                }
3788            } else {
3789                ArraySet<String> perms = mSystemPermissions.get(uid);
3790                if (perms != null) {
3791                    if (perms.contains(permName)) {
3792                        return PackageManager.PERMISSION_GRANTED;
3793                    }
3794                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3795                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3796                        return PackageManager.PERMISSION_GRANTED;
3797                    }
3798                }
3799            }
3800        }
3801
3802        return PackageManager.PERMISSION_DENIED;
3803    }
3804
3805    @Override
3806    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3807        if (UserHandle.getCallingUserId() != userId) {
3808            mContext.enforceCallingPermission(
3809                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3810                    "isPermissionRevokedByPolicy for user " + userId);
3811        }
3812
3813        if (checkPermission(permission, packageName, userId)
3814                == PackageManager.PERMISSION_GRANTED) {
3815            return false;
3816        }
3817
3818        final long identity = Binder.clearCallingIdentity();
3819        try {
3820            final int flags = getPermissionFlags(permission, packageName, userId);
3821            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3822        } finally {
3823            Binder.restoreCallingIdentity(identity);
3824        }
3825    }
3826
3827    @Override
3828    public String getPermissionControllerPackageName() {
3829        synchronized (mPackages) {
3830            return mRequiredInstallerPackage;
3831        }
3832    }
3833
3834    /**
3835     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3836     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3837     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3838     * @param message the message to log on security exception
3839     */
3840    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3841            boolean checkShell, String message) {
3842        if (userId < 0) {
3843            throw new IllegalArgumentException("Invalid userId " + userId);
3844        }
3845        if (checkShell) {
3846            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3847        }
3848        if (userId == UserHandle.getUserId(callingUid)) return;
3849        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3850            if (requireFullPermission) {
3851                mContext.enforceCallingOrSelfPermission(
3852                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3853            } else {
3854                try {
3855                    mContext.enforceCallingOrSelfPermission(
3856                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3857                } catch (SecurityException se) {
3858                    mContext.enforceCallingOrSelfPermission(
3859                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3860                }
3861            }
3862        }
3863    }
3864
3865    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3866        if (callingUid == Process.SHELL_UID) {
3867            if (userHandle >= 0
3868                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3869                throw new SecurityException("Shell does not have permission to access user "
3870                        + userHandle);
3871            } else if (userHandle < 0) {
3872                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3873                        + Debug.getCallers(3));
3874            }
3875        }
3876    }
3877
3878    private BasePermission findPermissionTreeLP(String permName) {
3879        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3880            if (permName.startsWith(bp.name) &&
3881                    permName.length() > bp.name.length() &&
3882                    permName.charAt(bp.name.length()) == '.') {
3883                return bp;
3884            }
3885        }
3886        return null;
3887    }
3888
3889    private BasePermission checkPermissionTreeLP(String permName) {
3890        if (permName != null) {
3891            BasePermission bp = findPermissionTreeLP(permName);
3892            if (bp != null) {
3893                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3894                    return bp;
3895                }
3896                throw new SecurityException("Calling uid "
3897                        + Binder.getCallingUid()
3898                        + " is not allowed to add to permission tree "
3899                        + bp.name + " owned by uid " + bp.uid);
3900            }
3901        }
3902        throw new SecurityException("No permission tree found for " + permName);
3903    }
3904
3905    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3906        if (s1 == null) {
3907            return s2 == null;
3908        }
3909        if (s2 == null) {
3910            return false;
3911        }
3912        if (s1.getClass() != s2.getClass()) {
3913            return false;
3914        }
3915        return s1.equals(s2);
3916    }
3917
3918    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3919        if (pi1.icon != pi2.icon) return false;
3920        if (pi1.logo != pi2.logo) return false;
3921        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3922        if (!compareStrings(pi1.name, pi2.name)) return false;
3923        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3924        // We'll take care of setting this one.
3925        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3926        // These are not currently stored in settings.
3927        //if (!compareStrings(pi1.group, pi2.group)) return false;
3928        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3929        //if (pi1.labelRes != pi2.labelRes) return false;
3930        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3931        return true;
3932    }
3933
3934    int permissionInfoFootprint(PermissionInfo info) {
3935        int size = info.name.length();
3936        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3937        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3938        return size;
3939    }
3940
3941    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3942        int size = 0;
3943        for (BasePermission perm : mSettings.mPermissions.values()) {
3944            if (perm.uid == tree.uid) {
3945                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3946            }
3947        }
3948        return size;
3949    }
3950
3951    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3952        // We calculate the max size of permissions defined by this uid and throw
3953        // if that plus the size of 'info' would exceed our stated maximum.
3954        if (tree.uid != Process.SYSTEM_UID) {
3955            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3956            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3957                throw new SecurityException("Permission tree size cap exceeded");
3958            }
3959        }
3960    }
3961
3962    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3963        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3964            throw new SecurityException("Label must be specified in permission");
3965        }
3966        BasePermission tree = checkPermissionTreeLP(info.name);
3967        BasePermission bp = mSettings.mPermissions.get(info.name);
3968        boolean added = bp == null;
3969        boolean changed = true;
3970        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3971        if (added) {
3972            enforcePermissionCapLocked(info, tree);
3973            bp = new BasePermission(info.name, tree.sourcePackage,
3974                    BasePermission.TYPE_DYNAMIC);
3975        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3976            throw new SecurityException(
3977                    "Not allowed to modify non-dynamic permission "
3978                    + info.name);
3979        } else {
3980            if (bp.protectionLevel == fixedLevel
3981                    && bp.perm.owner.equals(tree.perm.owner)
3982                    && bp.uid == tree.uid
3983                    && comparePermissionInfos(bp.perm.info, info)) {
3984                changed = false;
3985            }
3986        }
3987        bp.protectionLevel = fixedLevel;
3988        info = new PermissionInfo(info);
3989        info.protectionLevel = fixedLevel;
3990        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3991        bp.perm.info.packageName = tree.perm.info.packageName;
3992        bp.uid = tree.uid;
3993        if (added) {
3994            mSettings.mPermissions.put(info.name, bp);
3995        }
3996        if (changed) {
3997            if (!async) {
3998                mSettings.writeLPr();
3999            } else {
4000                scheduleWriteSettingsLocked();
4001            }
4002        }
4003        return added;
4004    }
4005
4006    @Override
4007    public boolean addPermission(PermissionInfo info) {
4008        synchronized (mPackages) {
4009            return addPermissionLocked(info, false);
4010        }
4011    }
4012
4013    @Override
4014    public boolean addPermissionAsync(PermissionInfo info) {
4015        synchronized (mPackages) {
4016            return addPermissionLocked(info, true);
4017        }
4018    }
4019
4020    @Override
4021    public void removePermission(String name) {
4022        synchronized (mPackages) {
4023            checkPermissionTreeLP(name);
4024            BasePermission bp = mSettings.mPermissions.get(name);
4025            if (bp != null) {
4026                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4027                    throw new SecurityException(
4028                            "Not allowed to modify non-dynamic permission "
4029                            + name);
4030                }
4031                mSettings.mPermissions.remove(name);
4032                mSettings.writeLPr();
4033            }
4034        }
4035    }
4036
4037    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4038            BasePermission bp) {
4039        int index = pkg.requestedPermissions.indexOf(bp.name);
4040        if (index == -1) {
4041            throw new SecurityException("Package " + pkg.packageName
4042                    + " has not requested permission " + bp.name);
4043        }
4044        if (!bp.isRuntime() && !bp.isDevelopment()) {
4045            throw new SecurityException("Permission " + bp.name
4046                    + " is not a changeable permission type");
4047        }
4048    }
4049
4050    @Override
4051    public void grantRuntimePermission(String packageName, String name, final int userId) {
4052        if (!sUserManager.exists(userId)) {
4053            Log.e(TAG, "No such user:" + userId);
4054            return;
4055        }
4056
4057        mContext.enforceCallingOrSelfPermission(
4058                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4059                "grantRuntimePermission");
4060
4061        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4062                true /* requireFullPermission */, true /* checkShell */,
4063                "grantRuntimePermission");
4064
4065        final int uid;
4066        final SettingBase sb;
4067
4068        synchronized (mPackages) {
4069            final PackageParser.Package pkg = mPackages.get(packageName);
4070            if (pkg == null) {
4071                throw new IllegalArgumentException("Unknown package: " + packageName);
4072            }
4073
4074            final BasePermission bp = mSettings.mPermissions.get(name);
4075            if (bp == null) {
4076                throw new IllegalArgumentException("Unknown permission: " + name);
4077            }
4078
4079            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4080
4081            // If a permission review is required for legacy apps we represent
4082            // their permissions as always granted runtime ones since we need
4083            // to keep the review required permission flag per user while an
4084            // install permission's state is shared across all users.
4085            if (Build.PERMISSIONS_REVIEW_REQUIRED
4086                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4087                    && bp.isRuntime()) {
4088                return;
4089            }
4090
4091            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4092            sb = (SettingBase) pkg.mExtras;
4093            if (sb == null) {
4094                throw new IllegalArgumentException("Unknown package: " + packageName);
4095            }
4096
4097            final PermissionsState permissionsState = sb.getPermissionsState();
4098
4099            final int flags = permissionsState.getPermissionFlags(name, userId);
4100            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4101                throw new SecurityException("Cannot grant system fixed permission "
4102                        + name + " for package " + packageName);
4103            }
4104
4105            if (bp.isDevelopment()) {
4106                // Development permissions must be handled specially, since they are not
4107                // normal runtime permissions.  For now they apply to all users.
4108                if (permissionsState.grantInstallPermission(bp) !=
4109                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4110                    scheduleWriteSettingsLocked();
4111                }
4112                return;
4113            }
4114
4115            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4116                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4117                return;
4118            }
4119
4120            final int result = permissionsState.grantRuntimePermission(bp, userId);
4121            switch (result) {
4122                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4123                    return;
4124                }
4125
4126                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4127                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4128                    mHandler.post(new Runnable() {
4129                        @Override
4130                        public void run() {
4131                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4132                        }
4133                    });
4134                }
4135                break;
4136            }
4137
4138            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4139
4140            // Not critical if that is lost - app has to request again.
4141            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4142        }
4143
4144        // Only need to do this if user is initialized. Otherwise it's a new user
4145        // and there are no processes running as the user yet and there's no need
4146        // to make an expensive call to remount processes for the changed permissions.
4147        if (READ_EXTERNAL_STORAGE.equals(name)
4148                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4149            final long token = Binder.clearCallingIdentity();
4150            try {
4151                if (sUserManager.isInitialized(userId)) {
4152                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4153                            MountServiceInternal.class);
4154                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4155                }
4156            } finally {
4157                Binder.restoreCallingIdentity(token);
4158            }
4159        }
4160    }
4161
4162    @Override
4163    public void revokeRuntimePermission(String packageName, String name, int userId) {
4164        if (!sUserManager.exists(userId)) {
4165            Log.e(TAG, "No such user:" + userId);
4166            return;
4167        }
4168
4169        mContext.enforceCallingOrSelfPermission(
4170                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4171                "revokeRuntimePermission");
4172
4173        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4174                true /* requireFullPermission */, true /* checkShell */,
4175                "revokeRuntimePermission");
4176
4177        final int appId;
4178
4179        synchronized (mPackages) {
4180            final PackageParser.Package pkg = mPackages.get(packageName);
4181            if (pkg == null) {
4182                throw new IllegalArgumentException("Unknown package: " + packageName);
4183            }
4184
4185            final BasePermission bp = mSettings.mPermissions.get(name);
4186            if (bp == null) {
4187                throw new IllegalArgumentException("Unknown permission: " + name);
4188            }
4189
4190            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4191
4192            // If a permission review is required for legacy apps we represent
4193            // their permissions as always granted runtime ones since we need
4194            // to keep the review required permission flag per user while an
4195            // install permission's state is shared across all users.
4196            if (Build.PERMISSIONS_REVIEW_REQUIRED
4197                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4198                    && bp.isRuntime()) {
4199                return;
4200            }
4201
4202            SettingBase sb = (SettingBase) pkg.mExtras;
4203            if (sb == null) {
4204                throw new IllegalArgumentException("Unknown package: " + packageName);
4205            }
4206
4207            final PermissionsState permissionsState = sb.getPermissionsState();
4208
4209            final int flags = permissionsState.getPermissionFlags(name, userId);
4210            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4211                throw new SecurityException("Cannot revoke system fixed permission "
4212                        + name + " for package " + packageName);
4213            }
4214
4215            if (bp.isDevelopment()) {
4216                // Development permissions must be handled specially, since they are not
4217                // normal runtime permissions.  For now they apply to all users.
4218                if (permissionsState.revokeInstallPermission(bp) !=
4219                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4220                    scheduleWriteSettingsLocked();
4221                }
4222                return;
4223            }
4224
4225            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4226                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4227                return;
4228            }
4229
4230            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4231
4232            // Critical, after this call app should never have the permission.
4233            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4234
4235            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4236        }
4237
4238        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4239    }
4240
4241    @Override
4242    public void resetRuntimePermissions() {
4243        mContext.enforceCallingOrSelfPermission(
4244                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4245                "revokeRuntimePermission");
4246
4247        int callingUid = Binder.getCallingUid();
4248        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4249            mContext.enforceCallingOrSelfPermission(
4250                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4251                    "resetRuntimePermissions");
4252        }
4253
4254        synchronized (mPackages) {
4255            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4256            for (int userId : UserManagerService.getInstance().getUserIds()) {
4257                final int packageCount = mPackages.size();
4258                for (int i = 0; i < packageCount; i++) {
4259                    PackageParser.Package pkg = mPackages.valueAt(i);
4260                    if (!(pkg.mExtras instanceof PackageSetting)) {
4261                        continue;
4262                    }
4263                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4264                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4265                }
4266            }
4267        }
4268    }
4269
4270    @Override
4271    public int getPermissionFlags(String name, String packageName, int userId) {
4272        if (!sUserManager.exists(userId)) {
4273            return 0;
4274        }
4275
4276        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4277
4278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4279                true /* requireFullPermission */, false /* checkShell */,
4280                "getPermissionFlags");
4281
4282        synchronized (mPackages) {
4283            final PackageParser.Package pkg = mPackages.get(packageName);
4284            if (pkg == null) {
4285                throw new IllegalArgumentException("Unknown package: " + packageName);
4286            }
4287
4288            final BasePermission bp = mSettings.mPermissions.get(name);
4289            if (bp == null) {
4290                throw new IllegalArgumentException("Unknown permission: " + name);
4291            }
4292
4293            SettingBase sb = (SettingBase) pkg.mExtras;
4294            if (sb == null) {
4295                throw new IllegalArgumentException("Unknown package: " + packageName);
4296            }
4297
4298            PermissionsState permissionsState = sb.getPermissionsState();
4299            return permissionsState.getPermissionFlags(name, userId);
4300        }
4301    }
4302
4303    @Override
4304    public void updatePermissionFlags(String name, String packageName, int flagMask,
4305            int flagValues, int userId) {
4306        if (!sUserManager.exists(userId)) {
4307            return;
4308        }
4309
4310        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4311
4312        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4313                true /* requireFullPermission */, true /* checkShell */,
4314                "updatePermissionFlags");
4315
4316        // Only the system can change these flags and nothing else.
4317        if (getCallingUid() != Process.SYSTEM_UID) {
4318            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4319            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4320            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4321            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4322            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4323        }
4324
4325        synchronized (mPackages) {
4326            final PackageParser.Package pkg = mPackages.get(packageName);
4327            if (pkg == null) {
4328                throw new IllegalArgumentException("Unknown package: " + packageName);
4329            }
4330
4331            final BasePermission bp = mSettings.mPermissions.get(name);
4332            if (bp == null) {
4333                throw new IllegalArgumentException("Unknown permission: " + name);
4334            }
4335
4336            SettingBase sb = (SettingBase) pkg.mExtras;
4337            if (sb == null) {
4338                throw new IllegalArgumentException("Unknown package: " + packageName);
4339            }
4340
4341            PermissionsState permissionsState = sb.getPermissionsState();
4342
4343            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4344
4345            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4346                // Install and runtime permissions are stored in different places,
4347                // so figure out what permission changed and persist the change.
4348                if (permissionsState.getInstallPermissionState(name) != null) {
4349                    scheduleWriteSettingsLocked();
4350                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4351                        || hadState) {
4352                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4353                }
4354            }
4355        }
4356    }
4357
4358    /**
4359     * Update the permission flags for all packages and runtime permissions of a user in order
4360     * to allow device or profile owner to remove POLICY_FIXED.
4361     */
4362    @Override
4363    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4364        if (!sUserManager.exists(userId)) {
4365            return;
4366        }
4367
4368        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4369
4370        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4371                true /* requireFullPermission */, true /* checkShell */,
4372                "updatePermissionFlagsForAllApps");
4373
4374        // Only the system can change system fixed flags.
4375        if (getCallingUid() != Process.SYSTEM_UID) {
4376            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4377            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4378        }
4379
4380        synchronized (mPackages) {
4381            boolean changed = false;
4382            final int packageCount = mPackages.size();
4383            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4384                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4385                SettingBase sb = (SettingBase) pkg.mExtras;
4386                if (sb == null) {
4387                    continue;
4388                }
4389                PermissionsState permissionsState = sb.getPermissionsState();
4390                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4391                        userId, flagMask, flagValues);
4392            }
4393            if (changed) {
4394                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4395            }
4396        }
4397    }
4398
4399    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4400        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4401                != PackageManager.PERMISSION_GRANTED
4402            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4403                != PackageManager.PERMISSION_GRANTED) {
4404            throw new SecurityException(message + " requires "
4405                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4406                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4407        }
4408    }
4409
4410    @Override
4411    public boolean shouldShowRequestPermissionRationale(String permissionName,
4412            String packageName, int userId) {
4413        if (UserHandle.getCallingUserId() != userId) {
4414            mContext.enforceCallingPermission(
4415                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4416                    "canShowRequestPermissionRationale for user " + userId);
4417        }
4418
4419        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4420        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4421            return false;
4422        }
4423
4424        if (checkPermission(permissionName, packageName, userId)
4425                == PackageManager.PERMISSION_GRANTED) {
4426            return false;
4427        }
4428
4429        final int flags;
4430
4431        final long identity = Binder.clearCallingIdentity();
4432        try {
4433            flags = getPermissionFlags(permissionName,
4434                    packageName, userId);
4435        } finally {
4436            Binder.restoreCallingIdentity(identity);
4437        }
4438
4439        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4440                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4441                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4442
4443        if ((flags & fixedFlags) != 0) {
4444            return false;
4445        }
4446
4447        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4448    }
4449
4450    @Override
4451    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4452        mContext.enforceCallingOrSelfPermission(
4453                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4454                "addOnPermissionsChangeListener");
4455
4456        synchronized (mPackages) {
4457            mOnPermissionChangeListeners.addListenerLocked(listener);
4458        }
4459    }
4460
4461    @Override
4462    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4463        synchronized (mPackages) {
4464            mOnPermissionChangeListeners.removeListenerLocked(listener);
4465        }
4466    }
4467
4468    @Override
4469    public boolean isProtectedBroadcast(String actionName) {
4470        synchronized (mPackages) {
4471            if (mProtectedBroadcasts.contains(actionName)) {
4472                return true;
4473            } else if (actionName != null) {
4474                // TODO: remove these terrible hacks
4475                if (actionName.startsWith("android.net.netmon.lingerExpired")
4476                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4477                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4478                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4479                    return true;
4480                }
4481            }
4482        }
4483        return false;
4484    }
4485
4486    @Override
4487    public int checkSignatures(String pkg1, String pkg2) {
4488        synchronized (mPackages) {
4489            final PackageParser.Package p1 = mPackages.get(pkg1);
4490            final PackageParser.Package p2 = mPackages.get(pkg2);
4491            if (p1 == null || p1.mExtras == null
4492                    || p2 == null || p2.mExtras == null) {
4493                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4494            }
4495            return compareSignatures(p1.mSignatures, p2.mSignatures);
4496        }
4497    }
4498
4499    @Override
4500    public int checkUidSignatures(int uid1, int uid2) {
4501        // Map to base uids.
4502        uid1 = UserHandle.getAppId(uid1);
4503        uid2 = UserHandle.getAppId(uid2);
4504        // reader
4505        synchronized (mPackages) {
4506            Signature[] s1;
4507            Signature[] s2;
4508            Object obj = mSettings.getUserIdLPr(uid1);
4509            if (obj != null) {
4510                if (obj instanceof SharedUserSetting) {
4511                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4512                } else if (obj instanceof PackageSetting) {
4513                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4514                } else {
4515                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4516                }
4517            } else {
4518                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4519            }
4520            obj = mSettings.getUserIdLPr(uid2);
4521            if (obj != null) {
4522                if (obj instanceof SharedUserSetting) {
4523                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4524                } else if (obj instanceof PackageSetting) {
4525                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4526                } else {
4527                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4528                }
4529            } else {
4530                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4531            }
4532            return compareSignatures(s1, s2);
4533        }
4534    }
4535
4536    /**
4537     * This method should typically only be used when granting or revoking
4538     * permissions, since the app may immediately restart after this call.
4539     * <p>
4540     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4541     * guard your work against the app being relaunched.
4542     */
4543    private void killUid(int appId, int userId, String reason) {
4544        final long identity = Binder.clearCallingIdentity();
4545        try {
4546            IActivityManager am = ActivityManagerNative.getDefault();
4547            if (am != null) {
4548                try {
4549                    am.killUid(appId, userId, reason);
4550                } catch (RemoteException e) {
4551                    /* ignore - same process */
4552                }
4553            }
4554        } finally {
4555            Binder.restoreCallingIdentity(identity);
4556        }
4557    }
4558
4559    /**
4560     * Compares two sets of signatures. Returns:
4561     * <br />
4562     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4563     * <br />
4564     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4565     * <br />
4566     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4567     * <br />
4568     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4569     * <br />
4570     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4571     */
4572    static int compareSignatures(Signature[] s1, Signature[] s2) {
4573        if (s1 == null) {
4574            return s2 == null
4575                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4576                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4577        }
4578
4579        if (s2 == null) {
4580            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4581        }
4582
4583        if (s1.length != s2.length) {
4584            return PackageManager.SIGNATURE_NO_MATCH;
4585        }
4586
4587        // Since both signature sets are of size 1, we can compare without HashSets.
4588        if (s1.length == 1) {
4589            return s1[0].equals(s2[0]) ?
4590                    PackageManager.SIGNATURE_MATCH :
4591                    PackageManager.SIGNATURE_NO_MATCH;
4592        }
4593
4594        ArraySet<Signature> set1 = new ArraySet<Signature>();
4595        for (Signature sig : s1) {
4596            set1.add(sig);
4597        }
4598        ArraySet<Signature> set2 = new ArraySet<Signature>();
4599        for (Signature sig : s2) {
4600            set2.add(sig);
4601        }
4602        // Make sure s2 contains all signatures in s1.
4603        if (set1.equals(set2)) {
4604            return PackageManager.SIGNATURE_MATCH;
4605        }
4606        return PackageManager.SIGNATURE_NO_MATCH;
4607    }
4608
4609    /**
4610     * If the database version for this type of package (internal storage or
4611     * external storage) is less than the version where package signatures
4612     * were updated, return true.
4613     */
4614    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4615        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4616        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4617    }
4618
4619    /**
4620     * Used for backward compatibility to make sure any packages with
4621     * certificate chains get upgraded to the new style. {@code existingSigs}
4622     * will be in the old format (since they were stored on disk from before the
4623     * system upgrade) and {@code scannedSigs} will be in the newer format.
4624     */
4625    private int compareSignaturesCompat(PackageSignatures existingSigs,
4626            PackageParser.Package scannedPkg) {
4627        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4628            return PackageManager.SIGNATURE_NO_MATCH;
4629        }
4630
4631        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4632        for (Signature sig : existingSigs.mSignatures) {
4633            existingSet.add(sig);
4634        }
4635        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4636        for (Signature sig : scannedPkg.mSignatures) {
4637            try {
4638                Signature[] chainSignatures = sig.getChainSignatures();
4639                for (Signature chainSig : chainSignatures) {
4640                    scannedCompatSet.add(chainSig);
4641                }
4642            } catch (CertificateEncodingException e) {
4643                scannedCompatSet.add(sig);
4644            }
4645        }
4646        /*
4647         * Make sure the expanded scanned set contains all signatures in the
4648         * existing one.
4649         */
4650        if (scannedCompatSet.equals(existingSet)) {
4651            // Migrate the old signatures to the new scheme.
4652            existingSigs.assignSignatures(scannedPkg.mSignatures);
4653            // The new KeySets will be re-added later in the scanning process.
4654            synchronized (mPackages) {
4655                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4656            }
4657            return PackageManager.SIGNATURE_MATCH;
4658        }
4659        return PackageManager.SIGNATURE_NO_MATCH;
4660    }
4661
4662    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4663        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4664        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4665    }
4666
4667    private int compareSignaturesRecover(PackageSignatures existingSigs,
4668            PackageParser.Package scannedPkg) {
4669        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4670            return PackageManager.SIGNATURE_NO_MATCH;
4671        }
4672
4673        String msg = null;
4674        try {
4675            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4676                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4677                        + scannedPkg.packageName);
4678                return PackageManager.SIGNATURE_MATCH;
4679            }
4680        } catch (CertificateException e) {
4681            msg = e.getMessage();
4682        }
4683
4684        logCriticalInfo(Log.INFO,
4685                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4686        return PackageManager.SIGNATURE_NO_MATCH;
4687    }
4688
4689    @Override
4690    public List<String> getAllPackages() {
4691        synchronized (mPackages) {
4692            return new ArrayList<String>(mPackages.keySet());
4693        }
4694    }
4695
4696    @Override
4697    public String[] getPackagesForUid(int uid) {
4698        uid = UserHandle.getAppId(uid);
4699        // reader
4700        synchronized (mPackages) {
4701            Object obj = mSettings.getUserIdLPr(uid);
4702            if (obj instanceof SharedUserSetting) {
4703                final SharedUserSetting sus = (SharedUserSetting) obj;
4704                final int N = sus.packages.size();
4705                final String[] res = new String[N];
4706                final Iterator<PackageSetting> it = sus.packages.iterator();
4707                int i = 0;
4708                while (it.hasNext()) {
4709                    res[i++] = it.next().name;
4710                }
4711                return res;
4712            } else if (obj instanceof PackageSetting) {
4713                final PackageSetting ps = (PackageSetting) obj;
4714                return new String[] { ps.name };
4715            }
4716        }
4717        return null;
4718    }
4719
4720    @Override
4721    public String getNameForUid(int uid) {
4722        // reader
4723        synchronized (mPackages) {
4724            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4725            if (obj instanceof SharedUserSetting) {
4726                final SharedUserSetting sus = (SharedUserSetting) obj;
4727                return sus.name + ":" + sus.userId;
4728            } else if (obj instanceof PackageSetting) {
4729                final PackageSetting ps = (PackageSetting) obj;
4730                return ps.name;
4731            }
4732        }
4733        return null;
4734    }
4735
4736    @Override
4737    public int getUidForSharedUser(String sharedUserName) {
4738        if(sharedUserName == null) {
4739            return -1;
4740        }
4741        // reader
4742        synchronized (mPackages) {
4743            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4744            if (suid == null) {
4745                return -1;
4746            }
4747            return suid.userId;
4748        }
4749    }
4750
4751    @Override
4752    public int getFlagsForUid(int uid) {
4753        synchronized (mPackages) {
4754            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4755            if (obj instanceof SharedUserSetting) {
4756                final SharedUserSetting sus = (SharedUserSetting) obj;
4757                return sus.pkgFlags;
4758            } else if (obj instanceof PackageSetting) {
4759                final PackageSetting ps = (PackageSetting) obj;
4760                return ps.pkgFlags;
4761            }
4762        }
4763        return 0;
4764    }
4765
4766    @Override
4767    public int getPrivateFlagsForUid(int uid) {
4768        synchronized (mPackages) {
4769            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4770            if (obj instanceof SharedUserSetting) {
4771                final SharedUserSetting sus = (SharedUserSetting) obj;
4772                return sus.pkgPrivateFlags;
4773            } else if (obj instanceof PackageSetting) {
4774                final PackageSetting ps = (PackageSetting) obj;
4775                return ps.pkgPrivateFlags;
4776            }
4777        }
4778        return 0;
4779    }
4780
4781    @Override
4782    public boolean isUidPrivileged(int uid) {
4783        uid = UserHandle.getAppId(uid);
4784        // reader
4785        synchronized (mPackages) {
4786            Object obj = mSettings.getUserIdLPr(uid);
4787            if (obj instanceof SharedUserSetting) {
4788                final SharedUserSetting sus = (SharedUserSetting) obj;
4789                final Iterator<PackageSetting> it = sus.packages.iterator();
4790                while (it.hasNext()) {
4791                    if (it.next().isPrivileged()) {
4792                        return true;
4793                    }
4794                }
4795            } else if (obj instanceof PackageSetting) {
4796                final PackageSetting ps = (PackageSetting) obj;
4797                return ps.isPrivileged();
4798            }
4799        }
4800        return false;
4801    }
4802
4803    @Override
4804    public String[] getAppOpPermissionPackages(String permissionName) {
4805        synchronized (mPackages) {
4806            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4807            if (pkgs == null) {
4808                return null;
4809            }
4810            return pkgs.toArray(new String[pkgs.size()]);
4811        }
4812    }
4813
4814    @Override
4815    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4816            int flags, int userId) {
4817        try {
4818            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4819
4820            if (!sUserManager.exists(userId)) return null;
4821            flags = updateFlagsForResolve(flags, userId, intent);
4822            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4823                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4824
4825            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4826            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4827                    flags, userId);
4828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4829
4830            final ResolveInfo bestChoice =
4831                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4832
4833            if (isEphemeralAllowed(intent, query, userId)) {
4834                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4835                final EphemeralResolveInfo ai =
4836                        getEphemeralResolveInfo(intent, resolvedType, userId);
4837                if (ai != null) {
4838                    if (DEBUG_EPHEMERAL) {
4839                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4840                    }
4841                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4842                    bestChoice.ephemeralResolveInfo = ai;
4843                }
4844                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4845            }
4846            return bestChoice;
4847        } finally {
4848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4849        }
4850    }
4851
4852    @Override
4853    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4854            IntentFilter filter, int match, ComponentName activity) {
4855        final int userId = UserHandle.getCallingUserId();
4856        if (DEBUG_PREFERRED) {
4857            Log.v(TAG, "setLastChosenActivity intent=" + intent
4858                + " resolvedType=" + resolvedType
4859                + " flags=" + flags
4860                + " filter=" + filter
4861                + " match=" + match
4862                + " activity=" + activity);
4863            filter.dump(new PrintStreamPrinter(System.out), "    ");
4864        }
4865        intent.setComponent(null);
4866        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4867                userId);
4868        // Find any earlier preferred or last chosen entries and nuke them
4869        findPreferredActivity(intent, resolvedType,
4870                flags, query, 0, false, true, false, userId);
4871        // Add the new activity as the last chosen for this filter
4872        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4873                "Setting last chosen");
4874    }
4875
4876    @Override
4877    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4878        final int userId = UserHandle.getCallingUserId();
4879        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4880        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4881                userId);
4882        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4883                false, false, false, userId);
4884    }
4885
4886
4887    private boolean isEphemeralAllowed(
4888            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4889        // Short circuit and return early if possible.
4890        if (DISABLE_EPHEMERAL_APPS) {
4891            return false;
4892        }
4893        final int callingUser = UserHandle.getCallingUserId();
4894        if (callingUser != UserHandle.USER_SYSTEM) {
4895            return false;
4896        }
4897        if (mEphemeralResolverConnection == null) {
4898            return false;
4899        }
4900        if (intent.getComponent() != null) {
4901            return false;
4902        }
4903        if (intent.getPackage() != null) {
4904            return false;
4905        }
4906        final boolean isWebUri = hasWebURI(intent);
4907        if (!isWebUri) {
4908            return false;
4909        }
4910        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4911        synchronized (mPackages) {
4912            final int count = resolvedActivites.size();
4913            for (int n = 0; n < count; n++) {
4914                ResolveInfo info = resolvedActivites.get(n);
4915                String packageName = info.activityInfo.packageName;
4916                PackageSetting ps = mSettings.mPackages.get(packageName);
4917                if (ps != null) {
4918                    // Try to get the status from User settings first
4919                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4920                    int status = (int) (packedStatus >> 32);
4921                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4922                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4923                        if (DEBUG_EPHEMERAL) {
4924                            Slog.v(TAG, "DENY ephemeral apps;"
4925                                + " pkg: " + packageName + ", status: " + status);
4926                        }
4927                        return false;
4928                    }
4929                }
4930            }
4931        }
4932        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4933        return true;
4934    }
4935
4936    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4937            int userId) {
4938        MessageDigest digest = null;
4939        try {
4940            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4941        } catch (NoSuchAlgorithmException e) {
4942            // If we can't create a digest, ignore ephemeral apps.
4943            return null;
4944        }
4945
4946        final byte[] hostBytes = intent.getData().getHost().getBytes();
4947        final byte[] digestBytes = digest.digest(hostBytes);
4948        int shaPrefix =
4949                digestBytes[0] << 24
4950                | digestBytes[1] << 16
4951                | digestBytes[2] << 8
4952                | digestBytes[3] << 0;
4953        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4954                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4955        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4956            // No hash prefix match; there are no ephemeral apps for this domain.
4957            return null;
4958        }
4959        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4960            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4961            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4962                continue;
4963            }
4964            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4965            // No filters; this should never happen.
4966            if (filters.isEmpty()) {
4967                continue;
4968            }
4969            // We have a domain match; resolve the filters to see if anything matches.
4970            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4971            for (int j = filters.size() - 1; j >= 0; --j) {
4972                final EphemeralResolveIntentInfo intentInfo =
4973                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4974                ephemeralResolver.addFilter(intentInfo);
4975            }
4976            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4977                    intent, resolvedType, false /*defaultOnly*/, userId);
4978            if (!matchedResolveInfoList.isEmpty()) {
4979                return matchedResolveInfoList.get(0);
4980            }
4981        }
4982        // Hash or filter mis-match; no ephemeral apps for this domain.
4983        return null;
4984    }
4985
4986    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4987            int flags, List<ResolveInfo> query, int userId) {
4988        if (query != null) {
4989            final int N = query.size();
4990            if (N == 1) {
4991                return query.get(0);
4992            } else if (N > 1) {
4993                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4994                // If there is more than one activity with the same priority,
4995                // then let the user decide between them.
4996                ResolveInfo r0 = query.get(0);
4997                ResolveInfo r1 = query.get(1);
4998                if (DEBUG_INTENT_MATCHING || debug) {
4999                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5000                            + r1.activityInfo.name + "=" + r1.priority);
5001                }
5002                // If the first activity has a higher priority, or a different
5003                // default, then it is always desirable to pick it.
5004                if (r0.priority != r1.priority
5005                        || r0.preferredOrder != r1.preferredOrder
5006                        || r0.isDefault != r1.isDefault) {
5007                    return query.get(0);
5008                }
5009                // If we have saved a preference for a preferred activity for
5010                // this Intent, use that.
5011                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5012                        flags, query, r0.priority, true, false, debug, userId);
5013                if (ri != null) {
5014                    return ri;
5015                }
5016                ri = new ResolveInfo(mResolveInfo);
5017                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5018                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5019                ri.activityInfo.applicationInfo = new ApplicationInfo(
5020                        ri.activityInfo.applicationInfo);
5021                if (userId != 0) {
5022                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5023                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5024                }
5025                // Make sure that the resolver is displayable in car mode
5026                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5027                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5028                return ri;
5029            }
5030        }
5031        return null;
5032    }
5033
5034    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5035            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5036        final int N = query.size();
5037        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5038                .get(userId);
5039        // Get the list of persistent preferred activities that handle the intent
5040        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5041        List<PersistentPreferredActivity> pprefs = ppir != null
5042                ? ppir.queryIntent(intent, resolvedType,
5043                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5044                : null;
5045        if (pprefs != null && pprefs.size() > 0) {
5046            final int M = pprefs.size();
5047            for (int i=0; i<M; i++) {
5048                final PersistentPreferredActivity ppa = pprefs.get(i);
5049                if (DEBUG_PREFERRED || debug) {
5050                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5051                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5052                            + "\n  component=" + ppa.mComponent);
5053                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5054                }
5055                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5056                        flags | MATCH_DISABLED_COMPONENTS, userId);
5057                if (DEBUG_PREFERRED || debug) {
5058                    Slog.v(TAG, "Found persistent preferred activity:");
5059                    if (ai != null) {
5060                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5061                    } else {
5062                        Slog.v(TAG, "  null");
5063                    }
5064                }
5065                if (ai == null) {
5066                    // This previously registered persistent preferred activity
5067                    // component is no longer known. Ignore it and do NOT remove it.
5068                    continue;
5069                }
5070                for (int j=0; j<N; j++) {
5071                    final ResolveInfo ri = query.get(j);
5072                    if (!ri.activityInfo.applicationInfo.packageName
5073                            .equals(ai.applicationInfo.packageName)) {
5074                        continue;
5075                    }
5076                    if (!ri.activityInfo.name.equals(ai.name)) {
5077                        continue;
5078                    }
5079                    //  Found a persistent preference that can handle the intent.
5080                    if (DEBUG_PREFERRED || debug) {
5081                        Slog.v(TAG, "Returning persistent preferred activity: " +
5082                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5083                    }
5084                    return ri;
5085                }
5086            }
5087        }
5088        return null;
5089    }
5090
5091    // TODO: handle preferred activities missing while user has amnesia
5092    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5093            List<ResolveInfo> query, int priority, boolean always,
5094            boolean removeMatches, boolean debug, int userId) {
5095        if (!sUserManager.exists(userId)) return null;
5096        flags = updateFlagsForResolve(flags, userId, intent);
5097        // writer
5098        synchronized (mPackages) {
5099            if (intent.getSelector() != null) {
5100                intent = intent.getSelector();
5101            }
5102            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5103
5104            // Try to find a matching persistent preferred activity.
5105            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5106                    debug, userId);
5107
5108            // If a persistent preferred activity matched, use it.
5109            if (pri != null) {
5110                return pri;
5111            }
5112
5113            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5114            // Get the list of preferred activities that handle the intent
5115            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5116            List<PreferredActivity> prefs = pir != null
5117                    ? pir.queryIntent(intent, resolvedType,
5118                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5119                    : null;
5120            if (prefs != null && prefs.size() > 0) {
5121                boolean changed = false;
5122                try {
5123                    // First figure out how good the original match set is.
5124                    // We will only allow preferred activities that came
5125                    // from the same match quality.
5126                    int match = 0;
5127
5128                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5129
5130                    final int N = query.size();
5131                    for (int j=0; j<N; j++) {
5132                        final ResolveInfo ri = query.get(j);
5133                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5134                                + ": 0x" + Integer.toHexString(match));
5135                        if (ri.match > match) {
5136                            match = ri.match;
5137                        }
5138                    }
5139
5140                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5141                            + Integer.toHexString(match));
5142
5143                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5144                    final int M = prefs.size();
5145                    for (int i=0; i<M; i++) {
5146                        final PreferredActivity pa = prefs.get(i);
5147                        if (DEBUG_PREFERRED || debug) {
5148                            Slog.v(TAG, "Checking PreferredActivity ds="
5149                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5150                                    + "\n  component=" + pa.mPref.mComponent);
5151                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5152                        }
5153                        if (pa.mPref.mMatch != match) {
5154                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5155                                    + Integer.toHexString(pa.mPref.mMatch));
5156                            continue;
5157                        }
5158                        // If it's not an "always" type preferred activity and that's what we're
5159                        // looking for, skip it.
5160                        if (always && !pa.mPref.mAlways) {
5161                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5162                            continue;
5163                        }
5164                        final ActivityInfo ai = getActivityInfo(
5165                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5166                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5167                                userId);
5168                        if (DEBUG_PREFERRED || debug) {
5169                            Slog.v(TAG, "Found preferred activity:");
5170                            if (ai != null) {
5171                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5172                            } else {
5173                                Slog.v(TAG, "  null");
5174                            }
5175                        }
5176                        if (ai == null) {
5177                            // This previously registered preferred activity
5178                            // component is no longer known.  Most likely an update
5179                            // to the app was installed and in the new version this
5180                            // component no longer exists.  Clean it up by removing
5181                            // it from the preferred activities list, and skip it.
5182                            Slog.w(TAG, "Removing dangling preferred activity: "
5183                                    + pa.mPref.mComponent);
5184                            pir.removeFilter(pa);
5185                            changed = true;
5186                            continue;
5187                        }
5188                        for (int j=0; j<N; j++) {
5189                            final ResolveInfo ri = query.get(j);
5190                            if (!ri.activityInfo.applicationInfo.packageName
5191                                    .equals(ai.applicationInfo.packageName)) {
5192                                continue;
5193                            }
5194                            if (!ri.activityInfo.name.equals(ai.name)) {
5195                                continue;
5196                            }
5197
5198                            if (removeMatches) {
5199                                pir.removeFilter(pa);
5200                                changed = true;
5201                                if (DEBUG_PREFERRED) {
5202                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5203                                }
5204                                break;
5205                            }
5206
5207                            // Okay we found a previously set preferred or last chosen app.
5208                            // If the result set is different from when this
5209                            // was created, we need to clear it and re-ask the
5210                            // user their preference, if we're looking for an "always" type entry.
5211                            if (always && !pa.mPref.sameSet(query)) {
5212                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5213                                        + intent + " type " + resolvedType);
5214                                if (DEBUG_PREFERRED) {
5215                                    Slog.v(TAG, "Removing preferred activity since set changed "
5216                                            + pa.mPref.mComponent);
5217                                }
5218                                pir.removeFilter(pa);
5219                                // Re-add the filter as a "last chosen" entry (!always)
5220                                PreferredActivity lastChosen = new PreferredActivity(
5221                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5222                                pir.addFilter(lastChosen);
5223                                changed = true;
5224                                return null;
5225                            }
5226
5227                            // Yay! Either the set matched or we're looking for the last chosen
5228                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5229                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5230                            return ri;
5231                        }
5232                    }
5233                } finally {
5234                    if (changed) {
5235                        if (DEBUG_PREFERRED) {
5236                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5237                        }
5238                        scheduleWritePackageRestrictionsLocked(userId);
5239                    }
5240                }
5241            }
5242        }
5243        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5244        return null;
5245    }
5246
5247    /*
5248     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5249     */
5250    @Override
5251    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5252            int targetUserId) {
5253        mContext.enforceCallingOrSelfPermission(
5254                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5255        List<CrossProfileIntentFilter> matches =
5256                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5257        if (matches != null) {
5258            int size = matches.size();
5259            for (int i = 0; i < size; i++) {
5260                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5261            }
5262        }
5263        if (hasWebURI(intent)) {
5264            // cross-profile app linking works only towards the parent.
5265            final UserInfo parent = getProfileParent(sourceUserId);
5266            synchronized(mPackages) {
5267                int flags = updateFlagsForResolve(0, parent.id, intent);
5268                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5269                        intent, resolvedType, flags, sourceUserId, parent.id);
5270                return xpDomainInfo != null;
5271            }
5272        }
5273        return false;
5274    }
5275
5276    private UserInfo getProfileParent(int userId) {
5277        final long identity = Binder.clearCallingIdentity();
5278        try {
5279            return sUserManager.getProfileParent(userId);
5280        } finally {
5281            Binder.restoreCallingIdentity(identity);
5282        }
5283    }
5284
5285    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5286            String resolvedType, int userId) {
5287        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5288        if (resolver != null) {
5289            return resolver.queryIntent(intent, resolvedType, false, userId);
5290        }
5291        return null;
5292    }
5293
5294    @Override
5295    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5296            String resolvedType, int flags, int userId) {
5297        try {
5298            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5299
5300            return new ParceledListSlice<>(
5301                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5302        } finally {
5303            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5304        }
5305    }
5306
5307    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5308            String resolvedType, int flags, int userId) {
5309        if (!sUserManager.exists(userId)) return Collections.emptyList();
5310        flags = updateFlagsForResolve(flags, userId, intent);
5311        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5312                false /* requireFullPermission */, false /* checkShell */,
5313                "query intent activities");
5314        ComponentName comp = intent.getComponent();
5315        if (comp == null) {
5316            if (intent.getSelector() != null) {
5317                intent = intent.getSelector();
5318                comp = intent.getComponent();
5319            }
5320        }
5321
5322        if (comp != null) {
5323            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5324            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5325            if (ai != null) {
5326                final ResolveInfo ri = new ResolveInfo();
5327                ri.activityInfo = ai;
5328                list.add(ri);
5329            }
5330            return list;
5331        }
5332
5333        // reader
5334        synchronized (mPackages) {
5335            final String pkgName = intent.getPackage();
5336            if (pkgName == null) {
5337                List<CrossProfileIntentFilter> matchingFilters =
5338                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5339                // Check for results that need to skip the current profile.
5340                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5341                        resolvedType, flags, userId);
5342                if (xpResolveInfo != null) {
5343                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5344                    result.add(xpResolveInfo);
5345                    return filterIfNotSystemUser(result, userId);
5346                }
5347
5348                // Check for results in the current profile.
5349                List<ResolveInfo> result = mActivities.queryIntent(
5350                        intent, resolvedType, flags, userId);
5351                result = filterIfNotSystemUser(result, userId);
5352
5353                // Check for cross profile results.
5354                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5355                xpResolveInfo = queryCrossProfileIntents(
5356                        matchingFilters, intent, resolvedType, flags, userId,
5357                        hasNonNegativePriorityResult);
5358                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5359                    boolean isVisibleToUser = filterIfNotSystemUser(
5360                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5361                    if (isVisibleToUser) {
5362                        result.add(xpResolveInfo);
5363                        Collections.sort(result, mResolvePrioritySorter);
5364                    }
5365                }
5366                if (hasWebURI(intent)) {
5367                    CrossProfileDomainInfo xpDomainInfo = null;
5368                    final UserInfo parent = getProfileParent(userId);
5369                    if (parent != null) {
5370                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5371                                flags, userId, parent.id);
5372                    }
5373                    if (xpDomainInfo != null) {
5374                        if (xpResolveInfo != null) {
5375                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5376                            // in the result.
5377                            result.remove(xpResolveInfo);
5378                        }
5379                        if (result.size() == 0) {
5380                            result.add(xpDomainInfo.resolveInfo);
5381                            return result;
5382                        }
5383                    } else if (result.size() <= 1) {
5384                        return result;
5385                    }
5386                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5387                            xpDomainInfo, userId);
5388                    Collections.sort(result, mResolvePrioritySorter);
5389                }
5390                return result;
5391            }
5392            final PackageParser.Package pkg = mPackages.get(pkgName);
5393            if (pkg != null) {
5394                return filterIfNotSystemUser(
5395                        mActivities.queryIntentForPackage(
5396                                intent, resolvedType, flags, pkg.activities, userId),
5397                        userId);
5398            }
5399            return new ArrayList<ResolveInfo>();
5400        }
5401    }
5402
5403    private static class CrossProfileDomainInfo {
5404        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5405        ResolveInfo resolveInfo;
5406        /* Best domain verification status of the activities found in the other profile */
5407        int bestDomainVerificationStatus;
5408    }
5409
5410    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5411            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5412        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5413                sourceUserId)) {
5414            return null;
5415        }
5416        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5417                resolvedType, flags, parentUserId);
5418
5419        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5420            return null;
5421        }
5422        CrossProfileDomainInfo result = null;
5423        int size = resultTargetUser.size();
5424        for (int i = 0; i < size; i++) {
5425            ResolveInfo riTargetUser = resultTargetUser.get(i);
5426            // Intent filter verification is only for filters that specify a host. So don't return
5427            // those that handle all web uris.
5428            if (riTargetUser.handleAllWebDataURI) {
5429                continue;
5430            }
5431            String packageName = riTargetUser.activityInfo.packageName;
5432            PackageSetting ps = mSettings.mPackages.get(packageName);
5433            if (ps == null) {
5434                continue;
5435            }
5436            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5437            int status = (int)(verificationState >> 32);
5438            if (result == null) {
5439                result = new CrossProfileDomainInfo();
5440                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5441                        sourceUserId, parentUserId);
5442                result.bestDomainVerificationStatus = status;
5443            } else {
5444                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5445                        result.bestDomainVerificationStatus);
5446            }
5447        }
5448        // Don't consider matches with status NEVER across profiles.
5449        if (result != null && result.bestDomainVerificationStatus
5450                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5451            return null;
5452        }
5453        return result;
5454    }
5455
5456    /**
5457     * Verification statuses are ordered from the worse to the best, except for
5458     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5459     */
5460    private int bestDomainVerificationStatus(int status1, int status2) {
5461        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5462            return status2;
5463        }
5464        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5465            return status1;
5466        }
5467        return (int) MathUtils.max(status1, status2);
5468    }
5469
5470    private boolean isUserEnabled(int userId) {
5471        long callingId = Binder.clearCallingIdentity();
5472        try {
5473            UserInfo userInfo = sUserManager.getUserInfo(userId);
5474            return userInfo != null && userInfo.isEnabled();
5475        } finally {
5476            Binder.restoreCallingIdentity(callingId);
5477        }
5478    }
5479
5480    /**
5481     * Filter out activities with systemUserOnly flag set, when current user is not System.
5482     *
5483     * @return filtered list
5484     */
5485    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5486        if (userId == UserHandle.USER_SYSTEM) {
5487            return resolveInfos;
5488        }
5489        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5490            ResolveInfo info = resolveInfos.get(i);
5491            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5492                resolveInfos.remove(i);
5493            }
5494        }
5495        return resolveInfos;
5496    }
5497
5498    /**
5499     * @param resolveInfos list of resolve infos in descending priority order
5500     * @return if the list contains a resolve info with non-negative priority
5501     */
5502    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5503        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5504    }
5505
5506    private static boolean hasWebURI(Intent intent) {
5507        if (intent.getData() == null) {
5508            return false;
5509        }
5510        final String scheme = intent.getScheme();
5511        if (TextUtils.isEmpty(scheme)) {
5512            return false;
5513        }
5514        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5515    }
5516
5517    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5518            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5519            int userId) {
5520        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5521
5522        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5523            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5524                    candidates.size());
5525        }
5526
5527        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5528        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5529        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5530        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5531        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5532        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5533
5534        synchronized (mPackages) {
5535            final int count = candidates.size();
5536            // First, try to use linked apps. Partition the candidates into four lists:
5537            // one for the final results, one for the "do not use ever", one for "undefined status"
5538            // and finally one for "browser app type".
5539            for (int n=0; n<count; n++) {
5540                ResolveInfo info = candidates.get(n);
5541                String packageName = info.activityInfo.packageName;
5542                PackageSetting ps = mSettings.mPackages.get(packageName);
5543                if (ps != null) {
5544                    // Add to the special match all list (Browser use case)
5545                    if (info.handleAllWebDataURI) {
5546                        matchAllList.add(info);
5547                        continue;
5548                    }
5549                    // Try to get the status from User settings first
5550                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5551                    int status = (int)(packedStatus >> 32);
5552                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5553                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5554                        if (DEBUG_DOMAIN_VERIFICATION) {
5555                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5556                                    + " : linkgen=" + linkGeneration);
5557                        }
5558                        // Use link-enabled generation as preferredOrder, i.e.
5559                        // prefer newly-enabled over earlier-enabled.
5560                        info.preferredOrder = linkGeneration;
5561                        alwaysList.add(info);
5562                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5563                        if (DEBUG_DOMAIN_VERIFICATION) {
5564                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5565                        }
5566                        neverList.add(info);
5567                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5568                        if (DEBUG_DOMAIN_VERIFICATION) {
5569                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5570                        }
5571                        alwaysAskList.add(info);
5572                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5573                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5574                        if (DEBUG_DOMAIN_VERIFICATION) {
5575                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5576                        }
5577                        undefinedList.add(info);
5578                    }
5579                }
5580            }
5581
5582            // We'll want to include browser possibilities in a few cases
5583            boolean includeBrowser = false;
5584
5585            // First try to add the "always" resolution(s) for the current user, if any
5586            if (alwaysList.size() > 0) {
5587                result.addAll(alwaysList);
5588            } else {
5589                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5590                result.addAll(undefinedList);
5591                // Maybe add one for the other profile.
5592                if (xpDomainInfo != null && (
5593                        xpDomainInfo.bestDomainVerificationStatus
5594                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5595                    result.add(xpDomainInfo.resolveInfo);
5596                }
5597                includeBrowser = true;
5598            }
5599
5600            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5601            // If there were 'always' entries their preferred order has been set, so we also
5602            // back that off to make the alternatives equivalent
5603            if (alwaysAskList.size() > 0) {
5604                for (ResolveInfo i : result) {
5605                    i.preferredOrder = 0;
5606                }
5607                result.addAll(alwaysAskList);
5608                includeBrowser = true;
5609            }
5610
5611            if (includeBrowser) {
5612                // Also add browsers (all of them or only the default one)
5613                if (DEBUG_DOMAIN_VERIFICATION) {
5614                    Slog.v(TAG, "   ...including browsers in candidate set");
5615                }
5616                if ((matchFlags & MATCH_ALL) != 0) {
5617                    result.addAll(matchAllList);
5618                } else {
5619                    // Browser/generic handling case.  If there's a default browser, go straight
5620                    // to that (but only if there is no other higher-priority match).
5621                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5622                    int maxMatchPrio = 0;
5623                    ResolveInfo defaultBrowserMatch = null;
5624                    final int numCandidates = matchAllList.size();
5625                    for (int n = 0; n < numCandidates; n++) {
5626                        ResolveInfo info = matchAllList.get(n);
5627                        // track the highest overall match priority...
5628                        if (info.priority > maxMatchPrio) {
5629                            maxMatchPrio = info.priority;
5630                        }
5631                        // ...and the highest-priority default browser match
5632                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5633                            if (defaultBrowserMatch == null
5634                                    || (defaultBrowserMatch.priority < info.priority)) {
5635                                if (debug) {
5636                                    Slog.v(TAG, "Considering default browser match " + info);
5637                                }
5638                                defaultBrowserMatch = info;
5639                            }
5640                        }
5641                    }
5642                    if (defaultBrowserMatch != null
5643                            && defaultBrowserMatch.priority >= maxMatchPrio
5644                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5645                    {
5646                        if (debug) {
5647                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5648                        }
5649                        result.add(defaultBrowserMatch);
5650                    } else {
5651                        result.addAll(matchAllList);
5652                    }
5653                }
5654
5655                // If there is nothing selected, add all candidates and remove the ones that the user
5656                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5657                if (result.size() == 0) {
5658                    result.addAll(candidates);
5659                    result.removeAll(neverList);
5660                }
5661            }
5662        }
5663        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5664            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5665                    result.size());
5666            for (ResolveInfo info : result) {
5667                Slog.v(TAG, "  + " + info.activityInfo);
5668            }
5669        }
5670        return result;
5671    }
5672
5673    // Returns a packed value as a long:
5674    //
5675    // high 'int'-sized word: link status: undefined/ask/never/always.
5676    // low 'int'-sized word: relative priority among 'always' results.
5677    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5678        long result = ps.getDomainVerificationStatusForUser(userId);
5679        // if none available, get the master status
5680        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5681            if (ps.getIntentFilterVerificationInfo() != null) {
5682                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5683            }
5684        }
5685        return result;
5686    }
5687
5688    private ResolveInfo querySkipCurrentProfileIntents(
5689            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5690            int flags, int sourceUserId) {
5691        if (matchingFilters != null) {
5692            int size = matchingFilters.size();
5693            for (int i = 0; i < size; i ++) {
5694                CrossProfileIntentFilter filter = matchingFilters.get(i);
5695                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5696                    // Checking if there are activities in the target user that can handle the
5697                    // intent.
5698                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5699                            resolvedType, flags, sourceUserId);
5700                    if (resolveInfo != null) {
5701                        return resolveInfo;
5702                    }
5703                }
5704            }
5705        }
5706        return null;
5707    }
5708
5709    // Return matching ResolveInfo in target user if any.
5710    private ResolveInfo queryCrossProfileIntents(
5711            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5712            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5713        if (matchingFilters != null) {
5714            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5715            // match the same intent. For performance reasons, it is better not to
5716            // run queryIntent twice for the same userId
5717            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5718            int size = matchingFilters.size();
5719            for (int i = 0; i < size; i++) {
5720                CrossProfileIntentFilter filter = matchingFilters.get(i);
5721                int targetUserId = filter.getTargetUserId();
5722                boolean skipCurrentProfile =
5723                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5724                boolean skipCurrentProfileIfNoMatchFound =
5725                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5726                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5727                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5728                    // Checking if there are activities in the target user that can handle the
5729                    // intent.
5730                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5731                            resolvedType, flags, sourceUserId);
5732                    if (resolveInfo != null) return resolveInfo;
5733                    alreadyTriedUserIds.put(targetUserId, true);
5734                }
5735            }
5736        }
5737        return null;
5738    }
5739
5740    /**
5741     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5742     * will forward the intent to the filter's target user.
5743     * Otherwise, returns null.
5744     */
5745    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5746            String resolvedType, int flags, int sourceUserId) {
5747        int targetUserId = filter.getTargetUserId();
5748        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5749                resolvedType, flags, targetUserId);
5750        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5751            // If all the matches in the target profile are suspended, return null.
5752            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5753                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5754                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5755                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5756                            targetUserId);
5757                }
5758            }
5759        }
5760        return null;
5761    }
5762
5763    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5764            int sourceUserId, int targetUserId) {
5765        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5766        long ident = Binder.clearCallingIdentity();
5767        boolean targetIsProfile;
5768        try {
5769            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5770        } finally {
5771            Binder.restoreCallingIdentity(ident);
5772        }
5773        String className;
5774        if (targetIsProfile) {
5775            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5776        } else {
5777            className = FORWARD_INTENT_TO_PARENT;
5778        }
5779        ComponentName forwardingActivityComponentName = new ComponentName(
5780                mAndroidApplication.packageName, className);
5781        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5782                sourceUserId);
5783        if (!targetIsProfile) {
5784            forwardingActivityInfo.showUserIcon = targetUserId;
5785            forwardingResolveInfo.noResourceId = true;
5786        }
5787        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5788        forwardingResolveInfo.priority = 0;
5789        forwardingResolveInfo.preferredOrder = 0;
5790        forwardingResolveInfo.match = 0;
5791        forwardingResolveInfo.isDefault = true;
5792        forwardingResolveInfo.filter = filter;
5793        forwardingResolveInfo.targetUserId = targetUserId;
5794        return forwardingResolveInfo;
5795    }
5796
5797    @Override
5798    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5799            Intent[] specifics, String[] specificTypes, Intent intent,
5800            String resolvedType, int flags, int userId) {
5801        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5802                specificTypes, intent, resolvedType, flags, userId));
5803    }
5804
5805    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5806            Intent[] specifics, String[] specificTypes, Intent intent,
5807            String resolvedType, int flags, int userId) {
5808        if (!sUserManager.exists(userId)) return Collections.emptyList();
5809        flags = updateFlagsForResolve(flags, userId, intent);
5810        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5811                false /* requireFullPermission */, false /* checkShell */,
5812                "query intent activity options");
5813        final String resultsAction = intent.getAction();
5814
5815        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5816                | PackageManager.GET_RESOLVED_FILTER, userId);
5817
5818        if (DEBUG_INTENT_MATCHING) {
5819            Log.v(TAG, "Query " + intent + ": " + results);
5820        }
5821
5822        int specificsPos = 0;
5823        int N;
5824
5825        // todo: note that the algorithm used here is O(N^2).  This
5826        // isn't a problem in our current environment, but if we start running
5827        // into situations where we have more than 5 or 10 matches then this
5828        // should probably be changed to something smarter...
5829
5830        // First we go through and resolve each of the specific items
5831        // that were supplied, taking care of removing any corresponding
5832        // duplicate items in the generic resolve list.
5833        if (specifics != null) {
5834            for (int i=0; i<specifics.length; i++) {
5835                final Intent sintent = specifics[i];
5836                if (sintent == null) {
5837                    continue;
5838                }
5839
5840                if (DEBUG_INTENT_MATCHING) {
5841                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5842                }
5843
5844                String action = sintent.getAction();
5845                if (resultsAction != null && resultsAction.equals(action)) {
5846                    // If this action was explicitly requested, then don't
5847                    // remove things that have it.
5848                    action = null;
5849                }
5850
5851                ResolveInfo ri = null;
5852                ActivityInfo ai = null;
5853
5854                ComponentName comp = sintent.getComponent();
5855                if (comp == null) {
5856                    ri = resolveIntent(
5857                        sintent,
5858                        specificTypes != null ? specificTypes[i] : null,
5859                            flags, userId);
5860                    if (ri == null) {
5861                        continue;
5862                    }
5863                    if (ri == mResolveInfo) {
5864                        // ACK!  Must do something better with this.
5865                    }
5866                    ai = ri.activityInfo;
5867                    comp = new ComponentName(ai.applicationInfo.packageName,
5868                            ai.name);
5869                } else {
5870                    ai = getActivityInfo(comp, flags, userId);
5871                    if (ai == null) {
5872                        continue;
5873                    }
5874                }
5875
5876                // Look for any generic query activities that are duplicates
5877                // of this specific one, and remove them from the results.
5878                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5879                N = results.size();
5880                int j;
5881                for (j=specificsPos; j<N; j++) {
5882                    ResolveInfo sri = results.get(j);
5883                    if ((sri.activityInfo.name.equals(comp.getClassName())
5884                            && sri.activityInfo.applicationInfo.packageName.equals(
5885                                    comp.getPackageName()))
5886                        || (action != null && sri.filter.matchAction(action))) {
5887                        results.remove(j);
5888                        if (DEBUG_INTENT_MATCHING) Log.v(
5889                            TAG, "Removing duplicate item from " + j
5890                            + " due to specific " + specificsPos);
5891                        if (ri == null) {
5892                            ri = sri;
5893                        }
5894                        j--;
5895                        N--;
5896                    }
5897                }
5898
5899                // Add this specific item to its proper place.
5900                if (ri == null) {
5901                    ri = new ResolveInfo();
5902                    ri.activityInfo = ai;
5903                }
5904                results.add(specificsPos, ri);
5905                ri.specificIndex = i;
5906                specificsPos++;
5907            }
5908        }
5909
5910        // Now we go through the remaining generic results and remove any
5911        // duplicate actions that are found here.
5912        N = results.size();
5913        for (int i=specificsPos; i<N-1; i++) {
5914            final ResolveInfo rii = results.get(i);
5915            if (rii.filter == null) {
5916                continue;
5917            }
5918
5919            // Iterate over all of the actions of this result's intent
5920            // filter...  typically this should be just one.
5921            final Iterator<String> it = rii.filter.actionsIterator();
5922            if (it == null) {
5923                continue;
5924            }
5925            while (it.hasNext()) {
5926                final String action = it.next();
5927                if (resultsAction != null && resultsAction.equals(action)) {
5928                    // If this action was explicitly requested, then don't
5929                    // remove things that have it.
5930                    continue;
5931                }
5932                for (int j=i+1; j<N; j++) {
5933                    final ResolveInfo rij = results.get(j);
5934                    if (rij.filter != null && rij.filter.hasAction(action)) {
5935                        results.remove(j);
5936                        if (DEBUG_INTENT_MATCHING) Log.v(
5937                            TAG, "Removing duplicate item from " + j
5938                            + " due to action " + action + " at " + i);
5939                        j--;
5940                        N--;
5941                    }
5942                }
5943            }
5944
5945            // If the caller didn't request filter information, drop it now
5946            // so we don't have to marshall/unmarshall it.
5947            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5948                rii.filter = null;
5949            }
5950        }
5951
5952        // Filter out the caller activity if so requested.
5953        if (caller != null) {
5954            N = results.size();
5955            for (int i=0; i<N; i++) {
5956                ActivityInfo ainfo = results.get(i).activityInfo;
5957                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5958                        && caller.getClassName().equals(ainfo.name)) {
5959                    results.remove(i);
5960                    break;
5961                }
5962            }
5963        }
5964
5965        // If the caller didn't request filter information,
5966        // drop them now so we don't have to
5967        // marshall/unmarshall it.
5968        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5969            N = results.size();
5970            for (int i=0; i<N; i++) {
5971                results.get(i).filter = null;
5972            }
5973        }
5974
5975        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5976        return results;
5977    }
5978
5979    @Override
5980    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5981            String resolvedType, int flags, int userId) {
5982        return new ParceledListSlice<>(
5983                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5984    }
5985
5986    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5987            String resolvedType, int flags, int userId) {
5988        if (!sUserManager.exists(userId)) return Collections.emptyList();
5989        flags = updateFlagsForResolve(flags, userId, intent);
5990        ComponentName comp = intent.getComponent();
5991        if (comp == null) {
5992            if (intent.getSelector() != null) {
5993                intent = intent.getSelector();
5994                comp = intent.getComponent();
5995            }
5996        }
5997        if (comp != null) {
5998            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5999            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6000            if (ai != null) {
6001                ResolveInfo ri = new ResolveInfo();
6002                ri.activityInfo = ai;
6003                list.add(ri);
6004            }
6005            return list;
6006        }
6007
6008        // reader
6009        synchronized (mPackages) {
6010            String pkgName = intent.getPackage();
6011            if (pkgName == null) {
6012                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6013            }
6014            final PackageParser.Package pkg = mPackages.get(pkgName);
6015            if (pkg != null) {
6016                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6017                        userId);
6018            }
6019            return Collections.emptyList();
6020        }
6021    }
6022
6023    @Override
6024    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6025        if (!sUserManager.exists(userId)) return null;
6026        flags = updateFlagsForResolve(flags, userId, intent);
6027        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6028        if (query != null) {
6029            if (query.size() >= 1) {
6030                // If there is more than one service with the same priority,
6031                // just arbitrarily pick the first one.
6032                return query.get(0);
6033            }
6034        }
6035        return null;
6036    }
6037
6038    @Override
6039    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6040            String resolvedType, int flags, int userId) {
6041        return new ParceledListSlice<>(
6042                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6043    }
6044
6045    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6046            String resolvedType, int flags, int userId) {
6047        if (!sUserManager.exists(userId)) return Collections.emptyList();
6048        flags = updateFlagsForResolve(flags, userId, intent);
6049        ComponentName comp = intent.getComponent();
6050        if (comp == null) {
6051            if (intent.getSelector() != null) {
6052                intent = intent.getSelector();
6053                comp = intent.getComponent();
6054            }
6055        }
6056        if (comp != null) {
6057            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6058            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6059            if (si != null) {
6060                final ResolveInfo ri = new ResolveInfo();
6061                ri.serviceInfo = si;
6062                list.add(ri);
6063            }
6064            return list;
6065        }
6066
6067        // reader
6068        synchronized (mPackages) {
6069            String pkgName = intent.getPackage();
6070            if (pkgName == null) {
6071                return mServices.queryIntent(intent, resolvedType, flags, userId);
6072            }
6073            final PackageParser.Package pkg = mPackages.get(pkgName);
6074            if (pkg != null) {
6075                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6076                        userId);
6077            }
6078            return Collections.emptyList();
6079        }
6080    }
6081
6082    @Override
6083    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6084            String resolvedType, int flags, int userId) {
6085        return new ParceledListSlice<>(
6086                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6087    }
6088
6089    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6090            Intent intent, String resolvedType, int flags, int userId) {
6091        if (!sUserManager.exists(userId)) return Collections.emptyList();
6092        flags = updateFlagsForResolve(flags, userId, intent);
6093        ComponentName comp = intent.getComponent();
6094        if (comp == null) {
6095            if (intent.getSelector() != null) {
6096                intent = intent.getSelector();
6097                comp = intent.getComponent();
6098            }
6099        }
6100        if (comp != null) {
6101            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6102            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6103            if (pi != null) {
6104                final ResolveInfo ri = new ResolveInfo();
6105                ri.providerInfo = pi;
6106                list.add(ri);
6107            }
6108            return list;
6109        }
6110
6111        // reader
6112        synchronized (mPackages) {
6113            String pkgName = intent.getPackage();
6114            if (pkgName == null) {
6115                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6116            }
6117            final PackageParser.Package pkg = mPackages.get(pkgName);
6118            if (pkg != null) {
6119                return mProviders.queryIntentForPackage(
6120                        intent, resolvedType, flags, pkg.providers, userId);
6121            }
6122            return Collections.emptyList();
6123        }
6124    }
6125
6126    @Override
6127    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6128        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6129        flags = updateFlagsForPackage(flags, userId, null);
6130        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6131        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6132                true /* requireFullPermission */, false /* checkShell */,
6133                "get installed packages");
6134
6135        // writer
6136        synchronized (mPackages) {
6137            ArrayList<PackageInfo> list;
6138            if (listUninstalled) {
6139                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6140                for (PackageSetting ps : mSettings.mPackages.values()) {
6141                    final PackageInfo pi;
6142                    if (ps.pkg != null) {
6143                        pi = generatePackageInfo(ps, flags, userId);
6144                    } else {
6145                        pi = generatePackageInfo(ps, flags, userId);
6146                    }
6147                    if (pi != null) {
6148                        list.add(pi);
6149                    }
6150                }
6151            } else {
6152                list = new ArrayList<PackageInfo>(mPackages.size());
6153                for (PackageParser.Package p : mPackages.values()) {
6154                    final PackageInfo pi =
6155                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6156                    if (pi != null) {
6157                        list.add(pi);
6158                    }
6159                }
6160            }
6161
6162            return new ParceledListSlice<PackageInfo>(list);
6163        }
6164    }
6165
6166    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6167            String[] permissions, boolean[] tmp, int flags, int userId) {
6168        int numMatch = 0;
6169        final PermissionsState permissionsState = ps.getPermissionsState();
6170        for (int i=0; i<permissions.length; i++) {
6171            final String permission = permissions[i];
6172            if (permissionsState.hasPermission(permission, userId)) {
6173                tmp[i] = true;
6174                numMatch++;
6175            } else {
6176                tmp[i] = false;
6177            }
6178        }
6179        if (numMatch == 0) {
6180            return;
6181        }
6182        final PackageInfo pi;
6183        if (ps.pkg != null) {
6184            pi = generatePackageInfo(ps, flags, userId);
6185        } else {
6186            pi = generatePackageInfo(ps, flags, userId);
6187        }
6188        // The above might return null in cases of uninstalled apps or install-state
6189        // skew across users/profiles.
6190        if (pi != null) {
6191            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6192                if (numMatch == permissions.length) {
6193                    pi.requestedPermissions = permissions;
6194                } else {
6195                    pi.requestedPermissions = new String[numMatch];
6196                    numMatch = 0;
6197                    for (int i=0; i<permissions.length; i++) {
6198                        if (tmp[i]) {
6199                            pi.requestedPermissions[numMatch] = permissions[i];
6200                            numMatch++;
6201                        }
6202                    }
6203                }
6204            }
6205            list.add(pi);
6206        }
6207    }
6208
6209    @Override
6210    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6211            String[] permissions, int flags, int userId) {
6212        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6213        flags = updateFlagsForPackage(flags, userId, permissions);
6214        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6215
6216        // writer
6217        synchronized (mPackages) {
6218            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6219            boolean[] tmpBools = new boolean[permissions.length];
6220            if (listUninstalled) {
6221                for (PackageSetting ps : mSettings.mPackages.values()) {
6222                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6223                }
6224            } else {
6225                for (PackageParser.Package pkg : mPackages.values()) {
6226                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6227                    if (ps != null) {
6228                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6229                                userId);
6230                    }
6231                }
6232            }
6233
6234            return new ParceledListSlice<PackageInfo>(list);
6235        }
6236    }
6237
6238    @Override
6239    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6240        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6241        flags = updateFlagsForApplication(flags, userId, null);
6242        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6243
6244        // writer
6245        synchronized (mPackages) {
6246            ArrayList<ApplicationInfo> list;
6247            if (listUninstalled) {
6248                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6249                for (PackageSetting ps : mSettings.mPackages.values()) {
6250                    ApplicationInfo ai;
6251                    if (ps.pkg != null) {
6252                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6253                                ps.readUserState(userId), userId);
6254                    } else {
6255                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6256                    }
6257                    if (ai != null) {
6258                        list.add(ai);
6259                    }
6260                }
6261            } else {
6262                list = new ArrayList<ApplicationInfo>(mPackages.size());
6263                for (PackageParser.Package p : mPackages.values()) {
6264                    if (p.mExtras != null) {
6265                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6266                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6267                        if (ai != null) {
6268                            list.add(ai);
6269                        }
6270                    }
6271                }
6272            }
6273
6274            return new ParceledListSlice<ApplicationInfo>(list);
6275        }
6276    }
6277
6278    @Override
6279    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6280        if (DISABLE_EPHEMERAL_APPS) {
6281            return null;
6282        }
6283
6284        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6285                "getEphemeralApplications");
6286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6287                true /* requireFullPermission */, false /* checkShell */,
6288                "getEphemeralApplications");
6289        synchronized (mPackages) {
6290            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6291                    .getEphemeralApplicationsLPw(userId);
6292            if (ephemeralApps != null) {
6293                return new ParceledListSlice<>(ephemeralApps);
6294            }
6295        }
6296        return null;
6297    }
6298
6299    @Override
6300    public boolean isEphemeralApplication(String packageName, int userId) {
6301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6302                true /* requireFullPermission */, false /* checkShell */,
6303                "isEphemeral");
6304        if (DISABLE_EPHEMERAL_APPS) {
6305            return false;
6306        }
6307
6308        if (!isCallerSameApp(packageName)) {
6309            return false;
6310        }
6311        synchronized (mPackages) {
6312            PackageParser.Package pkg = mPackages.get(packageName);
6313            if (pkg != null) {
6314                return pkg.applicationInfo.isEphemeralApp();
6315            }
6316        }
6317        return false;
6318    }
6319
6320    @Override
6321    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6322        if (DISABLE_EPHEMERAL_APPS) {
6323            return null;
6324        }
6325
6326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6327                true /* requireFullPermission */, false /* checkShell */,
6328                "getCookie");
6329        if (!isCallerSameApp(packageName)) {
6330            return null;
6331        }
6332        synchronized (mPackages) {
6333            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6334                    packageName, userId);
6335        }
6336    }
6337
6338    @Override
6339    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6340        if (DISABLE_EPHEMERAL_APPS) {
6341            return true;
6342        }
6343
6344        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6345                true /* requireFullPermission */, true /* checkShell */,
6346                "setCookie");
6347        if (!isCallerSameApp(packageName)) {
6348            return false;
6349        }
6350        synchronized (mPackages) {
6351            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6352                    packageName, cookie, userId);
6353        }
6354    }
6355
6356    @Override
6357    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6358        if (DISABLE_EPHEMERAL_APPS) {
6359            return null;
6360        }
6361
6362        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6363                "getEphemeralApplicationIcon");
6364        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6365                true /* requireFullPermission */, false /* checkShell */,
6366                "getEphemeralApplicationIcon");
6367        synchronized (mPackages) {
6368            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6369                    packageName, userId);
6370        }
6371    }
6372
6373    private boolean isCallerSameApp(String packageName) {
6374        PackageParser.Package pkg = mPackages.get(packageName);
6375        return pkg != null
6376                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6377    }
6378
6379    @Override
6380    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6381        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6382    }
6383
6384    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6385        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6386
6387        // reader
6388        synchronized (mPackages) {
6389            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6390            final int userId = UserHandle.getCallingUserId();
6391            while (i.hasNext()) {
6392                final PackageParser.Package p = i.next();
6393                if (p.applicationInfo == null) continue;
6394
6395                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6396                        && !p.applicationInfo.isDirectBootAware();
6397                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6398                        && p.applicationInfo.isDirectBootAware();
6399
6400                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6401                        && (!mSafeMode || isSystemApp(p))
6402                        && (matchesUnaware || matchesAware)) {
6403                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6404                    if (ps != null) {
6405                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6406                                ps.readUserState(userId), userId);
6407                        if (ai != null) {
6408                            finalList.add(ai);
6409                        }
6410                    }
6411                }
6412            }
6413        }
6414
6415        return finalList;
6416    }
6417
6418    @Override
6419    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6420        if (!sUserManager.exists(userId)) return null;
6421        flags = updateFlagsForComponent(flags, userId, name);
6422        // reader
6423        synchronized (mPackages) {
6424            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6425            PackageSetting ps = provider != null
6426                    ? mSettings.mPackages.get(provider.owner.packageName)
6427                    : null;
6428            return ps != null
6429                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6430                    ? PackageParser.generateProviderInfo(provider, flags,
6431                            ps.readUserState(userId), userId)
6432                    : null;
6433        }
6434    }
6435
6436    /**
6437     * @deprecated
6438     */
6439    @Deprecated
6440    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6441        // reader
6442        synchronized (mPackages) {
6443            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6444                    .entrySet().iterator();
6445            final int userId = UserHandle.getCallingUserId();
6446            while (i.hasNext()) {
6447                Map.Entry<String, PackageParser.Provider> entry = i.next();
6448                PackageParser.Provider p = entry.getValue();
6449                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6450
6451                if (ps != null && p.syncable
6452                        && (!mSafeMode || (p.info.applicationInfo.flags
6453                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6454                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6455                            ps.readUserState(userId), userId);
6456                    if (info != null) {
6457                        outNames.add(entry.getKey());
6458                        outInfo.add(info);
6459                    }
6460                }
6461            }
6462        }
6463    }
6464
6465    @Override
6466    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6467            int uid, int flags) {
6468        final int userId = processName != null ? UserHandle.getUserId(uid)
6469                : UserHandle.getCallingUserId();
6470        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6471        flags = updateFlagsForComponent(flags, userId, processName);
6472
6473        ArrayList<ProviderInfo> finalList = null;
6474        // reader
6475        synchronized (mPackages) {
6476            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6477            while (i.hasNext()) {
6478                final PackageParser.Provider p = i.next();
6479                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6480                if (ps != null && p.info.authority != null
6481                        && (processName == null
6482                                || (p.info.processName.equals(processName)
6483                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6484                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6485                    if (finalList == null) {
6486                        finalList = new ArrayList<ProviderInfo>(3);
6487                    }
6488                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6489                            ps.readUserState(userId), userId);
6490                    if (info != null) {
6491                        finalList.add(info);
6492                    }
6493                }
6494            }
6495        }
6496
6497        if (finalList != null) {
6498            Collections.sort(finalList, mProviderInitOrderSorter);
6499            return new ParceledListSlice<ProviderInfo>(finalList);
6500        }
6501
6502        return ParceledListSlice.emptyList();
6503    }
6504
6505    @Override
6506    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6507        // reader
6508        synchronized (mPackages) {
6509            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6510            return PackageParser.generateInstrumentationInfo(i, flags);
6511        }
6512    }
6513
6514    @Override
6515    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6516            String targetPackage, int flags) {
6517        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6518    }
6519
6520    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6521            int flags) {
6522        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6523
6524        // reader
6525        synchronized (mPackages) {
6526            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6527            while (i.hasNext()) {
6528                final PackageParser.Instrumentation p = i.next();
6529                if (targetPackage == null
6530                        || targetPackage.equals(p.info.targetPackage)) {
6531                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6532                            flags);
6533                    if (ii != null) {
6534                        finalList.add(ii);
6535                    }
6536                }
6537            }
6538        }
6539
6540        return finalList;
6541    }
6542
6543    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6544        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6545        if (overlays == null) {
6546            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6547            return;
6548        }
6549        for (PackageParser.Package opkg : overlays.values()) {
6550            // Not much to do if idmap fails: we already logged the error
6551            // and we certainly don't want to abort installation of pkg simply
6552            // because an overlay didn't fit properly. For these reasons,
6553            // ignore the return value of createIdmapForPackagePairLI.
6554            createIdmapForPackagePairLI(pkg, opkg);
6555        }
6556    }
6557
6558    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6559            PackageParser.Package opkg) {
6560        if (!opkg.mTrustedOverlay) {
6561            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6562                    opkg.baseCodePath + ": overlay not trusted");
6563            return false;
6564        }
6565        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6566        if (overlaySet == null) {
6567            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6568                    opkg.baseCodePath + " but target package has no known overlays");
6569            return false;
6570        }
6571        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6572        // TODO: generate idmap for split APKs
6573        try {
6574            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6575        } catch (InstallerException e) {
6576            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6577                    + opkg.baseCodePath);
6578            return false;
6579        }
6580        PackageParser.Package[] overlayArray =
6581            overlaySet.values().toArray(new PackageParser.Package[0]);
6582        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6583            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6584                return p1.mOverlayPriority - p2.mOverlayPriority;
6585            }
6586        };
6587        Arrays.sort(overlayArray, cmp);
6588
6589        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6590        int i = 0;
6591        for (PackageParser.Package p : overlayArray) {
6592            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6593        }
6594        return true;
6595    }
6596
6597    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6598        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6599        try {
6600            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6601        } finally {
6602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6603        }
6604    }
6605
6606    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6607        final File[] files = dir.listFiles();
6608        if (ArrayUtils.isEmpty(files)) {
6609            Log.d(TAG, "No files in app dir " + dir);
6610            return;
6611        }
6612
6613        if (DEBUG_PACKAGE_SCANNING) {
6614            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6615                    + " flags=0x" + Integer.toHexString(parseFlags));
6616        }
6617
6618        for (File file : files) {
6619            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6620                    && !PackageInstallerService.isStageName(file.getName());
6621            if (!isPackage) {
6622                // Ignore entries which are not packages
6623                continue;
6624            }
6625            try {
6626                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6627                        scanFlags, currentTime, null);
6628            } catch (PackageManagerException e) {
6629                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6630
6631                // Delete invalid userdata apps
6632                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6633                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6634                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6635                    removeCodePathLI(file);
6636                }
6637            }
6638        }
6639    }
6640
6641    private static File getSettingsProblemFile() {
6642        File dataDir = Environment.getDataDirectory();
6643        File systemDir = new File(dataDir, "system");
6644        File fname = new File(systemDir, "uiderrors.txt");
6645        return fname;
6646    }
6647
6648    static void reportSettingsProblem(int priority, String msg) {
6649        logCriticalInfo(priority, msg);
6650    }
6651
6652    static void logCriticalInfo(int priority, String msg) {
6653        Slog.println(priority, TAG, msg);
6654        EventLogTags.writePmCriticalInfo(msg);
6655        try {
6656            File fname = getSettingsProblemFile();
6657            FileOutputStream out = new FileOutputStream(fname, true);
6658            PrintWriter pw = new FastPrintWriter(out);
6659            SimpleDateFormat formatter = new SimpleDateFormat();
6660            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6661            pw.println(dateString + ": " + msg);
6662            pw.close();
6663            FileUtils.setPermissions(
6664                    fname.toString(),
6665                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6666                    -1, -1);
6667        } catch (java.io.IOException e) {
6668        }
6669    }
6670
6671    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6672            final int policyFlags) throws PackageManagerException {
6673        if (ps != null
6674                && ps.codePath.equals(srcFile)
6675                && ps.timeStamp == srcFile.lastModified()
6676                && !isCompatSignatureUpdateNeeded(pkg)
6677                && !isRecoverSignatureUpdateNeeded(pkg)) {
6678            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6679            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6680            ArraySet<PublicKey> signingKs;
6681            synchronized (mPackages) {
6682                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6683            }
6684            if (ps.signatures.mSignatures != null
6685                    && ps.signatures.mSignatures.length != 0
6686                    && signingKs != null) {
6687                // Optimization: reuse the existing cached certificates
6688                // if the package appears to be unchanged.
6689                pkg.mSignatures = ps.signatures.mSignatures;
6690                pkg.mSigningKeys = signingKs;
6691                return;
6692            }
6693
6694            Slog.w(TAG, "PackageSetting for " + ps.name
6695                    + " is missing signatures.  Collecting certs again to recover them.");
6696        } else {
6697            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6698        }
6699
6700        try {
6701            PackageParser.collectCertificates(pkg, policyFlags);
6702        } catch (PackageParserException e) {
6703            throw PackageManagerException.from(e);
6704        }
6705    }
6706
6707    /**
6708     *  Traces a package scan.
6709     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6710     */
6711    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6712            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6713        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6714        try {
6715            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6716        } finally {
6717            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6718        }
6719    }
6720
6721    /**
6722     *  Scans a package and returns the newly parsed package.
6723     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6724     */
6725    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6726            long currentTime, UserHandle user) throws PackageManagerException {
6727        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6728        PackageParser pp = new PackageParser();
6729        pp.setSeparateProcesses(mSeparateProcesses);
6730        pp.setOnlyCoreApps(mOnlyCore);
6731        pp.setDisplayMetrics(mMetrics);
6732
6733        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6734            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6735        }
6736
6737        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6738        final PackageParser.Package pkg;
6739        try {
6740            pkg = pp.parsePackage(scanFile, parseFlags);
6741        } catch (PackageParserException e) {
6742            throw PackageManagerException.from(e);
6743        } finally {
6744            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6745        }
6746
6747        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6748    }
6749
6750    /**
6751     *  Scans a package and returns the newly parsed package.
6752     *  @throws PackageManagerException on a parse error.
6753     */
6754    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6755            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6756            throws PackageManagerException {
6757        // If the package has children and this is the first dive in the function
6758        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6759        // packages (parent and children) would be successfully scanned before the
6760        // actual scan since scanning mutates internal state and we want to atomically
6761        // install the package and its children.
6762        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6763            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6764                scanFlags |= SCAN_CHECK_ONLY;
6765            }
6766        } else {
6767            scanFlags &= ~SCAN_CHECK_ONLY;
6768        }
6769
6770        // Scan the parent
6771        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6772                scanFlags, currentTime, user);
6773
6774        // Scan the children
6775        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6776        for (int i = 0; i < childCount; i++) {
6777            PackageParser.Package childPackage = pkg.childPackages.get(i);
6778            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6779                    currentTime, user);
6780        }
6781
6782
6783        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6784            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6785        }
6786
6787        return scannedPkg;
6788    }
6789
6790    /**
6791     *  Scans a package and returns the newly parsed package.
6792     *  @throws PackageManagerException on a parse error.
6793     */
6794    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6795            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6796            throws PackageManagerException {
6797        PackageSetting ps = null;
6798        PackageSetting updatedPkg;
6799        // reader
6800        synchronized (mPackages) {
6801            // Look to see if we already know about this package.
6802            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6803            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6804                // This package has been renamed to its original name.  Let's
6805                // use that.
6806                ps = mSettings.peekPackageLPr(oldName);
6807            }
6808            // If there was no original package, see one for the real package name.
6809            if (ps == null) {
6810                ps = mSettings.peekPackageLPr(pkg.packageName);
6811            }
6812            // Check to see if this package could be hiding/updating a system
6813            // package.  Must look for it either under the original or real
6814            // package name depending on our state.
6815            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6816            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6817
6818            // If this is a package we don't know about on the system partition, we
6819            // may need to remove disabled child packages on the system partition
6820            // or may need to not add child packages if the parent apk is updated
6821            // on the data partition and no longer defines this child package.
6822            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6823                // If this is a parent package for an updated system app and this system
6824                // app got an OTA update which no longer defines some of the child packages
6825                // we have to prune them from the disabled system packages.
6826                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6827                if (disabledPs != null) {
6828                    final int scannedChildCount = (pkg.childPackages != null)
6829                            ? pkg.childPackages.size() : 0;
6830                    final int disabledChildCount = disabledPs.childPackageNames != null
6831                            ? disabledPs.childPackageNames.size() : 0;
6832                    for (int i = 0; i < disabledChildCount; i++) {
6833                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6834                        boolean disabledPackageAvailable = false;
6835                        for (int j = 0; j < scannedChildCount; j++) {
6836                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6837                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6838                                disabledPackageAvailable = true;
6839                                break;
6840                            }
6841                         }
6842                         if (!disabledPackageAvailable) {
6843                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6844                         }
6845                    }
6846                }
6847            }
6848        }
6849
6850        boolean updatedPkgBetter = false;
6851        // First check if this is a system package that may involve an update
6852        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6853            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6854            // it needs to drop FLAG_PRIVILEGED.
6855            if (locationIsPrivileged(scanFile)) {
6856                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6857            } else {
6858                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6859            }
6860
6861            if (ps != null && !ps.codePath.equals(scanFile)) {
6862                // The path has changed from what was last scanned...  check the
6863                // version of the new path against what we have stored to determine
6864                // what to do.
6865                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6866                if (pkg.mVersionCode <= ps.versionCode) {
6867                    // The system package has been updated and the code path does not match
6868                    // Ignore entry. Skip it.
6869                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6870                            + " ignored: updated version " + ps.versionCode
6871                            + " better than this " + pkg.mVersionCode);
6872                    if (!updatedPkg.codePath.equals(scanFile)) {
6873                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6874                                + ps.name + " changing from " + updatedPkg.codePathString
6875                                + " to " + scanFile);
6876                        updatedPkg.codePath = scanFile;
6877                        updatedPkg.codePathString = scanFile.toString();
6878                        updatedPkg.resourcePath = scanFile;
6879                        updatedPkg.resourcePathString = scanFile.toString();
6880                    }
6881                    updatedPkg.pkg = pkg;
6882                    updatedPkg.versionCode = pkg.mVersionCode;
6883
6884                    // Update the disabled system child packages to point to the package too.
6885                    final int childCount = updatedPkg.childPackageNames != null
6886                            ? updatedPkg.childPackageNames.size() : 0;
6887                    for (int i = 0; i < childCount; i++) {
6888                        String childPackageName = updatedPkg.childPackageNames.get(i);
6889                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6890                                childPackageName);
6891                        if (updatedChildPkg != null) {
6892                            updatedChildPkg.pkg = pkg;
6893                            updatedChildPkg.versionCode = pkg.mVersionCode;
6894                        }
6895                    }
6896
6897                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6898                            + scanFile + " ignored: updated version " + ps.versionCode
6899                            + " better than this " + pkg.mVersionCode);
6900                } else {
6901                    // The current app on the system partition is better than
6902                    // what we have updated to on the data partition; switch
6903                    // back to the system partition version.
6904                    // At this point, its safely assumed that package installation for
6905                    // apps in system partition will go through. If not there won't be a working
6906                    // version of the app
6907                    // writer
6908                    synchronized (mPackages) {
6909                        // Just remove the loaded entries from package lists.
6910                        mPackages.remove(ps.name);
6911                    }
6912
6913                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6914                            + " reverting from " + ps.codePathString
6915                            + ": new version " + pkg.mVersionCode
6916                            + " better than installed " + ps.versionCode);
6917
6918                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6919                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6920                    synchronized (mInstallLock) {
6921                        args.cleanUpResourcesLI();
6922                    }
6923                    synchronized (mPackages) {
6924                        mSettings.enableSystemPackageLPw(ps.name);
6925                    }
6926                    updatedPkgBetter = true;
6927                }
6928            }
6929        }
6930
6931        if (updatedPkg != null) {
6932            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6933            // initially
6934            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6935
6936            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6937            // flag set initially
6938            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6939                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6940            }
6941        }
6942
6943        // Verify certificates against what was last scanned
6944        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6945
6946        /*
6947         * A new system app appeared, but we already had a non-system one of the
6948         * same name installed earlier.
6949         */
6950        boolean shouldHideSystemApp = false;
6951        if (updatedPkg == null && ps != null
6952                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6953            /*
6954             * Check to make sure the signatures match first. If they don't,
6955             * wipe the installed application and its data.
6956             */
6957            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6958                    != PackageManager.SIGNATURE_MATCH) {
6959                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6960                        + " signatures don't match existing userdata copy; removing");
6961                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6962                        "scanPackageInternalLI")) {
6963                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6964                }
6965                ps = null;
6966            } else {
6967                /*
6968                 * If the newly-added system app is an older version than the
6969                 * already installed version, hide it. It will be scanned later
6970                 * and re-added like an update.
6971                 */
6972                if (pkg.mVersionCode <= ps.versionCode) {
6973                    shouldHideSystemApp = true;
6974                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6975                            + " but new version " + pkg.mVersionCode + " better than installed "
6976                            + ps.versionCode + "; hiding system");
6977                } else {
6978                    /*
6979                     * The newly found system app is a newer version that the
6980                     * one previously installed. Simply remove the
6981                     * already-installed application and replace it with our own
6982                     * while keeping the application data.
6983                     */
6984                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6985                            + " reverting from " + ps.codePathString + ": new version "
6986                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6987                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6988                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6989                    synchronized (mInstallLock) {
6990                        args.cleanUpResourcesLI();
6991                    }
6992                }
6993            }
6994        }
6995
6996        // The apk is forward locked (not public) if its code and resources
6997        // are kept in different files. (except for app in either system or
6998        // vendor path).
6999        // TODO grab this value from PackageSettings
7000        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7001            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7002                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7003            }
7004        }
7005
7006        // TODO: extend to support forward-locked splits
7007        String resourcePath = null;
7008        String baseResourcePath = null;
7009        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7010            if (ps != null && ps.resourcePathString != null) {
7011                resourcePath = ps.resourcePathString;
7012                baseResourcePath = ps.resourcePathString;
7013            } else {
7014                // Should not happen at all. Just log an error.
7015                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7016            }
7017        } else {
7018            resourcePath = pkg.codePath;
7019            baseResourcePath = pkg.baseCodePath;
7020        }
7021
7022        // Set application objects path explicitly.
7023        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7024        pkg.setApplicationInfoCodePath(pkg.codePath);
7025        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7026        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7027        pkg.setApplicationInfoResourcePath(resourcePath);
7028        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7029        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7030
7031        // Note that we invoke the following method only if we are about to unpack an application
7032        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7033                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7034
7035        /*
7036         * If the system app should be overridden by a previously installed
7037         * data, hide the system app now and let the /data/app scan pick it up
7038         * again.
7039         */
7040        if (shouldHideSystemApp) {
7041            synchronized (mPackages) {
7042                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7043            }
7044        }
7045
7046        return scannedPkg;
7047    }
7048
7049    private static String fixProcessName(String defProcessName,
7050            String processName, int uid) {
7051        if (processName == null) {
7052            return defProcessName;
7053        }
7054        return processName;
7055    }
7056
7057    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7058            throws PackageManagerException {
7059        if (pkgSetting.signatures.mSignatures != null) {
7060            // Already existing package. Make sure signatures match
7061            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7062                    == PackageManager.SIGNATURE_MATCH;
7063            if (!match) {
7064                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7065                        == PackageManager.SIGNATURE_MATCH;
7066            }
7067            if (!match) {
7068                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7069                        == PackageManager.SIGNATURE_MATCH;
7070            }
7071            if (!match) {
7072                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7073                        + pkg.packageName + " signatures do not match the "
7074                        + "previously installed version; ignoring!");
7075            }
7076        }
7077
7078        // Check for shared user signatures
7079        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7080            // Already existing package. Make sure signatures match
7081            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7082                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7083            if (!match) {
7084                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7085                        == PackageManager.SIGNATURE_MATCH;
7086            }
7087            if (!match) {
7088                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7089                        == PackageManager.SIGNATURE_MATCH;
7090            }
7091            if (!match) {
7092                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7093                        "Package " + pkg.packageName
7094                        + " has no signatures that match those in shared user "
7095                        + pkgSetting.sharedUser.name + "; ignoring!");
7096            }
7097        }
7098    }
7099
7100    /**
7101     * Enforces that only the system UID or root's UID can call a method exposed
7102     * via Binder.
7103     *
7104     * @param message used as message if SecurityException is thrown
7105     * @throws SecurityException if the caller is not system or root
7106     */
7107    private static final void enforceSystemOrRoot(String message) {
7108        final int uid = Binder.getCallingUid();
7109        if (uid != Process.SYSTEM_UID && uid != 0) {
7110            throw new SecurityException(message);
7111        }
7112    }
7113
7114    @Override
7115    public void performFstrimIfNeeded() {
7116        enforceSystemOrRoot("Only the system can request fstrim");
7117
7118        // Before everything else, see whether we need to fstrim.
7119        try {
7120            IMountService ms = PackageHelper.getMountService();
7121            if (ms != null) {
7122                final boolean isUpgrade = isUpgrade();
7123                boolean doTrim = isUpgrade;
7124                if (doTrim) {
7125                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7126                } else {
7127                    final long interval = android.provider.Settings.Global.getLong(
7128                            mContext.getContentResolver(),
7129                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7130                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7131                    if (interval > 0) {
7132                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7133                        if (timeSinceLast > interval) {
7134                            doTrim = true;
7135                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7136                                    + "; running immediately");
7137                        }
7138                    }
7139                }
7140                if (doTrim) {
7141                    if (!isFirstBoot()) {
7142                        try {
7143                            ActivityManagerNative.getDefault().showBootMessage(
7144                                    mContext.getResources().getString(
7145                                            R.string.android_upgrading_fstrim), true);
7146                        } catch (RemoteException e) {
7147                        }
7148                    }
7149                    ms.runMaintenance();
7150                }
7151            } else {
7152                Slog.e(TAG, "Mount service unavailable!");
7153            }
7154        } catch (RemoteException e) {
7155            // Can't happen; MountService is local
7156        }
7157    }
7158
7159    @Override
7160    public void updatePackagesIfNeeded() {
7161        enforceSystemOrRoot("Only the system can request package update");
7162
7163        // We need to re-extract after an OTA.
7164        boolean causeUpgrade = isUpgrade();
7165
7166        // First boot or factory reset.
7167        // Note: we also handle devices that are upgrading to N right now as if it is their
7168        //       first boot, as they do not have profile data.
7169        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7170
7171        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7172        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7173
7174        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7175            return;
7176        }
7177
7178        List<PackageParser.Package> pkgs;
7179        synchronized (mPackages) {
7180            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7181        }
7182
7183        int curr = 0;
7184        int total = pkgs.size();
7185        for (PackageParser.Package pkg : pkgs) {
7186            curr++;
7187
7188            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7189                if (DEBUG_DEXOPT) {
7190                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7191                }
7192                continue;
7193            }
7194
7195            if (DEBUG_DEXOPT) {
7196                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7197            }
7198
7199            if (!isFirstBoot()) {
7200                try {
7201                    ActivityManagerNative.getDefault().showBootMessage(
7202                            mContext.getResources().getString(R.string.android_upgrading_apk,
7203                                    curr, total), true);
7204                } catch (RemoteException e) {
7205                }
7206            }
7207
7208            performDexOpt(pkg.packageName,
7209                    null /* instructionSet */,
7210                    true /* checkProfiles */,
7211                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7212                    false /* force */);
7213        }
7214    }
7215
7216    @Override
7217    public void notifyPackageUse(String packageName, int reason) {
7218        synchronized (mPackages) {
7219            PackageParser.Package p = mPackages.get(packageName);
7220            if (p == null) {
7221                return;
7222            }
7223            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7224        }
7225    }
7226
7227    // TODO: this is not used nor needed. Delete it.
7228    @Override
7229    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7230        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7231                getFullCompilerFilter(), false /* force */);
7232    }
7233
7234    @Override
7235    public boolean performDexOpt(String packageName, String instructionSet,
7236            boolean checkProfiles, int compileReason, boolean force) {
7237        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7238                getCompilerFilterForReason(compileReason), force);
7239    }
7240
7241    @Override
7242    public boolean performDexOptMode(String packageName, String instructionSet,
7243            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7244        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7245                targetCompilerFilter, force);
7246    }
7247
7248    private boolean performDexOptTraced(String packageName, String instructionSet,
7249                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7250        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7251        try {
7252            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7253                    targetCompilerFilter, force);
7254        } finally {
7255            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7256        }
7257    }
7258
7259    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7260    // if the package can now be considered up to date for the given filter.
7261    private boolean performDexOptInternal(String packageName, String instructionSet,
7262                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7263        PackageParser.Package p;
7264        final String targetInstructionSet;
7265        synchronized (mPackages) {
7266            p = mPackages.get(packageName);
7267            if (p == null) {
7268                return false;
7269            }
7270            mPackageUsage.write(false);
7271
7272            targetInstructionSet = instructionSet != null ? instructionSet :
7273                    getPrimaryInstructionSet(p.applicationInfo);
7274        }
7275        long callingId = Binder.clearCallingIdentity();
7276        try {
7277            synchronized (mInstallLock) {
7278                final String[] instructionSets = new String[] { targetInstructionSet };
7279                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7280                        checkProfiles, targetCompilerFilter, force);
7281                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7282            }
7283        } finally {
7284            Binder.restoreCallingIdentity(callingId);
7285        }
7286    }
7287
7288    public ArraySet<String> getOptimizablePackages() {
7289        ArraySet<String> pkgs = new ArraySet<String>();
7290        synchronized (mPackages) {
7291            for (PackageParser.Package p : mPackages.values()) {
7292                if (PackageDexOptimizer.canOptimizePackage(p)) {
7293                    pkgs.add(p.packageName);
7294                }
7295            }
7296        }
7297        return pkgs;
7298    }
7299
7300    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7301            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7302            boolean force) {
7303        // Select the dex optimizer based on the force parameter.
7304        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7305        //       allocate an object here.
7306        PackageDexOptimizer pdo = force
7307                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7308                : mPackageDexOptimizer;
7309
7310        // Optimize all dependencies first. Note: we ignore the return value and march on
7311        // on errors.
7312        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7313        if (!deps.isEmpty()) {
7314            for (PackageParser.Package depPackage : deps) {
7315                // TODO: Analyze and investigate if we (should) profile libraries.
7316                // Currently this will do a full compilation of the library by default.
7317                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7318                        false /* checkProfiles */,
7319                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7320            }
7321        }
7322
7323        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7324                targetCompilerFilter);
7325    }
7326
7327    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7328        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7329            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7330            Set<String> collectedNames = new HashSet<>();
7331            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7332
7333            retValue.remove(p);
7334
7335            return retValue;
7336        } else {
7337            return Collections.emptyList();
7338        }
7339    }
7340
7341    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7342            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7343        if (!collectedNames.contains(p.packageName)) {
7344            collectedNames.add(p.packageName);
7345            collected.add(p);
7346
7347            if (p.usesLibraries != null) {
7348                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7349            }
7350            if (p.usesOptionalLibraries != null) {
7351                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7352                        collectedNames);
7353            }
7354        }
7355    }
7356
7357    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7358            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7359        for (String libName : libs) {
7360            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7361            if (libPkg != null) {
7362                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7363            }
7364        }
7365    }
7366
7367    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7368        synchronized (mPackages) {
7369            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7370            if (lib != null && lib.apk != null) {
7371                return mPackages.get(lib.apk);
7372            }
7373        }
7374        return null;
7375    }
7376
7377    public void shutdown() {
7378        mPackageUsage.write(true);
7379    }
7380
7381    @Override
7382    public void forceDexOpt(String packageName) {
7383        enforceSystemOrRoot("forceDexOpt");
7384
7385        PackageParser.Package pkg;
7386        synchronized (mPackages) {
7387            pkg = mPackages.get(packageName);
7388            if (pkg == null) {
7389                throw new IllegalArgumentException("Unknown package: " + packageName);
7390            }
7391        }
7392
7393        synchronized (mInstallLock) {
7394            final String[] instructionSets = new String[] {
7395                    getPrimaryInstructionSet(pkg.applicationInfo) };
7396
7397            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7398
7399            // Whoever is calling forceDexOpt wants a fully compiled package.
7400            // Don't use profiles since that may cause compilation to be skipped.
7401            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7402                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7403                    true /* force */);
7404
7405            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7406            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7407                throw new IllegalStateException("Failed to dexopt: " + res);
7408            }
7409        }
7410    }
7411
7412    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7413        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7414            Slog.w(TAG, "Unable to update from " + oldPkg.name
7415                    + " to " + newPkg.packageName
7416                    + ": old package not in system partition");
7417            return false;
7418        } else if (mPackages.get(oldPkg.name) != null) {
7419            Slog.w(TAG, "Unable to update from " + oldPkg.name
7420                    + " to " + newPkg.packageName
7421                    + ": old package still exists");
7422            return false;
7423        }
7424        return true;
7425    }
7426
7427    void removeCodePathLI(File codePath) {
7428        if (codePath.isDirectory()) {
7429            try {
7430                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7431            } catch (InstallerException e) {
7432                Slog.w(TAG, "Failed to remove code path", e);
7433            }
7434        } else {
7435            codePath.delete();
7436        }
7437    }
7438
7439    private int[] resolveUserIds(int userId) {
7440        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7441    }
7442
7443    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7444        if (pkg == null) {
7445            Slog.wtf(TAG, "Package was null!", new Throwable());
7446            return;
7447        }
7448        clearAppDataLeafLIF(pkg, userId, flags);
7449        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7450        for (int i = 0; i < childCount; i++) {
7451            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7452        }
7453    }
7454
7455    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7456        final PackageSetting ps;
7457        synchronized (mPackages) {
7458            ps = mSettings.mPackages.get(pkg.packageName);
7459        }
7460        for (int realUserId : resolveUserIds(userId)) {
7461            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7462            try {
7463                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7464                        ceDataInode);
7465            } catch (InstallerException e) {
7466                Slog.w(TAG, String.valueOf(e));
7467            }
7468        }
7469    }
7470
7471    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7472        if (pkg == null) {
7473            Slog.wtf(TAG, "Package was null!", new Throwable());
7474            return;
7475        }
7476        destroyAppDataLeafLIF(pkg, userId, flags);
7477        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7478        for (int i = 0; i < childCount; i++) {
7479            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7480        }
7481    }
7482
7483    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7484        final PackageSetting ps;
7485        synchronized (mPackages) {
7486            ps = mSettings.mPackages.get(pkg.packageName);
7487        }
7488        for (int realUserId : resolveUserIds(userId)) {
7489            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7490            try {
7491                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7492                        ceDataInode);
7493            } catch (InstallerException e) {
7494                Slog.w(TAG, String.valueOf(e));
7495            }
7496        }
7497    }
7498
7499    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7500        if (pkg == null) {
7501            Slog.wtf(TAG, "Package was null!", new Throwable());
7502            return;
7503        }
7504        destroyAppProfilesLeafLIF(pkg);
7505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7506        for (int i = 0; i < childCount; i++) {
7507            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7508        }
7509    }
7510
7511    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7512        try {
7513            mInstaller.destroyAppProfiles(pkg.packageName);
7514        } catch (InstallerException e) {
7515            Slog.w(TAG, String.valueOf(e));
7516        }
7517    }
7518
7519    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7520        if (pkg == null) {
7521            Slog.wtf(TAG, "Package was null!", new Throwable());
7522            return;
7523        }
7524        clearAppProfilesLeafLIF(pkg);
7525        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7526        for (int i = 0; i < childCount; i++) {
7527            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7528        }
7529    }
7530
7531    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7532        try {
7533            mInstaller.clearAppProfiles(pkg.packageName);
7534        } catch (InstallerException e) {
7535            Slog.w(TAG, String.valueOf(e));
7536        }
7537    }
7538
7539    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7540            long lastUpdateTime) {
7541        // Set parent install/update time
7542        PackageSetting ps = (PackageSetting) pkg.mExtras;
7543        if (ps != null) {
7544            ps.firstInstallTime = firstInstallTime;
7545            ps.lastUpdateTime = lastUpdateTime;
7546        }
7547        // Set children install/update time
7548        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7549        for (int i = 0; i < childCount; i++) {
7550            PackageParser.Package childPkg = pkg.childPackages.get(i);
7551            ps = (PackageSetting) childPkg.mExtras;
7552            if (ps != null) {
7553                ps.firstInstallTime = firstInstallTime;
7554                ps.lastUpdateTime = lastUpdateTime;
7555            }
7556        }
7557    }
7558
7559    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7560            PackageParser.Package changingLib) {
7561        if (file.path != null) {
7562            usesLibraryFiles.add(file.path);
7563            return;
7564        }
7565        PackageParser.Package p = mPackages.get(file.apk);
7566        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7567            // If we are doing this while in the middle of updating a library apk,
7568            // then we need to make sure to use that new apk for determining the
7569            // dependencies here.  (We haven't yet finished committing the new apk
7570            // to the package manager state.)
7571            if (p == null || p.packageName.equals(changingLib.packageName)) {
7572                p = changingLib;
7573            }
7574        }
7575        if (p != null) {
7576            usesLibraryFiles.addAll(p.getAllCodePaths());
7577        }
7578    }
7579
7580    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7581            PackageParser.Package changingLib) throws PackageManagerException {
7582        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7583            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7584            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7585            for (int i=0; i<N; i++) {
7586                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7587                if (file == null) {
7588                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7589                            "Package " + pkg.packageName + " requires unavailable shared library "
7590                            + pkg.usesLibraries.get(i) + "; failing!");
7591                }
7592                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7593            }
7594            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7595            for (int i=0; i<N; i++) {
7596                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7597                if (file == null) {
7598                    Slog.w(TAG, "Package " + pkg.packageName
7599                            + " desires unavailable shared library "
7600                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7601                } else {
7602                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7603                }
7604            }
7605            N = usesLibraryFiles.size();
7606            if (N > 0) {
7607                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7608            } else {
7609                pkg.usesLibraryFiles = null;
7610            }
7611        }
7612    }
7613
7614    private static boolean hasString(List<String> list, List<String> which) {
7615        if (list == null) {
7616            return false;
7617        }
7618        for (int i=list.size()-1; i>=0; i--) {
7619            for (int j=which.size()-1; j>=0; j--) {
7620                if (which.get(j).equals(list.get(i))) {
7621                    return true;
7622                }
7623            }
7624        }
7625        return false;
7626    }
7627
7628    private void updateAllSharedLibrariesLPw() {
7629        for (PackageParser.Package pkg : mPackages.values()) {
7630            try {
7631                updateSharedLibrariesLPw(pkg, null);
7632            } catch (PackageManagerException e) {
7633                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7634            }
7635        }
7636    }
7637
7638    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7639            PackageParser.Package changingPkg) {
7640        ArrayList<PackageParser.Package> res = null;
7641        for (PackageParser.Package pkg : mPackages.values()) {
7642            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7643                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7644                if (res == null) {
7645                    res = new ArrayList<PackageParser.Package>();
7646                }
7647                res.add(pkg);
7648                try {
7649                    updateSharedLibrariesLPw(pkg, changingPkg);
7650                } catch (PackageManagerException e) {
7651                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7652                }
7653            }
7654        }
7655        return res;
7656    }
7657
7658    /**
7659     * Derive the value of the {@code cpuAbiOverride} based on the provided
7660     * value and an optional stored value from the package settings.
7661     */
7662    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7663        String cpuAbiOverride = null;
7664
7665        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7666            cpuAbiOverride = null;
7667        } else if (abiOverride != null) {
7668            cpuAbiOverride = abiOverride;
7669        } else if (settings != null) {
7670            cpuAbiOverride = settings.cpuAbiOverrideString;
7671        }
7672
7673        return cpuAbiOverride;
7674    }
7675
7676    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7677            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7678                    throws PackageManagerException {
7679        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7680        // If the package has children and this is the first dive in the function
7681        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7682        // whether all packages (parent and children) would be successfully scanned
7683        // before the actual scan since scanning mutates internal state and we want
7684        // to atomically install the package and its children.
7685        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7686            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7687                scanFlags |= SCAN_CHECK_ONLY;
7688            }
7689        } else {
7690            scanFlags &= ~SCAN_CHECK_ONLY;
7691        }
7692
7693        final PackageParser.Package scannedPkg;
7694        try {
7695            // Scan the parent
7696            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7697            // Scan the children
7698            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7699            for (int i = 0; i < childCount; i++) {
7700                PackageParser.Package childPkg = pkg.childPackages.get(i);
7701                scanPackageLI(childPkg, policyFlags,
7702                        scanFlags, currentTime, user);
7703            }
7704        } finally {
7705            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7706        }
7707
7708        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7709            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7710        }
7711
7712        return scannedPkg;
7713    }
7714
7715    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7716            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7717        boolean success = false;
7718        try {
7719            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7720                    currentTime, user);
7721            success = true;
7722            return res;
7723        } finally {
7724            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7725                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7726                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7727                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7728                destroyAppProfilesLIF(pkg);
7729            }
7730        }
7731    }
7732
7733    /**
7734     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7735     */
7736    private static boolean apkHasCode(String fileName) {
7737        StrictJarFile jarFile = null;
7738        try {
7739            jarFile = new StrictJarFile(fileName,
7740                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7741            return jarFile.findEntry("classes.dex") != null;
7742        } catch (IOException ignore) {
7743        } finally {
7744            try {
7745                jarFile.close();
7746            } catch (IOException ignore) {}
7747        }
7748        return false;
7749    }
7750
7751    /**
7752     * Enforces code policy for the package. This ensures that if an APK has
7753     * declared hasCode="true" in its manifest that the APK actually contains
7754     * code.
7755     *
7756     * @throws PackageManagerException If bytecode could not be found when it should exist
7757     */
7758    private static void enforceCodePolicy(PackageParser.Package pkg)
7759            throws PackageManagerException {
7760        final boolean shouldHaveCode =
7761                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7762        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7763            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7764                    "Package " + pkg.baseCodePath + " code is missing");
7765        }
7766
7767        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7768            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7769                final boolean splitShouldHaveCode =
7770                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7771                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7772                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7773                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7774                }
7775            }
7776        }
7777    }
7778
7779    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7780            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7781            throws PackageManagerException {
7782        final File scanFile = new File(pkg.codePath);
7783        if (pkg.applicationInfo.getCodePath() == null ||
7784                pkg.applicationInfo.getResourcePath() == null) {
7785            // Bail out. The resource and code paths haven't been set.
7786            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7787                    "Code and resource paths haven't been set correctly");
7788        }
7789
7790        // Apply policy
7791        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7792            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7793            if (pkg.applicationInfo.isDirectBootAware()) {
7794                // we're direct boot aware; set for all components
7795                for (PackageParser.Service s : pkg.services) {
7796                    s.info.encryptionAware = s.info.directBootAware = true;
7797                }
7798                for (PackageParser.Provider p : pkg.providers) {
7799                    p.info.encryptionAware = p.info.directBootAware = true;
7800                }
7801                for (PackageParser.Activity a : pkg.activities) {
7802                    a.info.encryptionAware = a.info.directBootAware = true;
7803                }
7804                for (PackageParser.Activity r : pkg.receivers) {
7805                    r.info.encryptionAware = r.info.directBootAware = true;
7806                }
7807            }
7808        } else {
7809            // Only allow system apps to be flagged as core apps.
7810            pkg.coreApp = false;
7811            // clear flags not applicable to regular apps
7812            pkg.applicationInfo.privateFlags &=
7813                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7814            pkg.applicationInfo.privateFlags &=
7815                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7816        }
7817        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7818
7819        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7820            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7821        }
7822
7823        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7824            enforceCodePolicy(pkg);
7825        }
7826
7827        if (mCustomResolverComponentName != null &&
7828                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7829            setUpCustomResolverActivity(pkg);
7830        }
7831
7832        if (pkg.packageName.equals("android")) {
7833            synchronized (mPackages) {
7834                if (mAndroidApplication != null) {
7835                    Slog.w(TAG, "*************************************************");
7836                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7837                    Slog.w(TAG, " file=" + scanFile);
7838                    Slog.w(TAG, "*************************************************");
7839                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7840                            "Core android package being redefined.  Skipping.");
7841                }
7842
7843                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7844                    // Set up information for our fall-back user intent resolution activity.
7845                    mPlatformPackage = pkg;
7846                    pkg.mVersionCode = mSdkVersion;
7847                    mAndroidApplication = pkg.applicationInfo;
7848
7849                    if (!mResolverReplaced) {
7850                        mResolveActivity.applicationInfo = mAndroidApplication;
7851                        mResolveActivity.name = ResolverActivity.class.getName();
7852                        mResolveActivity.packageName = mAndroidApplication.packageName;
7853                        mResolveActivity.processName = "system:ui";
7854                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7855                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7856                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7857                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7858                        mResolveActivity.exported = true;
7859                        mResolveActivity.enabled = true;
7860                        mResolveInfo.activityInfo = mResolveActivity;
7861                        mResolveInfo.priority = 0;
7862                        mResolveInfo.preferredOrder = 0;
7863                        mResolveInfo.match = 0;
7864                        mResolveComponentName = new ComponentName(
7865                                mAndroidApplication.packageName, mResolveActivity.name);
7866                    }
7867                }
7868            }
7869        }
7870
7871        if (DEBUG_PACKAGE_SCANNING) {
7872            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7873                Log.d(TAG, "Scanning package " + pkg.packageName);
7874        }
7875
7876        synchronized (mPackages) {
7877            if (mPackages.containsKey(pkg.packageName)
7878                    || mSharedLibraries.containsKey(pkg.packageName)) {
7879                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7880                        "Application package " + pkg.packageName
7881                                + " already installed.  Skipping duplicate.");
7882            }
7883
7884            // If we're only installing presumed-existing packages, require that the
7885            // scanned APK is both already known and at the path previously established
7886            // for it.  Previously unknown packages we pick up normally, but if we have an
7887            // a priori expectation about this package's install presence, enforce it.
7888            // With a singular exception for new system packages. When an OTA contains
7889            // a new system package, we allow the codepath to change from a system location
7890            // to the user-installed location. If we don't allow this change, any newer,
7891            // user-installed version of the application will be ignored.
7892            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7893                if (mExpectingBetter.containsKey(pkg.packageName)) {
7894                    logCriticalInfo(Log.WARN,
7895                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7896                } else {
7897                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7898                    if (known != null) {
7899                        if (DEBUG_PACKAGE_SCANNING) {
7900                            Log.d(TAG, "Examining " + pkg.codePath
7901                                    + " and requiring known paths " + known.codePathString
7902                                    + " & " + known.resourcePathString);
7903                        }
7904                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7905                                || !pkg.applicationInfo.getResourcePath().equals(
7906                                known.resourcePathString)) {
7907                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7908                                    "Application package " + pkg.packageName
7909                                            + " found at " + pkg.applicationInfo.getCodePath()
7910                                            + " but expected at " + known.codePathString
7911                                            + "; ignoring.");
7912                        }
7913                    }
7914                }
7915            }
7916        }
7917
7918        // Initialize package source and resource directories
7919        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7920        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7921
7922        SharedUserSetting suid = null;
7923        PackageSetting pkgSetting = null;
7924
7925        if (!isSystemApp(pkg)) {
7926            // Only system apps can use these features.
7927            pkg.mOriginalPackages = null;
7928            pkg.mRealPackage = null;
7929            pkg.mAdoptPermissions = null;
7930        }
7931
7932        // Getting the package setting may have a side-effect, so if we
7933        // are only checking if scan would succeed, stash a copy of the
7934        // old setting to restore at the end.
7935        PackageSetting nonMutatedPs = null;
7936
7937        // writer
7938        synchronized (mPackages) {
7939            if (pkg.mSharedUserId != null) {
7940                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7941                if (suid == null) {
7942                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7943                            "Creating application package " + pkg.packageName
7944                            + " for shared user failed");
7945                }
7946                if (DEBUG_PACKAGE_SCANNING) {
7947                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7948                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7949                                + "): packages=" + suid.packages);
7950                }
7951            }
7952
7953            // Check if we are renaming from an original package name.
7954            PackageSetting origPackage = null;
7955            String realName = null;
7956            if (pkg.mOriginalPackages != null) {
7957                // This package may need to be renamed to a previously
7958                // installed name.  Let's check on that...
7959                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7960                if (pkg.mOriginalPackages.contains(renamed)) {
7961                    // This package had originally been installed as the
7962                    // original name, and we have already taken care of
7963                    // transitioning to the new one.  Just update the new
7964                    // one to continue using the old name.
7965                    realName = pkg.mRealPackage;
7966                    if (!pkg.packageName.equals(renamed)) {
7967                        // Callers into this function may have already taken
7968                        // care of renaming the package; only do it here if
7969                        // it is not already done.
7970                        pkg.setPackageName(renamed);
7971                    }
7972
7973                } else {
7974                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7975                        if ((origPackage = mSettings.peekPackageLPr(
7976                                pkg.mOriginalPackages.get(i))) != null) {
7977                            // We do have the package already installed under its
7978                            // original name...  should we use it?
7979                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7980                                // New package is not compatible with original.
7981                                origPackage = null;
7982                                continue;
7983                            } else if (origPackage.sharedUser != null) {
7984                                // Make sure uid is compatible between packages.
7985                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7986                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7987                                            + " to " + pkg.packageName + ": old uid "
7988                                            + origPackage.sharedUser.name
7989                                            + " differs from " + pkg.mSharedUserId);
7990                                    origPackage = null;
7991                                    continue;
7992                                }
7993                                // TODO: Add case when shared user id is added [b/28144775]
7994                            } else {
7995                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7996                                        + pkg.packageName + " to old name " + origPackage.name);
7997                            }
7998                            break;
7999                        }
8000                    }
8001                }
8002            }
8003
8004            if (mTransferedPackages.contains(pkg.packageName)) {
8005                Slog.w(TAG, "Package " + pkg.packageName
8006                        + " was transferred to another, but its .apk remains");
8007            }
8008
8009            // See comments in nonMutatedPs declaration
8010            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8011                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8012                if (foundPs != null) {
8013                    nonMutatedPs = new PackageSetting(foundPs);
8014                }
8015            }
8016
8017            // Just create the setting, don't add it yet. For already existing packages
8018            // the PkgSetting exists already and doesn't have to be created.
8019            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8020                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8021                    pkg.applicationInfo.primaryCpuAbi,
8022                    pkg.applicationInfo.secondaryCpuAbi,
8023                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8024                    user, false);
8025            if (pkgSetting == null) {
8026                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8027                        "Creating application package " + pkg.packageName + " failed");
8028            }
8029
8030            if (pkgSetting.origPackage != null) {
8031                // If we are first transitioning from an original package,
8032                // fix up the new package's name now.  We need to do this after
8033                // looking up the package under its new name, so getPackageLP
8034                // can take care of fiddling things correctly.
8035                pkg.setPackageName(origPackage.name);
8036
8037                // File a report about this.
8038                String msg = "New package " + pkgSetting.realName
8039                        + " renamed to replace old package " + pkgSetting.name;
8040                reportSettingsProblem(Log.WARN, msg);
8041
8042                // Make a note of it.
8043                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8044                    mTransferedPackages.add(origPackage.name);
8045                }
8046
8047                // No longer need to retain this.
8048                pkgSetting.origPackage = null;
8049            }
8050
8051            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8052                // Make a note of it.
8053                mTransferedPackages.add(pkg.packageName);
8054            }
8055
8056            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8057                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8058            }
8059
8060            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8061                // Check all shared libraries and map to their actual file path.
8062                // We only do this here for apps not on a system dir, because those
8063                // are the only ones that can fail an install due to this.  We
8064                // will take care of the system apps by updating all of their
8065                // library paths after the scan is done.
8066                updateSharedLibrariesLPw(pkg, null);
8067            }
8068
8069            if (mFoundPolicyFile) {
8070                SELinuxMMAC.assignSeinfoValue(pkg);
8071            }
8072
8073            pkg.applicationInfo.uid = pkgSetting.appId;
8074            pkg.mExtras = pkgSetting;
8075            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8076                if (checkUpgradeKeySetLP(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                } else {
8081                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8082                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8083                                "Package " + pkg.packageName + " upgrade keys do not match the "
8084                                + "previously installed version");
8085                    } else {
8086                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8087                        String msg = "System package " + pkg.packageName
8088                            + " signature changed; retaining data.";
8089                        reportSettingsProblem(Log.WARN, msg);
8090                    }
8091                }
8092            } else {
8093                try {
8094                    verifySignaturesLP(pkgSetting, pkg);
8095                    // We just determined the app is signed correctly, so bring
8096                    // over the latest parsed certs.
8097                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8098                } catch (PackageManagerException e) {
8099                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8100                        throw e;
8101                    }
8102                    // The signature has changed, but this package is in the system
8103                    // image...  let's recover!
8104                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8105                    // However...  if this package is part of a shared user, but it
8106                    // doesn't match the signature of the shared user, let's fail.
8107                    // What this means is that you can't change the signatures
8108                    // associated with an overall shared user, which doesn't seem all
8109                    // that unreasonable.
8110                    if (pkgSetting.sharedUser != null) {
8111                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8112                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8113                            throw new PackageManagerException(
8114                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8115                                            "Signature mismatch for shared user: "
8116                                            + pkgSetting.sharedUser);
8117                        }
8118                    }
8119                    // File a report about this.
8120                    String msg = "System package " + pkg.packageName
8121                        + " signature changed; retaining data.";
8122                    reportSettingsProblem(Log.WARN, msg);
8123                }
8124            }
8125            // Verify that this new package doesn't have any content providers
8126            // that conflict with existing packages.  Only do this if the
8127            // package isn't already installed, since we don't want to break
8128            // things that are installed.
8129            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8130                final int N = pkg.providers.size();
8131                int i;
8132                for (i=0; i<N; i++) {
8133                    PackageParser.Provider p = pkg.providers.get(i);
8134                    if (p.info.authority != null) {
8135                        String names[] = p.info.authority.split(";");
8136                        for (int j = 0; j < names.length; j++) {
8137                            if (mProvidersByAuthority.containsKey(names[j])) {
8138                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8139                                final String otherPackageName =
8140                                        ((other != null && other.getComponentName() != null) ?
8141                                                other.getComponentName().getPackageName() : "?");
8142                                throw new PackageManagerException(
8143                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8144                                                "Can't install because provider name " + names[j]
8145                                                + " (in package " + pkg.applicationInfo.packageName
8146                                                + ") is already used by " + otherPackageName);
8147                            }
8148                        }
8149                    }
8150                }
8151            }
8152
8153            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8154                // This package wants to adopt ownership of permissions from
8155                // another package.
8156                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8157                    final String origName = pkg.mAdoptPermissions.get(i);
8158                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8159                    if (orig != null) {
8160                        if (verifyPackageUpdateLPr(orig, pkg)) {
8161                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8162                                    + pkg.packageName);
8163                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8164                        }
8165                    }
8166                }
8167            }
8168        }
8169
8170        final String pkgName = pkg.packageName;
8171
8172        final long scanFileTime = scanFile.lastModified();
8173        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8174        pkg.applicationInfo.processName = fixProcessName(
8175                pkg.applicationInfo.packageName,
8176                pkg.applicationInfo.processName,
8177                pkg.applicationInfo.uid);
8178
8179        if (pkg != mPlatformPackage) {
8180            // Get all of our default paths setup
8181            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8182        }
8183
8184        final String path = scanFile.getPath();
8185        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8186
8187        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8188            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8189
8190            // Some system apps still use directory structure for native libraries
8191            // in which case we might end up not detecting abi solely based on apk
8192            // structure. Try to detect abi based on directory structure.
8193            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8194                    pkg.applicationInfo.primaryCpuAbi == null) {
8195                setBundledAppAbisAndRoots(pkg, pkgSetting);
8196                setNativeLibraryPaths(pkg);
8197            }
8198
8199        } else {
8200            if ((scanFlags & SCAN_MOVE) != 0) {
8201                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8202                // but we already have this packages package info in the PackageSetting. We just
8203                // use that and derive the native library path based on the new codepath.
8204                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8205                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8206            }
8207
8208            // Set native library paths again. For moves, the path will be updated based on the
8209            // ABIs we've determined above. For non-moves, the path will be updated based on the
8210            // ABIs we determined during compilation, but the path will depend on the final
8211            // package path (after the rename away from the stage path).
8212            setNativeLibraryPaths(pkg);
8213        }
8214
8215        // This is a special case for the "system" package, where the ABI is
8216        // dictated by the zygote configuration (and init.rc). We should keep track
8217        // of this ABI so that we can deal with "normal" applications that run under
8218        // the same UID correctly.
8219        if (mPlatformPackage == pkg) {
8220            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8221                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8222        }
8223
8224        // If there's a mismatch between the abi-override in the package setting
8225        // and the abiOverride specified for the install. Warn about this because we
8226        // would've already compiled the app without taking the package setting into
8227        // account.
8228        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8229            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8230                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8231                        " for package " + pkg.packageName);
8232            }
8233        }
8234
8235        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8236        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8237        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8238
8239        // Copy the derived override back to the parsed package, so that we can
8240        // update the package settings accordingly.
8241        pkg.cpuAbiOverride = cpuAbiOverride;
8242
8243        if (DEBUG_ABI_SELECTION) {
8244            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8245                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8246                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8247        }
8248
8249        // Push the derived path down into PackageSettings so we know what to
8250        // clean up at uninstall time.
8251        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8252
8253        if (DEBUG_ABI_SELECTION) {
8254            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8255                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8256                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8257        }
8258
8259        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8260            // We don't do this here during boot because we can do it all
8261            // at once after scanning all existing packages.
8262            //
8263            // We also do this *before* we perform dexopt on this package, so that
8264            // we can avoid redundant dexopts, and also to make sure we've got the
8265            // code and package path correct.
8266            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8267                    pkg, true /* boot complete */);
8268        }
8269
8270        if (mFactoryTest && pkg.requestedPermissions.contains(
8271                android.Manifest.permission.FACTORY_TEST)) {
8272            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8273        }
8274
8275        ArrayList<PackageParser.Package> clientLibPkgs = null;
8276
8277        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8278            if (nonMutatedPs != null) {
8279                synchronized (mPackages) {
8280                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8281                }
8282            }
8283            return pkg;
8284        }
8285
8286        // Only privileged apps and updated privileged apps can add child packages.
8287        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8288            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8289                throw new PackageManagerException("Only privileged apps and updated "
8290                        + "privileged apps can add child packages. Ignoring package "
8291                        + pkg.packageName);
8292            }
8293            final int childCount = pkg.childPackages.size();
8294            for (int i = 0; i < childCount; i++) {
8295                PackageParser.Package childPkg = pkg.childPackages.get(i);
8296                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8297                        childPkg.packageName)) {
8298                    throw new PackageManagerException("Cannot override a child package of "
8299                            + "another disabled system app. Ignoring package " + pkg.packageName);
8300                }
8301            }
8302        }
8303
8304        // writer
8305        synchronized (mPackages) {
8306            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8307                // Only system apps can add new shared libraries.
8308                if (pkg.libraryNames != null) {
8309                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8310                        String name = pkg.libraryNames.get(i);
8311                        boolean allowed = false;
8312                        if (pkg.isUpdatedSystemApp()) {
8313                            // New library entries can only be added through the
8314                            // system image.  This is important to get rid of a lot
8315                            // of nasty edge cases: for example if we allowed a non-
8316                            // system update of the app to add a library, then uninstalling
8317                            // the update would make the library go away, and assumptions
8318                            // we made such as through app install filtering would now
8319                            // have allowed apps on the device which aren't compatible
8320                            // with it.  Better to just have the restriction here, be
8321                            // conservative, and create many fewer cases that can negatively
8322                            // impact the user experience.
8323                            final PackageSetting sysPs = mSettings
8324                                    .getDisabledSystemPkgLPr(pkg.packageName);
8325                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8326                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8327                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8328                                        allowed = true;
8329                                        break;
8330                                    }
8331                                }
8332                            }
8333                        } else {
8334                            allowed = true;
8335                        }
8336                        if (allowed) {
8337                            if (!mSharedLibraries.containsKey(name)) {
8338                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8339                            } else if (!name.equals(pkg.packageName)) {
8340                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8341                                        + name + " already exists; skipping");
8342                            }
8343                        } else {
8344                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8345                                    + name + " that is not declared on system image; skipping");
8346                        }
8347                    }
8348                    if ((scanFlags & SCAN_BOOTING) == 0) {
8349                        // If we are not booting, we need to update any applications
8350                        // that are clients of our shared library.  If we are booting,
8351                        // this will all be done once the scan is complete.
8352                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8353                    }
8354                }
8355            }
8356        }
8357
8358        if ((scanFlags & SCAN_BOOTING) != 0) {
8359            // No apps can run during boot scan, so they don't need to be frozen
8360        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8361            // Caller asked to not kill app, so it's probably not frozen
8362        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8363            // Caller asked us to ignore frozen check for some reason; they
8364            // probably didn't know the package name
8365        } else {
8366            // We're doing major surgery on this package, so it better be frozen
8367            // right now to keep it from launching
8368            checkPackageFrozen(pkgName);
8369        }
8370
8371        // Also need to kill any apps that are dependent on the library.
8372        if (clientLibPkgs != null) {
8373            for (int i=0; i<clientLibPkgs.size(); i++) {
8374                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8375                killApplication(clientPkg.applicationInfo.packageName,
8376                        clientPkg.applicationInfo.uid, "update lib");
8377            }
8378        }
8379
8380        // Make sure we're not adding any bogus keyset info
8381        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8382        ksms.assertScannedPackageValid(pkg);
8383
8384        // writer
8385        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8386
8387        boolean createIdmapFailed = false;
8388        synchronized (mPackages) {
8389            // We don't expect installation to fail beyond this point
8390
8391            // Add the new setting to mSettings
8392            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8393            // Add the new setting to mPackages
8394            mPackages.put(pkg.applicationInfo.packageName, pkg);
8395            // Make sure we don't accidentally delete its data.
8396            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8397            while (iter.hasNext()) {
8398                PackageCleanItem item = iter.next();
8399                if (pkgName.equals(item.packageName)) {
8400                    iter.remove();
8401                }
8402            }
8403
8404            // Take care of first install / last update times.
8405            if (currentTime != 0) {
8406                if (pkgSetting.firstInstallTime == 0) {
8407                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8408                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8409                    pkgSetting.lastUpdateTime = currentTime;
8410                }
8411            } else if (pkgSetting.firstInstallTime == 0) {
8412                // We need *something*.  Take time time stamp of the file.
8413                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8414            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8415                if (scanFileTime != pkgSetting.timeStamp) {
8416                    // A package on the system image has changed; consider this
8417                    // to be an update.
8418                    pkgSetting.lastUpdateTime = scanFileTime;
8419                }
8420            }
8421
8422            // Add the package's KeySets to the global KeySetManagerService
8423            ksms.addScannedPackageLPw(pkg);
8424
8425            int N = pkg.providers.size();
8426            StringBuilder r = null;
8427            int i;
8428            for (i=0; i<N; i++) {
8429                PackageParser.Provider p = pkg.providers.get(i);
8430                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8431                        p.info.processName, pkg.applicationInfo.uid);
8432                mProviders.addProvider(p);
8433                p.syncable = p.info.isSyncable;
8434                if (p.info.authority != null) {
8435                    String names[] = p.info.authority.split(";");
8436                    p.info.authority = null;
8437                    for (int j = 0; j < names.length; j++) {
8438                        if (j == 1 && p.syncable) {
8439                            // We only want the first authority for a provider to possibly be
8440                            // syncable, so if we already added this provider using a different
8441                            // authority clear the syncable flag. We copy the provider before
8442                            // changing it because the mProviders object contains a reference
8443                            // to a provider that we don't want to change.
8444                            // Only do this for the second authority since the resulting provider
8445                            // object can be the same for all future authorities for this provider.
8446                            p = new PackageParser.Provider(p);
8447                            p.syncable = false;
8448                        }
8449                        if (!mProvidersByAuthority.containsKey(names[j])) {
8450                            mProvidersByAuthority.put(names[j], p);
8451                            if (p.info.authority == null) {
8452                                p.info.authority = names[j];
8453                            } else {
8454                                p.info.authority = p.info.authority + ";" + names[j];
8455                            }
8456                            if (DEBUG_PACKAGE_SCANNING) {
8457                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8458                                    Log.d(TAG, "Registered content provider: " + names[j]
8459                                            + ", className = " + p.info.name + ", isSyncable = "
8460                                            + p.info.isSyncable);
8461                            }
8462                        } else {
8463                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8464                            Slog.w(TAG, "Skipping provider name " + names[j] +
8465                                    " (in package " + pkg.applicationInfo.packageName +
8466                                    "): name already used by "
8467                                    + ((other != null && other.getComponentName() != null)
8468                                            ? other.getComponentName().getPackageName() : "?"));
8469                        }
8470                    }
8471                }
8472                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8473                    if (r == null) {
8474                        r = new StringBuilder(256);
8475                    } else {
8476                        r.append(' ');
8477                    }
8478                    r.append(p.info.name);
8479                }
8480            }
8481            if (r != null) {
8482                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8483            }
8484
8485            N = pkg.services.size();
8486            r = null;
8487            for (i=0; i<N; i++) {
8488                PackageParser.Service s = pkg.services.get(i);
8489                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8490                        s.info.processName, pkg.applicationInfo.uid);
8491                mServices.addService(s);
8492                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8493                    if (r == null) {
8494                        r = new StringBuilder(256);
8495                    } else {
8496                        r.append(' ');
8497                    }
8498                    r.append(s.info.name);
8499                }
8500            }
8501            if (r != null) {
8502                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8503            }
8504
8505            N = pkg.receivers.size();
8506            r = null;
8507            for (i=0; i<N; i++) {
8508                PackageParser.Activity a = pkg.receivers.get(i);
8509                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8510                        a.info.processName, pkg.applicationInfo.uid);
8511                mReceivers.addActivity(a, "receiver");
8512                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8513                    if (r == null) {
8514                        r = new StringBuilder(256);
8515                    } else {
8516                        r.append(' ');
8517                    }
8518                    r.append(a.info.name);
8519                }
8520            }
8521            if (r != null) {
8522                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8523            }
8524
8525            N = pkg.activities.size();
8526            r = null;
8527            for (i=0; i<N; i++) {
8528                PackageParser.Activity a = pkg.activities.get(i);
8529                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8530                        a.info.processName, pkg.applicationInfo.uid);
8531                mActivities.addActivity(a, "activity");
8532                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8533                    if (r == null) {
8534                        r = new StringBuilder(256);
8535                    } else {
8536                        r.append(' ');
8537                    }
8538                    r.append(a.info.name);
8539                }
8540            }
8541            if (r != null) {
8542                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8543            }
8544
8545            N = pkg.permissionGroups.size();
8546            r = null;
8547            for (i=0; i<N; i++) {
8548                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8549                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8550                if (cur == null) {
8551                    mPermissionGroups.put(pg.info.name, pg);
8552                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8553                        if (r == null) {
8554                            r = new StringBuilder(256);
8555                        } else {
8556                            r.append(' ');
8557                        }
8558                        r.append(pg.info.name);
8559                    }
8560                } else {
8561                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8562                            + pg.info.packageName + " ignored: original from "
8563                            + cur.info.packageName);
8564                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8565                        if (r == null) {
8566                            r = new StringBuilder(256);
8567                        } else {
8568                            r.append(' ');
8569                        }
8570                        r.append("DUP:");
8571                        r.append(pg.info.name);
8572                    }
8573                }
8574            }
8575            if (r != null) {
8576                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8577            }
8578
8579            N = pkg.permissions.size();
8580            r = null;
8581            for (i=0; i<N; i++) {
8582                PackageParser.Permission p = pkg.permissions.get(i);
8583
8584                // Assume by default that we did not install this permission into the system.
8585                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8586
8587                // Now that permission groups have a special meaning, we ignore permission
8588                // groups for legacy apps to prevent unexpected behavior. In particular,
8589                // permissions for one app being granted to someone just becase they happen
8590                // to be in a group defined by another app (before this had no implications).
8591                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8592                    p.group = mPermissionGroups.get(p.info.group);
8593                    // Warn for a permission in an unknown group.
8594                    if (p.info.group != null && p.group == null) {
8595                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8596                                + p.info.packageName + " in an unknown group " + p.info.group);
8597                    }
8598                }
8599
8600                ArrayMap<String, BasePermission> permissionMap =
8601                        p.tree ? mSettings.mPermissionTrees
8602                                : mSettings.mPermissions;
8603                BasePermission bp = permissionMap.get(p.info.name);
8604
8605                // Allow system apps to redefine non-system permissions
8606                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8607                    final boolean currentOwnerIsSystem = (bp.perm != null
8608                            && isSystemApp(bp.perm.owner));
8609                    if (isSystemApp(p.owner)) {
8610                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8611                            // It's a built-in permission and no owner, take ownership now
8612                            bp.packageSetting = pkgSetting;
8613                            bp.perm = p;
8614                            bp.uid = pkg.applicationInfo.uid;
8615                            bp.sourcePackage = p.info.packageName;
8616                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8617                        } else if (!currentOwnerIsSystem) {
8618                            String msg = "New decl " + p.owner + " of permission  "
8619                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8620                            reportSettingsProblem(Log.WARN, msg);
8621                            bp = null;
8622                        }
8623                    }
8624                }
8625
8626                if (bp == null) {
8627                    bp = new BasePermission(p.info.name, p.info.packageName,
8628                            BasePermission.TYPE_NORMAL);
8629                    permissionMap.put(p.info.name, bp);
8630                }
8631
8632                if (bp.perm == null) {
8633                    if (bp.sourcePackage == null
8634                            || bp.sourcePackage.equals(p.info.packageName)) {
8635                        BasePermission tree = findPermissionTreeLP(p.info.name);
8636                        if (tree == null
8637                                || tree.sourcePackage.equals(p.info.packageName)) {
8638                            bp.packageSetting = pkgSetting;
8639                            bp.perm = p;
8640                            bp.uid = pkg.applicationInfo.uid;
8641                            bp.sourcePackage = p.info.packageName;
8642                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8643                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8644                                if (r == null) {
8645                                    r = new StringBuilder(256);
8646                                } else {
8647                                    r.append(' ');
8648                                }
8649                                r.append(p.info.name);
8650                            }
8651                        } else {
8652                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8653                                    + p.info.packageName + " ignored: base tree "
8654                                    + tree.name + " is from package "
8655                                    + tree.sourcePackage);
8656                        }
8657                    } else {
8658                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8659                                + p.info.packageName + " ignored: original from "
8660                                + bp.sourcePackage);
8661                    }
8662                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8663                    if (r == null) {
8664                        r = new StringBuilder(256);
8665                    } else {
8666                        r.append(' ');
8667                    }
8668                    r.append("DUP:");
8669                    r.append(p.info.name);
8670                }
8671                if (bp.perm == p) {
8672                    bp.protectionLevel = p.info.protectionLevel;
8673                }
8674            }
8675
8676            if (r != null) {
8677                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8678            }
8679
8680            N = pkg.instrumentation.size();
8681            r = null;
8682            for (i=0; i<N; i++) {
8683                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8684                a.info.packageName = pkg.applicationInfo.packageName;
8685                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8686                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8687                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8688                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8689                a.info.dataDir = pkg.applicationInfo.dataDir;
8690                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8691                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8692
8693                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8694                // need other information about the application, like the ABI and what not ?
8695                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8696                mInstrumentation.put(a.getComponentName(), a);
8697                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8698                    if (r == null) {
8699                        r = new StringBuilder(256);
8700                    } else {
8701                        r.append(' ');
8702                    }
8703                    r.append(a.info.name);
8704                }
8705            }
8706            if (r != null) {
8707                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8708            }
8709
8710            if (pkg.protectedBroadcasts != null) {
8711                N = pkg.protectedBroadcasts.size();
8712                for (i=0; i<N; i++) {
8713                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8714                }
8715            }
8716
8717            pkgSetting.setTimeStamp(scanFileTime);
8718
8719            // Create idmap files for pairs of (packages, overlay packages).
8720            // Note: "android", ie framework-res.apk, is handled by native layers.
8721            if (pkg.mOverlayTarget != null) {
8722                // This is an overlay package.
8723                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8724                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8725                        mOverlays.put(pkg.mOverlayTarget,
8726                                new ArrayMap<String, PackageParser.Package>());
8727                    }
8728                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8729                    map.put(pkg.packageName, pkg);
8730                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8731                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8732                        createIdmapFailed = true;
8733                    }
8734                }
8735            } else if (mOverlays.containsKey(pkg.packageName) &&
8736                    !pkg.packageName.equals("android")) {
8737                // This is a regular package, with one or more known overlay packages.
8738                createIdmapsForPackageLI(pkg);
8739            }
8740        }
8741
8742        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8743
8744        if (createIdmapFailed) {
8745            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8746                    "scanPackageLI failed to createIdmap");
8747        }
8748        return pkg;
8749    }
8750
8751    /**
8752     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8753     * is derived purely on the basis of the contents of {@code scanFile} and
8754     * {@code cpuAbiOverride}.
8755     *
8756     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8757     */
8758    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8759                                 String cpuAbiOverride, boolean extractLibs)
8760            throws PackageManagerException {
8761        // TODO: We can probably be smarter about this stuff. For installed apps,
8762        // we can calculate this information at install time once and for all. For
8763        // system apps, we can probably assume that this information doesn't change
8764        // after the first boot scan. As things stand, we do lots of unnecessary work.
8765
8766        // Give ourselves some initial paths; we'll come back for another
8767        // pass once we've determined ABI below.
8768        setNativeLibraryPaths(pkg);
8769
8770        // We would never need to extract libs for forward-locked and external packages,
8771        // since the container service will do it for us. We shouldn't attempt to
8772        // extract libs from system app when it was not updated.
8773        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8774                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8775            extractLibs = false;
8776        }
8777
8778        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8779        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8780
8781        NativeLibraryHelper.Handle handle = null;
8782        try {
8783            handle = NativeLibraryHelper.Handle.create(pkg);
8784            // TODO(multiArch): This can be null for apps that didn't go through the
8785            // usual installation process. We can calculate it again, like we
8786            // do during install time.
8787            //
8788            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8789            // unnecessary.
8790            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8791
8792            // Null out the abis so that they can be recalculated.
8793            pkg.applicationInfo.primaryCpuAbi = null;
8794            pkg.applicationInfo.secondaryCpuAbi = null;
8795            if (isMultiArch(pkg.applicationInfo)) {
8796                // Warn if we've set an abiOverride for multi-lib packages..
8797                // By definition, we need to copy both 32 and 64 bit libraries for
8798                // such packages.
8799                if (pkg.cpuAbiOverride != null
8800                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8801                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8802                }
8803
8804                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8805                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8806                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8807                    if (extractLibs) {
8808                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8809                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8810                                useIsaSpecificSubdirs);
8811                    } else {
8812                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8813                    }
8814                }
8815
8816                maybeThrowExceptionForMultiArchCopy(
8817                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8818
8819                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8820                    if (extractLibs) {
8821                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8822                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8823                                useIsaSpecificSubdirs);
8824                    } else {
8825                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8826                    }
8827                }
8828
8829                maybeThrowExceptionForMultiArchCopy(
8830                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8831
8832                if (abi64 >= 0) {
8833                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8834                }
8835
8836                if (abi32 >= 0) {
8837                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8838                    if (abi64 >= 0) {
8839                        if (pkg.use32bitAbi) {
8840                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8841                            pkg.applicationInfo.primaryCpuAbi = abi;
8842                        } else {
8843                            pkg.applicationInfo.secondaryCpuAbi = abi;
8844                        }
8845                    } else {
8846                        pkg.applicationInfo.primaryCpuAbi = abi;
8847                    }
8848                }
8849
8850            } else {
8851                String[] abiList = (cpuAbiOverride != null) ?
8852                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8853
8854                // Enable gross and lame hacks for apps that are built with old
8855                // SDK tools. We must scan their APKs for renderscript bitcode and
8856                // not launch them if it's present. Don't bother checking on devices
8857                // that don't have 64 bit support.
8858                boolean needsRenderScriptOverride = false;
8859                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8860                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8861                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8862                    needsRenderScriptOverride = true;
8863                }
8864
8865                final int copyRet;
8866                if (extractLibs) {
8867                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8868                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8869                } else {
8870                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8871                }
8872
8873                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8874                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8875                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8876                }
8877
8878                if (copyRet >= 0) {
8879                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8880                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8881                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8882                } else if (needsRenderScriptOverride) {
8883                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8884                }
8885            }
8886        } catch (IOException ioe) {
8887            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8888        } finally {
8889            IoUtils.closeQuietly(handle);
8890        }
8891
8892        // Now that we've calculated the ABIs and determined if it's an internal app,
8893        // we will go ahead and populate the nativeLibraryPath.
8894        setNativeLibraryPaths(pkg);
8895    }
8896
8897    /**
8898     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8899     * i.e, so that all packages can be run inside a single process if required.
8900     *
8901     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8902     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8903     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8904     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8905     * updating a package that belongs to a shared user.
8906     *
8907     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8908     * adds unnecessary complexity.
8909     */
8910    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8911            PackageParser.Package scannedPackage, boolean bootComplete) {
8912        String requiredInstructionSet = null;
8913        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8914            requiredInstructionSet = VMRuntime.getInstructionSet(
8915                     scannedPackage.applicationInfo.primaryCpuAbi);
8916        }
8917
8918        PackageSetting requirer = null;
8919        for (PackageSetting ps : packagesForUser) {
8920            // If packagesForUser contains scannedPackage, we skip it. This will happen
8921            // when scannedPackage is an update of an existing package. Without this check,
8922            // we will never be able to change the ABI of any package belonging to a shared
8923            // user, even if it's compatible with other packages.
8924            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8925                if (ps.primaryCpuAbiString == null) {
8926                    continue;
8927                }
8928
8929                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8930                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8931                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8932                    // this but there's not much we can do.
8933                    String errorMessage = "Instruction set mismatch, "
8934                            + ((requirer == null) ? "[caller]" : requirer)
8935                            + " requires " + requiredInstructionSet + " whereas " + ps
8936                            + " requires " + instructionSet;
8937                    Slog.w(TAG, errorMessage);
8938                }
8939
8940                if (requiredInstructionSet == null) {
8941                    requiredInstructionSet = instructionSet;
8942                    requirer = ps;
8943                }
8944            }
8945        }
8946
8947        if (requiredInstructionSet != null) {
8948            String adjustedAbi;
8949            if (requirer != null) {
8950                // requirer != null implies that either scannedPackage was null or that scannedPackage
8951                // did not require an ABI, in which case we have to adjust scannedPackage to match
8952                // the ABI of the set (which is the same as requirer's ABI)
8953                adjustedAbi = requirer.primaryCpuAbiString;
8954                if (scannedPackage != null) {
8955                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8956                }
8957            } else {
8958                // requirer == null implies that we're updating all ABIs in the set to
8959                // match scannedPackage.
8960                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8961            }
8962
8963            for (PackageSetting ps : packagesForUser) {
8964                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8965                    if (ps.primaryCpuAbiString != null) {
8966                        continue;
8967                    }
8968
8969                    ps.primaryCpuAbiString = adjustedAbi;
8970                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8971                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8972                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8973                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8974                                + " (requirer="
8975                                + (requirer == null ? "null" : requirer.pkg.packageName)
8976                                + ", scannedPackage="
8977                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8978                                + ")");
8979                        try {
8980                            mInstaller.rmdex(ps.codePathString,
8981                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8982                        } catch (InstallerException ignored) {
8983                        }
8984                    }
8985                }
8986            }
8987        }
8988    }
8989
8990    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8991        synchronized (mPackages) {
8992            mResolverReplaced = true;
8993            // Set up information for custom user intent resolution activity.
8994            mResolveActivity.applicationInfo = pkg.applicationInfo;
8995            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8996            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8997            mResolveActivity.processName = pkg.applicationInfo.packageName;
8998            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8999            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9000                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9001            mResolveActivity.theme = 0;
9002            mResolveActivity.exported = true;
9003            mResolveActivity.enabled = true;
9004            mResolveInfo.activityInfo = mResolveActivity;
9005            mResolveInfo.priority = 0;
9006            mResolveInfo.preferredOrder = 0;
9007            mResolveInfo.match = 0;
9008            mResolveComponentName = mCustomResolverComponentName;
9009            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9010                    mResolveComponentName);
9011        }
9012    }
9013
9014    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9015        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9016
9017        // Set up information for ephemeral installer activity
9018        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9019        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9020        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9021        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9022        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9023        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9024                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9025        mEphemeralInstallerActivity.theme = 0;
9026        mEphemeralInstallerActivity.exported = true;
9027        mEphemeralInstallerActivity.enabled = true;
9028        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9029        mEphemeralInstallerInfo.priority = 0;
9030        mEphemeralInstallerInfo.preferredOrder = 0;
9031        mEphemeralInstallerInfo.match = 0;
9032
9033        if (DEBUG_EPHEMERAL) {
9034            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9035        }
9036    }
9037
9038    private static String calculateBundledApkRoot(final String codePathString) {
9039        final File codePath = new File(codePathString);
9040        final File codeRoot;
9041        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9042            codeRoot = Environment.getRootDirectory();
9043        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9044            codeRoot = Environment.getOemDirectory();
9045        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9046            codeRoot = Environment.getVendorDirectory();
9047        } else {
9048            // Unrecognized code path; take its top real segment as the apk root:
9049            // e.g. /something/app/blah.apk => /something
9050            try {
9051                File f = codePath.getCanonicalFile();
9052                File parent = f.getParentFile();    // non-null because codePath is a file
9053                File tmp;
9054                while ((tmp = parent.getParentFile()) != null) {
9055                    f = parent;
9056                    parent = tmp;
9057                }
9058                codeRoot = f;
9059                Slog.w(TAG, "Unrecognized code path "
9060                        + codePath + " - using " + codeRoot);
9061            } catch (IOException e) {
9062                // Can't canonicalize the code path -- shenanigans?
9063                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9064                return Environment.getRootDirectory().getPath();
9065            }
9066        }
9067        return codeRoot.getPath();
9068    }
9069
9070    /**
9071     * Derive and set the location of native libraries for the given package,
9072     * which varies depending on where and how the package was installed.
9073     */
9074    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9075        final ApplicationInfo info = pkg.applicationInfo;
9076        final String codePath = pkg.codePath;
9077        final File codeFile = new File(codePath);
9078        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9079        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9080
9081        info.nativeLibraryRootDir = null;
9082        info.nativeLibraryRootRequiresIsa = false;
9083        info.nativeLibraryDir = null;
9084        info.secondaryNativeLibraryDir = null;
9085
9086        if (isApkFile(codeFile)) {
9087            // Monolithic install
9088            if (bundledApp) {
9089                // If "/system/lib64/apkname" exists, assume that is the per-package
9090                // native library directory to use; otherwise use "/system/lib/apkname".
9091                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9092                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9093                        getPrimaryInstructionSet(info));
9094
9095                // This is a bundled system app so choose the path based on the ABI.
9096                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9097                // is just the default path.
9098                final String apkName = deriveCodePathName(codePath);
9099                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9100                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9101                        apkName).getAbsolutePath();
9102
9103                if (info.secondaryCpuAbi != null) {
9104                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9105                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9106                            secondaryLibDir, apkName).getAbsolutePath();
9107                }
9108            } else if (asecApp) {
9109                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9110                        .getAbsolutePath();
9111            } else {
9112                final String apkName = deriveCodePathName(codePath);
9113                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9114                        .getAbsolutePath();
9115            }
9116
9117            info.nativeLibraryRootRequiresIsa = false;
9118            info.nativeLibraryDir = info.nativeLibraryRootDir;
9119        } else {
9120            // Cluster install
9121            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9122            info.nativeLibraryRootRequiresIsa = true;
9123
9124            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9125                    getPrimaryInstructionSet(info)).getAbsolutePath();
9126
9127            if (info.secondaryCpuAbi != null) {
9128                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9129                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9130            }
9131        }
9132    }
9133
9134    /**
9135     * Calculate the abis and roots for a bundled app. These can uniquely
9136     * be determined from the contents of the system partition, i.e whether
9137     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9138     * of this information, and instead assume that the system was built
9139     * sensibly.
9140     */
9141    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9142                                           PackageSetting pkgSetting) {
9143        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9144
9145        // If "/system/lib64/apkname" exists, assume that is the per-package
9146        // native library directory to use; otherwise use "/system/lib/apkname".
9147        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9148        setBundledAppAbi(pkg, apkRoot, apkName);
9149        // pkgSetting might be null during rescan following uninstall of updates
9150        // to a bundled app, so accommodate that possibility.  The settings in
9151        // that case will be established later from the parsed package.
9152        //
9153        // If the settings aren't null, sync them up with what we've just derived.
9154        // note that apkRoot isn't stored in the package settings.
9155        if (pkgSetting != null) {
9156            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9157            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9158        }
9159    }
9160
9161    /**
9162     * Deduces the ABI of a bundled app and sets the relevant fields on the
9163     * parsed pkg object.
9164     *
9165     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9166     *        under which system libraries are installed.
9167     * @param apkName the name of the installed package.
9168     */
9169    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9170        final File codeFile = new File(pkg.codePath);
9171
9172        final boolean has64BitLibs;
9173        final boolean has32BitLibs;
9174        if (isApkFile(codeFile)) {
9175            // Monolithic install
9176            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9177            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9178        } else {
9179            // Cluster install
9180            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9181            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9182                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9183                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9184                has64BitLibs = (new File(rootDir, isa)).exists();
9185            } else {
9186                has64BitLibs = false;
9187            }
9188            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9189                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9190                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9191                has32BitLibs = (new File(rootDir, isa)).exists();
9192            } else {
9193                has32BitLibs = false;
9194            }
9195        }
9196
9197        if (has64BitLibs && !has32BitLibs) {
9198            // The package has 64 bit libs, but not 32 bit libs. Its primary
9199            // ABI should be 64 bit. We can safely assume here that the bundled
9200            // native libraries correspond to the most preferred ABI in the list.
9201
9202            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9203            pkg.applicationInfo.secondaryCpuAbi = null;
9204        } else if (has32BitLibs && !has64BitLibs) {
9205            // The package has 32 bit libs but not 64 bit libs. Its primary
9206            // ABI should be 32 bit.
9207
9208            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9209            pkg.applicationInfo.secondaryCpuAbi = null;
9210        } else if (has32BitLibs && has64BitLibs) {
9211            // The application has both 64 and 32 bit bundled libraries. We check
9212            // here that the app declares multiArch support, and warn if it doesn't.
9213            //
9214            // We will be lenient here and record both ABIs. The primary will be the
9215            // ABI that's higher on the list, i.e, a device that's configured to prefer
9216            // 64 bit apps will see a 64 bit primary ABI,
9217
9218            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9219                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9220            }
9221
9222            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9223                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9224                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9225            } else {
9226                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9227                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9228            }
9229        } else {
9230            pkg.applicationInfo.primaryCpuAbi = null;
9231            pkg.applicationInfo.secondaryCpuAbi = null;
9232        }
9233    }
9234
9235    private void killApplication(String pkgName, int appId, String reason) {
9236        // Request the ActivityManager to kill the process(only for existing packages)
9237        // so that we do not end up in a confused state while the user is still using the older
9238        // version of the application while the new one gets installed.
9239        final long token = Binder.clearCallingIdentity();
9240        try {
9241            IActivityManager am = ActivityManagerNative.getDefault();
9242            if (am != null) {
9243                try {
9244                    am.killApplicationWithAppId(pkgName, appId, reason);
9245                } catch (RemoteException e) {
9246                }
9247            }
9248        } finally {
9249            Binder.restoreCallingIdentity(token);
9250        }
9251    }
9252
9253    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9254        // Remove the parent package setting
9255        PackageSetting ps = (PackageSetting) pkg.mExtras;
9256        if (ps != null) {
9257            removePackageLI(ps, chatty);
9258        }
9259        // Remove the child package setting
9260        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9261        for (int i = 0; i < childCount; i++) {
9262            PackageParser.Package childPkg = pkg.childPackages.get(i);
9263            ps = (PackageSetting) childPkg.mExtras;
9264            if (ps != null) {
9265                removePackageLI(ps, chatty);
9266            }
9267        }
9268    }
9269
9270    void removePackageLI(PackageSetting ps, boolean chatty) {
9271        if (DEBUG_INSTALL) {
9272            if (chatty)
9273                Log.d(TAG, "Removing package " + ps.name);
9274        }
9275
9276        // writer
9277        synchronized (mPackages) {
9278            mPackages.remove(ps.name);
9279            final PackageParser.Package pkg = ps.pkg;
9280            if (pkg != null) {
9281                cleanPackageDataStructuresLILPw(pkg, chatty);
9282            }
9283        }
9284    }
9285
9286    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9287        if (DEBUG_INSTALL) {
9288            if (chatty)
9289                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9290        }
9291
9292        // writer
9293        synchronized (mPackages) {
9294            // Remove the parent package
9295            mPackages.remove(pkg.applicationInfo.packageName);
9296            cleanPackageDataStructuresLILPw(pkg, chatty);
9297
9298            // Remove the child packages
9299            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9300            for (int i = 0; i < childCount; i++) {
9301                PackageParser.Package childPkg = pkg.childPackages.get(i);
9302                mPackages.remove(childPkg.applicationInfo.packageName);
9303                cleanPackageDataStructuresLILPw(childPkg, chatty);
9304            }
9305        }
9306    }
9307
9308    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9309        int N = pkg.providers.size();
9310        StringBuilder r = null;
9311        int i;
9312        for (i=0; i<N; i++) {
9313            PackageParser.Provider p = pkg.providers.get(i);
9314            mProviders.removeProvider(p);
9315            if (p.info.authority == null) {
9316
9317                /* There was another ContentProvider with this authority when
9318                 * this app was installed so this authority is null,
9319                 * Ignore it as we don't have to unregister the provider.
9320                 */
9321                continue;
9322            }
9323            String names[] = p.info.authority.split(";");
9324            for (int j = 0; j < names.length; j++) {
9325                if (mProvidersByAuthority.get(names[j]) == p) {
9326                    mProvidersByAuthority.remove(names[j]);
9327                    if (DEBUG_REMOVE) {
9328                        if (chatty)
9329                            Log.d(TAG, "Unregistered content provider: " + names[j]
9330                                    + ", className = " + p.info.name + ", isSyncable = "
9331                                    + p.info.isSyncable);
9332                    }
9333                }
9334            }
9335            if (DEBUG_REMOVE && chatty) {
9336                if (r == null) {
9337                    r = new StringBuilder(256);
9338                } else {
9339                    r.append(' ');
9340                }
9341                r.append(p.info.name);
9342            }
9343        }
9344        if (r != null) {
9345            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9346        }
9347
9348        N = pkg.services.size();
9349        r = null;
9350        for (i=0; i<N; i++) {
9351            PackageParser.Service s = pkg.services.get(i);
9352            mServices.removeService(s);
9353            if (chatty) {
9354                if (r == null) {
9355                    r = new StringBuilder(256);
9356                } else {
9357                    r.append(' ');
9358                }
9359                r.append(s.info.name);
9360            }
9361        }
9362        if (r != null) {
9363            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9364        }
9365
9366        N = pkg.receivers.size();
9367        r = null;
9368        for (i=0; i<N; i++) {
9369            PackageParser.Activity a = pkg.receivers.get(i);
9370            mReceivers.removeActivity(a, "receiver");
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, "  Receivers: " + r);
9382        }
9383
9384        N = pkg.activities.size();
9385        r = null;
9386        for (i=0; i<N; i++) {
9387            PackageParser.Activity a = pkg.activities.get(i);
9388            mActivities.removeActivity(a, "activity");
9389            if (DEBUG_REMOVE && chatty) {
9390                if (r == null) {
9391                    r = new StringBuilder(256);
9392                } else {
9393                    r.append(' ');
9394                }
9395                r.append(a.info.name);
9396            }
9397        }
9398        if (r != null) {
9399            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9400        }
9401
9402        N = pkg.permissions.size();
9403        r = null;
9404        for (i=0; i<N; i++) {
9405            PackageParser.Permission p = pkg.permissions.get(i);
9406            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9407            if (bp == null) {
9408                bp = mSettings.mPermissionTrees.get(p.info.name);
9409            }
9410            if (bp != null && bp.perm == p) {
9411                bp.perm = null;
9412                if (DEBUG_REMOVE && chatty) {
9413                    if (r == null) {
9414                        r = new StringBuilder(256);
9415                    } else {
9416                        r.append(' ');
9417                    }
9418                    r.append(p.info.name);
9419                }
9420            }
9421            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9422                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9423                if (appOpPkgs != null) {
9424                    appOpPkgs.remove(pkg.packageName);
9425                }
9426            }
9427        }
9428        if (r != null) {
9429            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9430        }
9431
9432        N = pkg.requestedPermissions.size();
9433        r = null;
9434        for (i=0; i<N; i++) {
9435            String perm = pkg.requestedPermissions.get(i);
9436            BasePermission bp = mSettings.mPermissions.get(perm);
9437            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9438                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9439                if (appOpPkgs != null) {
9440                    appOpPkgs.remove(pkg.packageName);
9441                    if (appOpPkgs.isEmpty()) {
9442                        mAppOpPermissionPackages.remove(perm);
9443                    }
9444                }
9445            }
9446        }
9447        if (r != null) {
9448            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9449        }
9450
9451        N = pkg.instrumentation.size();
9452        r = null;
9453        for (i=0; i<N; i++) {
9454            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9455            mInstrumentation.remove(a.getComponentName());
9456            if (DEBUG_REMOVE && chatty) {
9457                if (r == null) {
9458                    r = new StringBuilder(256);
9459                } else {
9460                    r.append(' ');
9461                }
9462                r.append(a.info.name);
9463            }
9464        }
9465        if (r != null) {
9466            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9467        }
9468
9469        r = null;
9470        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9471            // Only system apps can hold shared libraries.
9472            if (pkg.libraryNames != null) {
9473                for (i=0; i<pkg.libraryNames.size(); i++) {
9474                    String name = pkg.libraryNames.get(i);
9475                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9476                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9477                        mSharedLibraries.remove(name);
9478                        if (DEBUG_REMOVE && chatty) {
9479                            if (r == null) {
9480                                r = new StringBuilder(256);
9481                            } else {
9482                                r.append(' ');
9483                            }
9484                            r.append(name);
9485                        }
9486                    }
9487                }
9488            }
9489        }
9490        if (r != null) {
9491            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9492        }
9493    }
9494
9495    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9496        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9497            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9498                return true;
9499            }
9500        }
9501        return false;
9502    }
9503
9504    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9505    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9506    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9507
9508    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9509        // Update the parent permissions
9510        updatePermissionsLPw(pkg.packageName, pkg, flags);
9511        // Update the child permissions
9512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9513        for (int i = 0; i < childCount; i++) {
9514            PackageParser.Package childPkg = pkg.childPackages.get(i);
9515            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9516        }
9517    }
9518
9519    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9520            int flags) {
9521        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9522        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9523    }
9524
9525    private void updatePermissionsLPw(String changingPkg,
9526            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9527        // Make sure there are no dangling permission trees.
9528        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9529        while (it.hasNext()) {
9530            final BasePermission bp = it.next();
9531            if (bp.packageSetting == null) {
9532                // We may not yet have parsed the package, so just see if
9533                // we still know about its settings.
9534                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9535            }
9536            if (bp.packageSetting == null) {
9537                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9538                        + " from package " + bp.sourcePackage);
9539                it.remove();
9540            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9541                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9542                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9543                            + " from package " + bp.sourcePackage);
9544                    flags |= UPDATE_PERMISSIONS_ALL;
9545                    it.remove();
9546                }
9547            }
9548        }
9549
9550        // Make sure all dynamic permissions have been assigned to a package,
9551        // and make sure there are no dangling permissions.
9552        it = mSettings.mPermissions.values().iterator();
9553        while (it.hasNext()) {
9554            final BasePermission bp = it.next();
9555            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9556                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9557                        + bp.name + " pkg=" + bp.sourcePackage
9558                        + " info=" + bp.pendingInfo);
9559                if (bp.packageSetting == null && bp.pendingInfo != null) {
9560                    final BasePermission tree = findPermissionTreeLP(bp.name);
9561                    if (tree != null && tree.perm != null) {
9562                        bp.packageSetting = tree.packageSetting;
9563                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9564                                new PermissionInfo(bp.pendingInfo));
9565                        bp.perm.info.packageName = tree.perm.info.packageName;
9566                        bp.perm.info.name = bp.name;
9567                        bp.uid = tree.uid;
9568                    }
9569                }
9570            }
9571            if (bp.packageSetting == null) {
9572                // We may not yet have parsed the package, so just see if
9573                // we still know about its settings.
9574                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9575            }
9576            if (bp.packageSetting == null) {
9577                Slog.w(TAG, "Removing dangling permission: " + bp.name
9578                        + " from package " + bp.sourcePackage);
9579                it.remove();
9580            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9581                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9582                    Slog.i(TAG, "Removing old permission: " + bp.name
9583                            + " from package " + bp.sourcePackage);
9584                    flags |= UPDATE_PERMISSIONS_ALL;
9585                    it.remove();
9586                }
9587            }
9588        }
9589
9590        // Now update the permissions for all packages, in particular
9591        // replace the granted permissions of the system packages.
9592        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9593            for (PackageParser.Package pkg : mPackages.values()) {
9594                if (pkg != pkgInfo) {
9595                    // Only replace for packages on requested volume
9596                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9597                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9598                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9599                    grantPermissionsLPw(pkg, replace, changingPkg);
9600                }
9601            }
9602        }
9603
9604        if (pkgInfo != null) {
9605            // Only replace for packages on requested volume
9606            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9607            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9608                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9609            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9610        }
9611    }
9612
9613    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9614            String packageOfInterest) {
9615        // IMPORTANT: There are two types of permissions: install and runtime.
9616        // Install time permissions are granted when the app is installed to
9617        // all device users and users added in the future. Runtime permissions
9618        // are granted at runtime explicitly to specific users. Normal and signature
9619        // protected permissions are install time permissions. Dangerous permissions
9620        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9621        // otherwise they are runtime permissions. This function does not manage
9622        // runtime permissions except for the case an app targeting Lollipop MR1
9623        // being upgraded to target a newer SDK, in which case dangerous permissions
9624        // are transformed from install time to runtime ones.
9625
9626        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9627        if (ps == null) {
9628            return;
9629        }
9630
9631        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9632
9633        PermissionsState permissionsState = ps.getPermissionsState();
9634        PermissionsState origPermissions = permissionsState;
9635
9636        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9637
9638        boolean runtimePermissionsRevoked = false;
9639        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9640
9641        boolean changedInstallPermission = false;
9642
9643        if (replace) {
9644            ps.installPermissionsFixed = false;
9645            if (!ps.isSharedUser()) {
9646                origPermissions = new PermissionsState(permissionsState);
9647                permissionsState.reset();
9648            } else {
9649                // We need to know only about runtime permission changes since the
9650                // calling code always writes the install permissions state but
9651                // the runtime ones are written only if changed. The only cases of
9652                // changed runtime permissions here are promotion of an install to
9653                // runtime and revocation of a runtime from a shared user.
9654                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9655                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9656                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9657                    runtimePermissionsRevoked = true;
9658                }
9659            }
9660        }
9661
9662        permissionsState.setGlobalGids(mGlobalGids);
9663
9664        final int N = pkg.requestedPermissions.size();
9665        for (int i=0; i<N; i++) {
9666            final String name = pkg.requestedPermissions.get(i);
9667            final BasePermission bp = mSettings.mPermissions.get(name);
9668
9669            if (DEBUG_INSTALL) {
9670                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9671            }
9672
9673            if (bp == null || bp.packageSetting == null) {
9674                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9675                    Slog.w(TAG, "Unknown permission " + name
9676                            + " in package " + pkg.packageName);
9677                }
9678                continue;
9679            }
9680
9681            final String perm = bp.name;
9682            boolean allowedSig = false;
9683            int grant = GRANT_DENIED;
9684
9685            // Keep track of app op permissions.
9686            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9687                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9688                if (pkgs == null) {
9689                    pkgs = new ArraySet<>();
9690                    mAppOpPermissionPackages.put(bp.name, pkgs);
9691                }
9692                pkgs.add(pkg.packageName);
9693            }
9694
9695            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9696            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9697                    >= Build.VERSION_CODES.M;
9698            switch (level) {
9699                case PermissionInfo.PROTECTION_NORMAL: {
9700                    // For all apps normal permissions are install time ones.
9701                    grant = GRANT_INSTALL;
9702                } break;
9703
9704                case PermissionInfo.PROTECTION_DANGEROUS: {
9705                    // If a permission review is required for legacy apps we represent
9706                    // their permissions as always granted runtime ones since we need
9707                    // to keep the review required permission flag per user while an
9708                    // install permission's state is shared across all users.
9709                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9710                        // For legacy apps dangerous permissions are install time ones.
9711                        grant = GRANT_INSTALL;
9712                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9713                        // For legacy apps that became modern, install becomes runtime.
9714                        grant = GRANT_UPGRADE;
9715                    } else if (mPromoteSystemApps
9716                            && isSystemApp(ps)
9717                            && mExistingSystemPackages.contains(ps.name)) {
9718                        // For legacy system apps, install becomes runtime.
9719                        // We cannot check hasInstallPermission() for system apps since those
9720                        // permissions were granted implicitly and not persisted pre-M.
9721                        grant = GRANT_UPGRADE;
9722                    } else {
9723                        // For modern apps keep runtime permissions unchanged.
9724                        grant = GRANT_RUNTIME;
9725                    }
9726                } break;
9727
9728                case PermissionInfo.PROTECTION_SIGNATURE: {
9729                    // For all apps signature permissions are install time ones.
9730                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9731                    if (allowedSig) {
9732                        grant = GRANT_INSTALL;
9733                    }
9734                } break;
9735            }
9736
9737            if (DEBUG_INSTALL) {
9738                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9739            }
9740
9741            if (grant != GRANT_DENIED) {
9742                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9743                    // If this is an existing, non-system package, then
9744                    // we can't add any new permissions to it.
9745                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9746                        // Except...  if this is a permission that was added
9747                        // to the platform (note: need to only do this when
9748                        // updating the platform).
9749                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9750                            grant = GRANT_DENIED;
9751                        }
9752                    }
9753                }
9754
9755                switch (grant) {
9756                    case GRANT_INSTALL: {
9757                        // Revoke this as runtime permission to handle the case of
9758                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9759                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9760                            if (origPermissions.getRuntimePermissionState(
9761                                    bp.name, userId) != null) {
9762                                // Revoke the runtime permission and clear the flags.
9763                                origPermissions.revokeRuntimePermission(bp, userId);
9764                                origPermissions.updatePermissionFlags(bp, userId,
9765                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9766                                // If we revoked a permission permission, we have to write.
9767                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9768                                        changedRuntimePermissionUserIds, userId);
9769                            }
9770                        }
9771                        // Grant an install permission.
9772                        if (permissionsState.grantInstallPermission(bp) !=
9773                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9774                            changedInstallPermission = true;
9775                        }
9776                    } break;
9777
9778                    case GRANT_RUNTIME: {
9779                        // Grant previously granted runtime permissions.
9780                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9781                            PermissionState permissionState = origPermissions
9782                                    .getRuntimePermissionState(bp.name, userId);
9783                            int flags = permissionState != null
9784                                    ? permissionState.getFlags() : 0;
9785                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9786                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9787                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9788                                    // If we cannot put the permission as it was, we have to write.
9789                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9790                                            changedRuntimePermissionUserIds, userId);
9791                                }
9792                                // If the app supports runtime permissions no need for a review.
9793                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9794                                        && appSupportsRuntimePermissions
9795                                        && (flags & PackageManager
9796                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9797                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9798                                    // Since we changed the flags, we have to write.
9799                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9800                                            changedRuntimePermissionUserIds, userId);
9801                                }
9802                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9803                                    && !appSupportsRuntimePermissions) {
9804                                // For legacy apps that need a permission review, every new
9805                                // runtime permission is granted but it is pending a review.
9806                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9807                                    permissionsState.grantRuntimePermission(bp, userId);
9808                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9809                                    // We changed the permission and flags, hence have to write.
9810                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9811                                            changedRuntimePermissionUserIds, userId);
9812                                }
9813                            }
9814                            // Propagate the permission flags.
9815                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9816                        }
9817                    } break;
9818
9819                    case GRANT_UPGRADE: {
9820                        // Grant runtime permissions for a previously held install permission.
9821                        PermissionState permissionState = origPermissions
9822                                .getInstallPermissionState(bp.name);
9823                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9824
9825                        if (origPermissions.revokeInstallPermission(bp)
9826                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9827                            // We will be transferring the permission flags, so clear them.
9828                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9829                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9830                            changedInstallPermission = true;
9831                        }
9832
9833                        // If the permission is not to be promoted to runtime we ignore it and
9834                        // also its other flags as they are not applicable to install permissions.
9835                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9836                            for (int userId : currentUserIds) {
9837                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9838                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9839                                    // Transfer the permission flags.
9840                                    permissionsState.updatePermissionFlags(bp, userId,
9841                                            flags, flags);
9842                                    // If we granted the permission, we have to write.
9843                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9844                                            changedRuntimePermissionUserIds, userId);
9845                                }
9846                            }
9847                        }
9848                    } break;
9849
9850                    default: {
9851                        if (packageOfInterest == null
9852                                || packageOfInterest.equals(pkg.packageName)) {
9853                            Slog.w(TAG, "Not granting permission " + perm
9854                                    + " to package " + pkg.packageName
9855                                    + " because it was previously installed without");
9856                        }
9857                    } break;
9858                }
9859            } else {
9860                if (permissionsState.revokeInstallPermission(bp) !=
9861                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9862                    // Also drop the permission flags.
9863                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9864                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9865                    changedInstallPermission = true;
9866                    Slog.i(TAG, "Un-granting permission " + perm
9867                            + " from package " + pkg.packageName
9868                            + " (protectionLevel=" + bp.protectionLevel
9869                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9870                            + ")");
9871                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9872                    // Don't print warning for app op permissions, since it is fine for them
9873                    // not to be granted, there is a UI for the user to decide.
9874                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9875                        Slog.w(TAG, "Not granting permission " + perm
9876                                + " to package " + pkg.packageName
9877                                + " (protectionLevel=" + bp.protectionLevel
9878                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9879                                + ")");
9880                    }
9881                }
9882            }
9883        }
9884
9885        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9886                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9887            // This is the first that we have heard about this package, so the
9888            // permissions we have now selected are fixed until explicitly
9889            // changed.
9890            ps.installPermissionsFixed = true;
9891        }
9892
9893        // Persist the runtime permissions state for users with changes. If permissions
9894        // were revoked because no app in the shared user declares them we have to
9895        // write synchronously to avoid losing runtime permissions state.
9896        for (int userId : changedRuntimePermissionUserIds) {
9897            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9898        }
9899
9900        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9901    }
9902
9903    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9904        boolean allowed = false;
9905        final int NP = PackageParser.NEW_PERMISSIONS.length;
9906        for (int ip=0; ip<NP; ip++) {
9907            final PackageParser.NewPermissionInfo npi
9908                    = PackageParser.NEW_PERMISSIONS[ip];
9909            if (npi.name.equals(perm)
9910                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9911                allowed = true;
9912                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9913                        + pkg.packageName);
9914                break;
9915            }
9916        }
9917        return allowed;
9918    }
9919
9920    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9921            BasePermission bp, PermissionsState origPermissions) {
9922        boolean allowed;
9923        allowed = (compareSignatures(
9924                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9925                        == PackageManager.SIGNATURE_MATCH)
9926                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9927                        == PackageManager.SIGNATURE_MATCH);
9928        if (!allowed && (bp.protectionLevel
9929                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9930            if (isSystemApp(pkg)) {
9931                // For updated system applications, a system permission
9932                // is granted only if it had been defined by the original application.
9933                if (pkg.isUpdatedSystemApp()) {
9934                    final PackageSetting sysPs = mSettings
9935                            .getDisabledSystemPkgLPr(pkg.packageName);
9936                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9937                        // If the original was granted this permission, we take
9938                        // that grant decision as read and propagate it to the
9939                        // update.
9940                        if (sysPs.isPrivileged()) {
9941                            allowed = true;
9942                        }
9943                    } else {
9944                        // The system apk may have been updated with an older
9945                        // version of the one on the data partition, but which
9946                        // granted a new system permission that it didn't have
9947                        // before.  In this case we do want to allow the app to
9948                        // now get the new permission if the ancestral apk is
9949                        // privileged to get it.
9950                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9951                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9952                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9953                                    allowed = true;
9954                                    break;
9955                                }
9956                            }
9957                        }
9958                        // Also if a privileged parent package on the system image or any of
9959                        // its children requested a privileged permission, the updated child
9960                        // packages can also get the permission.
9961                        if (pkg.parentPackage != null) {
9962                            final PackageSetting disabledSysParentPs = mSettings
9963                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9964                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9965                                    && disabledSysParentPs.isPrivileged()) {
9966                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9967                                    allowed = true;
9968                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9969                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9970                                    for (int i = 0; i < count; i++) {
9971                                        PackageParser.Package disabledSysChildPkg =
9972                                                disabledSysParentPs.pkg.childPackages.get(i);
9973                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9974                                                perm)) {
9975                                            allowed = true;
9976                                            break;
9977                                        }
9978                                    }
9979                                }
9980                            }
9981                        }
9982                    }
9983                } else {
9984                    allowed = isPrivilegedApp(pkg);
9985                }
9986            }
9987        }
9988        if (!allowed) {
9989            if (!allowed && (bp.protectionLevel
9990                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9991                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9992                // If this was a previously normal/dangerous permission that got moved
9993                // to a system permission as part of the runtime permission redesign, then
9994                // we still want to blindly grant it to old apps.
9995                allowed = true;
9996            }
9997            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9998                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9999                // If this permission is to be granted to the system installer and
10000                // this app is an installer, then it gets the permission.
10001                allowed = true;
10002            }
10003            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10004                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10005                // If this permission is to be granted to the system verifier and
10006                // this app is a verifier, then it gets the permission.
10007                allowed = true;
10008            }
10009            if (!allowed && (bp.protectionLevel
10010                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10011                    && isSystemApp(pkg)) {
10012                // Any pre-installed system app is allowed to get this permission.
10013                allowed = true;
10014            }
10015            if (!allowed && (bp.protectionLevel
10016                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10017                // For development permissions, a development permission
10018                // is granted only if it was already granted.
10019                allowed = origPermissions.hasInstallPermission(perm);
10020            }
10021            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10022                    && pkg.packageName.equals(mSetupWizardPackage)) {
10023                // If this permission is to be granted to the system setup wizard and
10024                // this app is a setup wizard, then it gets the permission.
10025                allowed = true;
10026            }
10027        }
10028        return allowed;
10029    }
10030
10031    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10032        final int permCount = pkg.requestedPermissions.size();
10033        for (int j = 0; j < permCount; j++) {
10034            String requestedPermission = pkg.requestedPermissions.get(j);
10035            if (permission.equals(requestedPermission)) {
10036                return true;
10037            }
10038        }
10039        return false;
10040    }
10041
10042    final class ActivityIntentResolver
10043            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10044        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10045                boolean defaultOnly, int userId) {
10046            if (!sUserManager.exists(userId)) return null;
10047            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10048            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10049        }
10050
10051        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10052                int userId) {
10053            if (!sUserManager.exists(userId)) return null;
10054            mFlags = flags;
10055            return super.queryIntent(intent, resolvedType,
10056                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10057        }
10058
10059        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10060                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10061            if (!sUserManager.exists(userId)) return null;
10062            if (packageActivities == null) {
10063                return null;
10064            }
10065            mFlags = flags;
10066            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10067            final int N = packageActivities.size();
10068            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10069                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10070
10071            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10072            for (int i = 0; i < N; ++i) {
10073                intentFilters = packageActivities.get(i).intents;
10074                if (intentFilters != null && intentFilters.size() > 0) {
10075                    PackageParser.ActivityIntentInfo[] array =
10076                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10077                    intentFilters.toArray(array);
10078                    listCut.add(array);
10079                }
10080            }
10081            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10082        }
10083
10084        /**
10085         * Finds a privileged activity that matches the specified activity names.
10086         */
10087        private PackageParser.Activity findMatchingActivity(
10088                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10089            for (PackageParser.Activity sysActivity : activityList) {
10090                if (sysActivity.info.name.equals(activityInfo.name)) {
10091                    return sysActivity;
10092                }
10093                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10094                    return sysActivity;
10095                }
10096                if (sysActivity.info.targetActivity != null) {
10097                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10098                        return sysActivity;
10099                    }
10100                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10101                        return sysActivity;
10102                    }
10103                }
10104            }
10105            return null;
10106        }
10107
10108        public class IterGenerator<E> {
10109            public Iterator<E> generate(ActivityIntentInfo info) {
10110                return null;
10111            }
10112        }
10113
10114        public class ActionIterGenerator extends IterGenerator<String> {
10115            @Override
10116            public Iterator<String> generate(ActivityIntentInfo info) {
10117                return info.actionsIterator();
10118            }
10119        }
10120
10121        public class CategoriesIterGenerator extends IterGenerator<String> {
10122            @Override
10123            public Iterator<String> generate(ActivityIntentInfo info) {
10124                return info.categoriesIterator();
10125            }
10126        }
10127
10128        public class SchemesIterGenerator extends IterGenerator<String> {
10129            @Override
10130            public Iterator<String> generate(ActivityIntentInfo info) {
10131                return info.schemesIterator();
10132            }
10133        }
10134
10135        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10136            @Override
10137            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10138                return info.authoritiesIterator();
10139            }
10140        }
10141
10142        /**
10143         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10144         * MODIFIED. Do not pass in a list that should not be changed.
10145         */
10146        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10147                IterGenerator<T> generator, Iterator<T> searchIterator) {
10148            // loop through the set of actions; every one must be found in the intent filter
10149            while (searchIterator.hasNext()) {
10150                // we must have at least one filter in the list to consider a match
10151                if (intentList.size() == 0) {
10152                    break;
10153                }
10154
10155                final T searchAction = searchIterator.next();
10156
10157                // loop through the set of intent filters
10158                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10159                while (intentIter.hasNext()) {
10160                    final ActivityIntentInfo intentInfo = intentIter.next();
10161                    boolean selectionFound = false;
10162
10163                    // loop through the intent filter's selection criteria; at least one
10164                    // of them must match the searched criteria
10165                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10166                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10167                        final T intentSelection = intentSelectionIter.next();
10168                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10169                            selectionFound = true;
10170                            break;
10171                        }
10172                    }
10173
10174                    // the selection criteria wasn't found in this filter's set; this filter
10175                    // is not a potential match
10176                    if (!selectionFound) {
10177                        intentIter.remove();
10178                    }
10179                }
10180            }
10181        }
10182
10183        private boolean isProtectedAction(ActivityIntentInfo filter) {
10184            final Iterator<String> actionsIter = filter.actionsIterator();
10185            while (actionsIter != null && actionsIter.hasNext()) {
10186                final String filterAction = actionsIter.next();
10187                if (PROTECTED_ACTIONS.contains(filterAction)) {
10188                    return true;
10189                }
10190            }
10191            return false;
10192        }
10193
10194        /**
10195         * Adjusts the priority of the given intent filter according to policy.
10196         * <p>
10197         * <ul>
10198         * <li>The priority for non privileged applications is capped to '0'</li>
10199         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10200         * <li>The priority for unbundled updates to privileged applications is capped to the
10201         *      priority defined on the system partition</li>
10202         * </ul>
10203         * <p>
10204         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10205         * allowed to obtain any priority on any action.
10206         */
10207        private void adjustPriority(
10208                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10209            // nothing to do; priority is fine as-is
10210            if (intent.getPriority() <= 0) {
10211                return;
10212            }
10213
10214            final ActivityInfo activityInfo = intent.activity.info;
10215            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10216
10217            final boolean privilegedApp =
10218                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10219            if (!privilegedApp) {
10220                // non-privileged applications can never define a priority >0
10221                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10222                        + " package: " + applicationInfo.packageName
10223                        + " activity: " + intent.activity.className
10224                        + " origPrio: " + intent.getPriority());
10225                intent.setPriority(0);
10226                return;
10227            }
10228
10229            if (systemActivities == null) {
10230                // the system package is not disabled; we're parsing the system partition
10231                if (isProtectedAction(intent)) {
10232                    if (mDeferProtectedFilters) {
10233                        // We can't deal with these just yet. No component should ever obtain a
10234                        // >0 priority for a protected actions, with ONE exception -- the setup
10235                        // wizard. The setup wizard, however, cannot be known until we're able to
10236                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10237                        // until all intent filters have been processed. Chicken, meet egg.
10238                        // Let the filter temporarily have a high priority and rectify the
10239                        // priorities after all system packages have been scanned.
10240                        mProtectedFilters.add(intent);
10241                        if (DEBUG_FILTERS) {
10242                            Slog.i(TAG, "Protected action; save for later;"
10243                                    + " package: " + applicationInfo.packageName
10244                                    + " activity: " + intent.activity.className
10245                                    + " origPrio: " + intent.getPriority());
10246                        }
10247                        return;
10248                    } else {
10249                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10250                            Slog.i(TAG, "No setup wizard;"
10251                                + " All protected intents capped to priority 0");
10252                        }
10253                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10254                            if (DEBUG_FILTERS) {
10255                                Slog.i(TAG, "Found setup wizard;"
10256                                    + " allow priority " + intent.getPriority() + ";"
10257                                    + " package: " + intent.activity.info.packageName
10258                                    + " activity: " + intent.activity.className
10259                                    + " priority: " + intent.getPriority());
10260                            }
10261                            // setup wizard gets whatever it wants
10262                            return;
10263                        }
10264                        Slog.w(TAG, "Protected action; cap priority to 0;"
10265                                + " package: " + intent.activity.info.packageName
10266                                + " activity: " + intent.activity.className
10267                                + " origPrio: " + intent.getPriority());
10268                        intent.setPriority(0);
10269                        return;
10270                    }
10271                }
10272                // privileged apps on the system image get whatever priority they request
10273                return;
10274            }
10275
10276            // privileged app unbundled update ... try to find the same activity
10277            final PackageParser.Activity foundActivity =
10278                    findMatchingActivity(systemActivities, activityInfo);
10279            if (foundActivity == null) {
10280                // this is a new activity; it cannot obtain >0 priority
10281                if (DEBUG_FILTERS) {
10282                    Slog.i(TAG, "New activity; cap priority to 0;"
10283                            + " package: " + applicationInfo.packageName
10284                            + " activity: " + intent.activity.className
10285                            + " origPrio: " + intent.getPriority());
10286                }
10287                intent.setPriority(0);
10288                return;
10289            }
10290
10291            // found activity, now check for filter equivalence
10292
10293            // a shallow copy is enough; we modify the list, not its contents
10294            final List<ActivityIntentInfo> intentListCopy =
10295                    new ArrayList<>(foundActivity.intents);
10296            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10297
10298            // find matching action subsets
10299            final Iterator<String> actionsIterator = intent.actionsIterator();
10300            if (actionsIterator != null) {
10301                getIntentListSubset(
10302                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10303                if (intentListCopy.size() == 0) {
10304                    // no more intents to match; we're not equivalent
10305                    if (DEBUG_FILTERS) {
10306                        Slog.i(TAG, "Mismatched action; 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 category subsets
10317            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10318            if (categoriesIterator != null) {
10319                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10320                        categoriesIterator);
10321                if (intentListCopy.size() == 0) {
10322                    // no more intents to match; we're not equivalent
10323                    if (DEBUG_FILTERS) {
10324                        Slog.i(TAG, "Mismatched category; 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 schemes subsets
10335            final Iterator<String> schemesIterator = intent.schemesIterator();
10336            if (schemesIterator != null) {
10337                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10338                        schemesIterator);
10339                if (intentListCopy.size() == 0) {
10340                    // no more intents to match; we're not equivalent
10341                    if (DEBUG_FILTERS) {
10342                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10343                                + " package: " + applicationInfo.packageName
10344                                + " activity: " + intent.activity.className
10345                                + " origPrio: " + intent.getPriority());
10346                    }
10347                    intent.setPriority(0);
10348                    return;
10349                }
10350            }
10351
10352            // find matching authorities subsets
10353            final Iterator<IntentFilter.AuthorityEntry>
10354                    authoritiesIterator = intent.authoritiesIterator();
10355            if (authoritiesIterator != null) {
10356                getIntentListSubset(intentListCopy,
10357                        new AuthoritiesIterGenerator(),
10358                        authoritiesIterator);
10359                if (intentListCopy.size() == 0) {
10360                    // no more intents to match; we're not equivalent
10361                    if (DEBUG_FILTERS) {
10362                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10363                                + " package: " + applicationInfo.packageName
10364                                + " activity: " + intent.activity.className
10365                                + " origPrio: " + intent.getPriority());
10366                    }
10367                    intent.setPriority(0);
10368                    return;
10369                }
10370            }
10371
10372            // we found matching filter(s); app gets the max priority of all intents
10373            int cappedPriority = 0;
10374            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10375                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10376            }
10377            if (intent.getPriority() > cappedPriority) {
10378                if (DEBUG_FILTERS) {
10379                    Slog.i(TAG, "Found matching filter(s);"
10380                            + " cap priority to " + cappedPriority + ";"
10381                            + " package: " + applicationInfo.packageName
10382                            + " activity: " + intent.activity.className
10383                            + " origPrio: " + intent.getPriority());
10384                }
10385                intent.setPriority(cappedPriority);
10386                return;
10387            }
10388            // all this for nothing; the requested priority was <= what was on the system
10389        }
10390
10391        public final void addActivity(PackageParser.Activity a, String type) {
10392            mActivities.put(a.getComponentName(), a);
10393            if (DEBUG_SHOW_INFO)
10394                Log.v(
10395                TAG, "  " + type + " " +
10396                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10397            if (DEBUG_SHOW_INFO)
10398                Log.v(TAG, "    Class=" + a.info.name);
10399            final int NI = a.intents.size();
10400            for (int j=0; j<NI; j++) {
10401                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10402                if ("activity".equals(type)) {
10403                    final PackageSetting ps =
10404                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10405                    final List<PackageParser.Activity> systemActivities =
10406                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10407                    adjustPriority(systemActivities, intent);
10408                }
10409                if (DEBUG_SHOW_INFO) {
10410                    Log.v(TAG, "    IntentFilter:");
10411                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10412                }
10413                if (!intent.debugCheck()) {
10414                    Log.w(TAG, "==> For Activity " + a.info.name);
10415                }
10416                addFilter(intent);
10417            }
10418        }
10419
10420        public final void removeActivity(PackageParser.Activity a, String type) {
10421            mActivities.remove(a.getComponentName());
10422            if (DEBUG_SHOW_INFO) {
10423                Log.v(TAG, "  " + type + " "
10424                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10425                                : a.info.name) + ":");
10426                Log.v(TAG, "    Class=" + a.info.name);
10427            }
10428            final int NI = a.intents.size();
10429            for (int j=0; j<NI; j++) {
10430                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10431                if (DEBUG_SHOW_INFO) {
10432                    Log.v(TAG, "    IntentFilter:");
10433                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10434                }
10435                removeFilter(intent);
10436            }
10437        }
10438
10439        @Override
10440        protected boolean allowFilterResult(
10441                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10442            ActivityInfo filterAi = filter.activity.info;
10443            for (int i=dest.size()-1; i>=0; i--) {
10444                ActivityInfo destAi = dest.get(i).activityInfo;
10445                if (destAi.name == filterAi.name
10446                        && destAi.packageName == filterAi.packageName) {
10447                    return false;
10448                }
10449            }
10450            return true;
10451        }
10452
10453        @Override
10454        protected ActivityIntentInfo[] newArray(int size) {
10455            return new ActivityIntentInfo[size];
10456        }
10457
10458        @Override
10459        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10460            if (!sUserManager.exists(userId)) return true;
10461            PackageParser.Package p = filter.activity.owner;
10462            if (p != null) {
10463                PackageSetting ps = (PackageSetting)p.mExtras;
10464                if (ps != null) {
10465                    // System apps are never considered stopped for purposes of
10466                    // filtering, because there may be no way for the user to
10467                    // actually re-launch them.
10468                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10469                            && ps.getStopped(userId);
10470                }
10471            }
10472            return false;
10473        }
10474
10475        @Override
10476        protected boolean isPackageForFilter(String packageName,
10477                PackageParser.ActivityIntentInfo info) {
10478            return packageName.equals(info.activity.owner.packageName);
10479        }
10480
10481        @Override
10482        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10483                int match, int userId) {
10484            if (!sUserManager.exists(userId)) return null;
10485            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10486                return null;
10487            }
10488            final PackageParser.Activity activity = info.activity;
10489            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10490            if (ps == null) {
10491                return null;
10492            }
10493            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10494                    ps.readUserState(userId), userId);
10495            if (ai == null) {
10496                return null;
10497            }
10498            final ResolveInfo res = new ResolveInfo();
10499            res.activityInfo = ai;
10500            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10501                res.filter = info;
10502            }
10503            if (info != null) {
10504                res.handleAllWebDataURI = info.handleAllWebDataURI();
10505            }
10506            res.priority = info.getPriority();
10507            res.preferredOrder = activity.owner.mPreferredOrder;
10508            //System.out.println("Result: " + res.activityInfo.className +
10509            //                   " = " + res.priority);
10510            res.match = match;
10511            res.isDefault = info.hasDefault;
10512            res.labelRes = info.labelRes;
10513            res.nonLocalizedLabel = info.nonLocalizedLabel;
10514            if (userNeedsBadging(userId)) {
10515                res.noResourceId = true;
10516            } else {
10517                res.icon = info.icon;
10518            }
10519            res.iconResourceId = info.icon;
10520            res.system = res.activityInfo.applicationInfo.isSystemApp();
10521            return res;
10522        }
10523
10524        @Override
10525        protected void sortResults(List<ResolveInfo> results) {
10526            Collections.sort(results, mResolvePrioritySorter);
10527        }
10528
10529        @Override
10530        protected void dumpFilter(PrintWriter out, String prefix,
10531                PackageParser.ActivityIntentInfo filter) {
10532            out.print(prefix); out.print(
10533                    Integer.toHexString(System.identityHashCode(filter.activity)));
10534                    out.print(' ');
10535                    filter.activity.printComponentShortName(out);
10536                    out.print(" filter ");
10537                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10538        }
10539
10540        @Override
10541        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10542            return filter.activity;
10543        }
10544
10545        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10546            PackageParser.Activity activity = (PackageParser.Activity)label;
10547            out.print(prefix); out.print(
10548                    Integer.toHexString(System.identityHashCode(activity)));
10549                    out.print(' ');
10550                    activity.printComponentShortName(out);
10551            if (count > 1) {
10552                out.print(" ("); out.print(count); out.print(" filters)");
10553            }
10554            out.println();
10555        }
10556
10557        // Keys are String (activity class name), values are Activity.
10558        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10559                = new ArrayMap<ComponentName, PackageParser.Activity>();
10560        private int mFlags;
10561    }
10562
10563    private final class ServiceIntentResolver
10564            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10565        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10566                boolean defaultOnly, int userId) {
10567            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10568            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10569        }
10570
10571        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10572                int userId) {
10573            if (!sUserManager.exists(userId)) return null;
10574            mFlags = flags;
10575            return super.queryIntent(intent, resolvedType,
10576                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10577        }
10578
10579        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10580                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10581            if (!sUserManager.exists(userId)) return null;
10582            if (packageServices == null) {
10583                return null;
10584            }
10585            mFlags = flags;
10586            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10587            final int N = packageServices.size();
10588            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10589                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10590
10591            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10592            for (int i = 0; i < N; ++i) {
10593                intentFilters = packageServices.get(i).intents;
10594                if (intentFilters != null && intentFilters.size() > 0) {
10595                    PackageParser.ServiceIntentInfo[] array =
10596                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10597                    intentFilters.toArray(array);
10598                    listCut.add(array);
10599                }
10600            }
10601            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10602        }
10603
10604        public final void addService(PackageParser.Service s) {
10605            mServices.put(s.getComponentName(), s);
10606            if (DEBUG_SHOW_INFO) {
10607                Log.v(TAG, "  "
10608                        + (s.info.nonLocalizedLabel != null
10609                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10610                Log.v(TAG, "    Class=" + s.info.name);
10611            }
10612            final int NI = s.intents.size();
10613            int j;
10614            for (j=0; j<NI; j++) {
10615                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10616                if (DEBUG_SHOW_INFO) {
10617                    Log.v(TAG, "    IntentFilter:");
10618                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10619                }
10620                if (!intent.debugCheck()) {
10621                    Log.w(TAG, "==> For Service " + s.info.name);
10622                }
10623                addFilter(intent);
10624            }
10625        }
10626
10627        public final void removeService(PackageParser.Service s) {
10628            mServices.remove(s.getComponentName());
10629            if (DEBUG_SHOW_INFO) {
10630                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10631                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10632                Log.v(TAG, "    Class=" + s.info.name);
10633            }
10634            final int NI = s.intents.size();
10635            int j;
10636            for (j=0; j<NI; j++) {
10637                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10638                if (DEBUG_SHOW_INFO) {
10639                    Log.v(TAG, "    IntentFilter:");
10640                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10641                }
10642                removeFilter(intent);
10643            }
10644        }
10645
10646        @Override
10647        protected boolean allowFilterResult(
10648                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10649            ServiceInfo filterSi = filter.service.info;
10650            for (int i=dest.size()-1; i>=0; i--) {
10651                ServiceInfo destAi = dest.get(i).serviceInfo;
10652                if (destAi.name == filterSi.name
10653                        && destAi.packageName == filterSi.packageName) {
10654                    return false;
10655                }
10656            }
10657            return true;
10658        }
10659
10660        @Override
10661        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10662            return new PackageParser.ServiceIntentInfo[size];
10663        }
10664
10665        @Override
10666        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10667            if (!sUserManager.exists(userId)) return true;
10668            PackageParser.Package p = filter.service.owner;
10669            if (p != null) {
10670                PackageSetting ps = (PackageSetting)p.mExtras;
10671                if (ps != null) {
10672                    // System apps are never considered stopped for purposes of
10673                    // filtering, because there may be no way for the user to
10674                    // actually re-launch them.
10675                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10676                            && ps.getStopped(userId);
10677                }
10678            }
10679            return false;
10680        }
10681
10682        @Override
10683        protected boolean isPackageForFilter(String packageName,
10684                PackageParser.ServiceIntentInfo info) {
10685            return packageName.equals(info.service.owner.packageName);
10686        }
10687
10688        @Override
10689        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10690                int match, int userId) {
10691            if (!sUserManager.exists(userId)) return null;
10692            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10693            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10694                return null;
10695            }
10696            final PackageParser.Service service = info.service;
10697            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10698            if (ps == null) {
10699                return null;
10700            }
10701            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10702                    ps.readUserState(userId), userId);
10703            if (si == null) {
10704                return null;
10705            }
10706            final ResolveInfo res = new ResolveInfo();
10707            res.serviceInfo = si;
10708            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10709                res.filter = filter;
10710            }
10711            res.priority = info.getPriority();
10712            res.preferredOrder = service.owner.mPreferredOrder;
10713            res.match = match;
10714            res.isDefault = info.hasDefault;
10715            res.labelRes = info.labelRes;
10716            res.nonLocalizedLabel = info.nonLocalizedLabel;
10717            res.icon = info.icon;
10718            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10719            return res;
10720        }
10721
10722        @Override
10723        protected void sortResults(List<ResolveInfo> results) {
10724            Collections.sort(results, mResolvePrioritySorter);
10725        }
10726
10727        @Override
10728        protected void dumpFilter(PrintWriter out, String prefix,
10729                PackageParser.ServiceIntentInfo filter) {
10730            out.print(prefix); out.print(
10731                    Integer.toHexString(System.identityHashCode(filter.service)));
10732                    out.print(' ');
10733                    filter.service.printComponentShortName(out);
10734                    out.print(" filter ");
10735                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10736        }
10737
10738        @Override
10739        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10740            return filter.service;
10741        }
10742
10743        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10744            PackageParser.Service service = (PackageParser.Service)label;
10745            out.print(prefix); out.print(
10746                    Integer.toHexString(System.identityHashCode(service)));
10747                    out.print(' ');
10748                    service.printComponentShortName(out);
10749            if (count > 1) {
10750                out.print(" ("); out.print(count); out.print(" filters)");
10751            }
10752            out.println();
10753        }
10754
10755//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10756//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10757//            final List<ResolveInfo> retList = Lists.newArrayList();
10758//            while (i.hasNext()) {
10759//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10760//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10761//                    retList.add(resolveInfo);
10762//                }
10763//            }
10764//            return retList;
10765//        }
10766
10767        // Keys are String (activity class name), values are Activity.
10768        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10769                = new ArrayMap<ComponentName, PackageParser.Service>();
10770        private int mFlags;
10771    };
10772
10773    private final class ProviderIntentResolver
10774            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10775        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10776                boolean defaultOnly, int userId) {
10777            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10778            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10779        }
10780
10781        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10782                int userId) {
10783            if (!sUserManager.exists(userId))
10784                return null;
10785            mFlags = flags;
10786            return super.queryIntent(intent, resolvedType,
10787                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10788        }
10789
10790        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10791                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10792            if (!sUserManager.exists(userId))
10793                return null;
10794            if (packageProviders == null) {
10795                return null;
10796            }
10797            mFlags = flags;
10798            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10799            final int N = packageProviders.size();
10800            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10801                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10802
10803            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10804            for (int i = 0; i < N; ++i) {
10805                intentFilters = packageProviders.get(i).intents;
10806                if (intentFilters != null && intentFilters.size() > 0) {
10807                    PackageParser.ProviderIntentInfo[] array =
10808                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10809                    intentFilters.toArray(array);
10810                    listCut.add(array);
10811                }
10812            }
10813            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10814        }
10815
10816        public final void addProvider(PackageParser.Provider p) {
10817            if (mProviders.containsKey(p.getComponentName())) {
10818                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10819                return;
10820            }
10821
10822            mProviders.put(p.getComponentName(), p);
10823            if (DEBUG_SHOW_INFO) {
10824                Log.v(TAG, "  "
10825                        + (p.info.nonLocalizedLabel != null
10826                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10827                Log.v(TAG, "    Class=" + p.info.name);
10828            }
10829            final int NI = p.intents.size();
10830            int j;
10831            for (j = 0; j < NI; j++) {
10832                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10833                if (DEBUG_SHOW_INFO) {
10834                    Log.v(TAG, "    IntentFilter:");
10835                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10836                }
10837                if (!intent.debugCheck()) {
10838                    Log.w(TAG, "==> For Provider " + p.info.name);
10839                }
10840                addFilter(intent);
10841            }
10842        }
10843
10844        public final void removeProvider(PackageParser.Provider p) {
10845            mProviders.remove(p.getComponentName());
10846            if (DEBUG_SHOW_INFO) {
10847                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10848                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10849                Log.v(TAG, "    Class=" + p.info.name);
10850            }
10851            final int NI = p.intents.size();
10852            int j;
10853            for (j = 0; j < NI; j++) {
10854                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10855                if (DEBUG_SHOW_INFO) {
10856                    Log.v(TAG, "    IntentFilter:");
10857                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10858                }
10859                removeFilter(intent);
10860            }
10861        }
10862
10863        @Override
10864        protected boolean allowFilterResult(
10865                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10866            ProviderInfo filterPi = filter.provider.info;
10867            for (int i = dest.size() - 1; i >= 0; i--) {
10868                ProviderInfo destPi = dest.get(i).providerInfo;
10869                if (destPi.name == filterPi.name
10870                        && destPi.packageName == filterPi.packageName) {
10871                    return false;
10872                }
10873            }
10874            return true;
10875        }
10876
10877        @Override
10878        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10879            return new PackageParser.ProviderIntentInfo[size];
10880        }
10881
10882        @Override
10883        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10884            if (!sUserManager.exists(userId))
10885                return true;
10886            PackageParser.Package p = filter.provider.owner;
10887            if (p != null) {
10888                PackageSetting ps = (PackageSetting) p.mExtras;
10889                if (ps != null) {
10890                    // System apps are never considered stopped for purposes of
10891                    // filtering, because there may be no way for the user to
10892                    // actually re-launch them.
10893                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10894                            && ps.getStopped(userId);
10895                }
10896            }
10897            return false;
10898        }
10899
10900        @Override
10901        protected boolean isPackageForFilter(String packageName,
10902                PackageParser.ProviderIntentInfo info) {
10903            return packageName.equals(info.provider.owner.packageName);
10904        }
10905
10906        @Override
10907        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10908                int match, int userId) {
10909            if (!sUserManager.exists(userId))
10910                return null;
10911            final PackageParser.ProviderIntentInfo info = filter;
10912            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10913                return null;
10914            }
10915            final PackageParser.Provider provider = info.provider;
10916            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10917            if (ps == null) {
10918                return null;
10919            }
10920            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10921                    ps.readUserState(userId), userId);
10922            if (pi == null) {
10923                return null;
10924            }
10925            final ResolveInfo res = new ResolveInfo();
10926            res.providerInfo = pi;
10927            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10928                res.filter = filter;
10929            }
10930            res.priority = info.getPriority();
10931            res.preferredOrder = provider.owner.mPreferredOrder;
10932            res.match = match;
10933            res.isDefault = info.hasDefault;
10934            res.labelRes = info.labelRes;
10935            res.nonLocalizedLabel = info.nonLocalizedLabel;
10936            res.icon = info.icon;
10937            res.system = res.providerInfo.applicationInfo.isSystemApp();
10938            return res;
10939        }
10940
10941        @Override
10942        protected void sortResults(List<ResolveInfo> results) {
10943            Collections.sort(results, mResolvePrioritySorter);
10944        }
10945
10946        @Override
10947        protected void dumpFilter(PrintWriter out, String prefix,
10948                PackageParser.ProviderIntentInfo filter) {
10949            out.print(prefix);
10950            out.print(
10951                    Integer.toHexString(System.identityHashCode(filter.provider)));
10952            out.print(' ');
10953            filter.provider.printComponentShortName(out);
10954            out.print(" filter ");
10955            out.println(Integer.toHexString(System.identityHashCode(filter)));
10956        }
10957
10958        @Override
10959        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10960            return filter.provider;
10961        }
10962
10963        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10964            PackageParser.Provider provider = (PackageParser.Provider)label;
10965            out.print(prefix); out.print(
10966                    Integer.toHexString(System.identityHashCode(provider)));
10967                    out.print(' ');
10968                    provider.printComponentShortName(out);
10969            if (count > 1) {
10970                out.print(" ("); out.print(count); out.print(" filters)");
10971            }
10972            out.println();
10973        }
10974
10975        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10976                = new ArrayMap<ComponentName, PackageParser.Provider>();
10977        private int mFlags;
10978    }
10979
10980    private static final class EphemeralIntentResolver
10981            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10982        @Override
10983        protected EphemeralResolveIntentInfo[] newArray(int size) {
10984            return new EphemeralResolveIntentInfo[size];
10985        }
10986
10987        @Override
10988        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10989            return true;
10990        }
10991
10992        @Override
10993        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10994                int userId) {
10995            if (!sUserManager.exists(userId)) {
10996                return null;
10997            }
10998            return info.getEphemeralResolveInfo();
10999        }
11000    }
11001
11002    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11003            new Comparator<ResolveInfo>() {
11004        public int compare(ResolveInfo r1, ResolveInfo r2) {
11005            int v1 = r1.priority;
11006            int v2 = r2.priority;
11007            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11008            if (v1 != v2) {
11009                return (v1 > v2) ? -1 : 1;
11010            }
11011            v1 = r1.preferredOrder;
11012            v2 = r2.preferredOrder;
11013            if (v1 != v2) {
11014                return (v1 > v2) ? -1 : 1;
11015            }
11016            if (r1.isDefault != r2.isDefault) {
11017                return r1.isDefault ? -1 : 1;
11018            }
11019            v1 = r1.match;
11020            v2 = r2.match;
11021            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11022            if (v1 != v2) {
11023                return (v1 > v2) ? -1 : 1;
11024            }
11025            if (r1.system != r2.system) {
11026                return r1.system ? -1 : 1;
11027            }
11028            if (r1.activityInfo != null) {
11029                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11030            }
11031            if (r1.serviceInfo != null) {
11032                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11033            }
11034            if (r1.providerInfo != null) {
11035                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11036            }
11037            return 0;
11038        }
11039    };
11040
11041    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11042            new Comparator<ProviderInfo>() {
11043        public int compare(ProviderInfo p1, ProviderInfo p2) {
11044            final int v1 = p1.initOrder;
11045            final int v2 = p2.initOrder;
11046            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11047        }
11048    };
11049
11050    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11051            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11052            final int[] userIds) {
11053        mHandler.post(new Runnable() {
11054            @Override
11055            public void run() {
11056                try {
11057                    final IActivityManager am = ActivityManagerNative.getDefault();
11058                    if (am == null) return;
11059                    final int[] resolvedUserIds;
11060                    if (userIds == null) {
11061                        resolvedUserIds = am.getRunningUserIds();
11062                    } else {
11063                        resolvedUserIds = userIds;
11064                    }
11065                    for (int id : resolvedUserIds) {
11066                        final Intent intent = new Intent(action,
11067                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11068                        if (extras != null) {
11069                            intent.putExtras(extras);
11070                        }
11071                        if (targetPkg != null) {
11072                            intent.setPackage(targetPkg);
11073                        }
11074                        // Modify the UID when posting to other users
11075                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11076                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11077                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11078                            intent.putExtra(Intent.EXTRA_UID, uid);
11079                        }
11080                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11081                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11082                        if (DEBUG_BROADCASTS) {
11083                            RuntimeException here = new RuntimeException("here");
11084                            here.fillInStackTrace();
11085                            Slog.d(TAG, "Sending to user " + id + ": "
11086                                    + intent.toShortString(false, true, false, false)
11087                                    + " " + intent.getExtras(), here);
11088                        }
11089                        am.broadcastIntent(null, intent, null, finishedReceiver,
11090                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11091                                null, finishedReceiver != null, false, id);
11092                    }
11093                } catch (RemoteException ex) {
11094                }
11095            }
11096        });
11097    }
11098
11099    /**
11100     * Check if the external storage media is available. This is true if there
11101     * is a mounted external storage medium or if the external storage is
11102     * emulated.
11103     */
11104    private boolean isExternalMediaAvailable() {
11105        return mMediaMounted || Environment.isExternalStorageEmulated();
11106    }
11107
11108    @Override
11109    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11110        // writer
11111        synchronized (mPackages) {
11112            if (!isExternalMediaAvailable()) {
11113                // If the external storage is no longer mounted at this point,
11114                // the caller may not have been able to delete all of this
11115                // packages files and can not delete any more.  Bail.
11116                return null;
11117            }
11118            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11119            if (lastPackage != null) {
11120                pkgs.remove(lastPackage);
11121            }
11122            if (pkgs.size() > 0) {
11123                return pkgs.get(0);
11124            }
11125        }
11126        return null;
11127    }
11128
11129    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11130        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11131                userId, andCode ? 1 : 0, packageName);
11132        if (mSystemReady) {
11133            msg.sendToTarget();
11134        } else {
11135            if (mPostSystemReadyMessages == null) {
11136                mPostSystemReadyMessages = new ArrayList<>();
11137            }
11138            mPostSystemReadyMessages.add(msg);
11139        }
11140    }
11141
11142    void startCleaningPackages() {
11143        // reader
11144        if (!isExternalMediaAvailable()) {
11145            return;
11146        }
11147        synchronized (mPackages) {
11148            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11149                return;
11150            }
11151        }
11152        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11153        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11154        IActivityManager am = ActivityManagerNative.getDefault();
11155        if (am != null) {
11156            try {
11157                am.startService(null, intent, null, mContext.getOpPackageName(),
11158                        UserHandle.USER_SYSTEM);
11159            } catch (RemoteException e) {
11160            }
11161        }
11162    }
11163
11164    @Override
11165    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11166            int installFlags, String installerPackageName, int userId) {
11167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11168
11169        final int callingUid = Binder.getCallingUid();
11170        enforceCrossUserPermission(callingUid, userId,
11171                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11172
11173        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11174            try {
11175                if (observer != null) {
11176                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11177                }
11178            } catch (RemoteException re) {
11179            }
11180            return;
11181        }
11182
11183        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11184            installFlags |= PackageManager.INSTALL_FROM_ADB;
11185
11186        } else {
11187            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11188            // about installerPackageName.
11189
11190            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11191            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11192        }
11193
11194        UserHandle user;
11195        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11196            user = UserHandle.ALL;
11197        } else {
11198            user = new UserHandle(userId);
11199        }
11200
11201        // Only system components can circumvent runtime permissions when installing.
11202        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11203                && mContext.checkCallingOrSelfPermission(Manifest.permission
11204                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11205            throw new SecurityException("You need the "
11206                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11207                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11208        }
11209
11210        final File originFile = new File(originPath);
11211        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11212
11213        final Message msg = mHandler.obtainMessage(INIT_COPY);
11214        final VerificationInfo verificationInfo = new VerificationInfo(
11215                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11216        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11217                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11218                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11219                null /*certificates*/);
11220        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11221        msg.obj = params;
11222
11223        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11224                System.identityHashCode(msg.obj));
11225        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11226                System.identityHashCode(msg.obj));
11227
11228        mHandler.sendMessage(msg);
11229    }
11230
11231    void installStage(String packageName, File stagedDir, String stagedCid,
11232            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11233            String installerPackageName, int installerUid, UserHandle user,
11234            Certificate[][] certificates) {
11235        if (DEBUG_EPHEMERAL) {
11236            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11237                Slog.d(TAG, "Ephemeral install of " + packageName);
11238            }
11239        }
11240        final VerificationInfo verificationInfo = new VerificationInfo(
11241                sessionParams.originatingUri, sessionParams.referrerUri,
11242                sessionParams.originatingUid, installerUid);
11243
11244        final OriginInfo origin;
11245        if (stagedDir != null) {
11246            origin = OriginInfo.fromStagedFile(stagedDir);
11247        } else {
11248            origin = OriginInfo.fromStagedContainer(stagedCid);
11249        }
11250
11251        final Message msg = mHandler.obtainMessage(INIT_COPY);
11252        final InstallParams params = new InstallParams(origin, null, observer,
11253                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11254                verificationInfo, user, sessionParams.abiOverride,
11255                sessionParams.grantedRuntimePermissions, certificates);
11256        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11257        msg.obj = params;
11258
11259        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11260                System.identityHashCode(msg.obj));
11261        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11262                System.identityHashCode(msg.obj));
11263
11264        mHandler.sendMessage(msg);
11265    }
11266
11267    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11268            int userId) {
11269        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11270        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11271    }
11272
11273    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11274            int appId, int userId) {
11275        Bundle extras = new Bundle(1);
11276        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11277
11278        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11279                packageName, extras, 0, null, null, new int[] {userId});
11280        try {
11281            IActivityManager am = ActivityManagerNative.getDefault();
11282            if (isSystem && am.isUserRunning(userId, 0)) {
11283                // The just-installed/enabled app is bundled on the system, so presumed
11284                // to be able to run automatically without needing an explicit launch.
11285                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11286                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11287                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11288                        .setPackage(packageName);
11289                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11290                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11291            }
11292        } catch (RemoteException e) {
11293            // shouldn't happen
11294            Slog.w(TAG, "Unable to bootstrap installed package", e);
11295        }
11296    }
11297
11298    @Override
11299    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11300            int userId) {
11301        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11302        PackageSetting pkgSetting;
11303        final int uid = Binder.getCallingUid();
11304        enforceCrossUserPermission(uid, userId,
11305                true /* requireFullPermission */, true /* checkShell */,
11306                "setApplicationHiddenSetting for user " + userId);
11307
11308        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11309            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11310            return false;
11311        }
11312
11313        long callingId = Binder.clearCallingIdentity();
11314        try {
11315            boolean sendAdded = false;
11316            boolean sendRemoved = false;
11317            // writer
11318            synchronized (mPackages) {
11319                pkgSetting = mSettings.mPackages.get(packageName);
11320                if (pkgSetting == null) {
11321                    return false;
11322                }
11323                if (pkgSetting.getHidden(userId) != hidden) {
11324                    pkgSetting.setHidden(hidden, userId);
11325                    mSettings.writePackageRestrictionsLPr(userId);
11326                    if (hidden) {
11327                        sendRemoved = true;
11328                    } else {
11329                        sendAdded = true;
11330                    }
11331                }
11332            }
11333            if (sendAdded) {
11334                sendPackageAddedForUser(packageName, pkgSetting, userId);
11335                return true;
11336            }
11337            if (sendRemoved) {
11338                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11339                        "hiding pkg");
11340                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11341                return true;
11342            }
11343        } finally {
11344            Binder.restoreCallingIdentity(callingId);
11345        }
11346        return false;
11347    }
11348
11349    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11350            int userId) {
11351        final PackageRemovedInfo info = new PackageRemovedInfo();
11352        info.removedPackage = packageName;
11353        info.removedUsers = new int[] {userId};
11354        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11355        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11356    }
11357
11358    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11359        if (pkgList.length > 0) {
11360            Bundle extras = new Bundle(1);
11361            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11362
11363            sendPackageBroadcast(
11364                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11365                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11366                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11367                    new int[] {userId});
11368        }
11369    }
11370
11371    /**
11372     * Returns true if application is not found or there was an error. Otherwise it returns
11373     * the hidden state of the package for the given user.
11374     */
11375    @Override
11376    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11377        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11378        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11379                true /* requireFullPermission */, false /* checkShell */,
11380                "getApplicationHidden for user " + userId);
11381        PackageSetting pkgSetting;
11382        long callingId = Binder.clearCallingIdentity();
11383        try {
11384            // writer
11385            synchronized (mPackages) {
11386                pkgSetting = mSettings.mPackages.get(packageName);
11387                if (pkgSetting == null) {
11388                    return true;
11389                }
11390                return pkgSetting.getHidden(userId);
11391            }
11392        } finally {
11393            Binder.restoreCallingIdentity(callingId);
11394        }
11395    }
11396
11397    /**
11398     * @hide
11399     */
11400    @Override
11401    public int installExistingPackageAsUser(String packageName, int userId) {
11402        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11403                null);
11404        PackageSetting pkgSetting;
11405        final int uid = Binder.getCallingUid();
11406        enforceCrossUserPermission(uid, userId,
11407                true /* requireFullPermission */, true /* checkShell */,
11408                "installExistingPackage for user " + userId);
11409        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11410            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11411        }
11412
11413        long callingId = Binder.clearCallingIdentity();
11414        try {
11415            boolean installed = false;
11416
11417            // writer
11418            synchronized (mPackages) {
11419                pkgSetting = mSettings.mPackages.get(packageName);
11420                if (pkgSetting == null) {
11421                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11422                }
11423                if (!pkgSetting.getInstalled(userId)) {
11424                    pkgSetting.setInstalled(true, userId);
11425                    pkgSetting.setHidden(false, userId);
11426                    mSettings.writePackageRestrictionsLPr(userId);
11427                    installed = true;
11428                }
11429            }
11430
11431            if (installed) {
11432                if (pkgSetting.pkg != null) {
11433                    synchronized (mInstallLock) {
11434                        // We don't need to freeze for a brand new install
11435                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11436                    }
11437                }
11438                sendPackageAddedForUser(packageName, pkgSetting, userId);
11439            }
11440        } finally {
11441            Binder.restoreCallingIdentity(callingId);
11442        }
11443
11444        return PackageManager.INSTALL_SUCCEEDED;
11445    }
11446
11447    boolean isUserRestricted(int userId, String restrictionKey) {
11448        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11449        if (restrictions.getBoolean(restrictionKey, false)) {
11450            Log.w(TAG, "User is restricted: " + restrictionKey);
11451            return true;
11452        }
11453        return false;
11454    }
11455
11456    @Override
11457    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11458            int userId) {
11459        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11460        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11461                true /* requireFullPermission */, true /* checkShell */,
11462                "setPackagesSuspended for user " + userId);
11463
11464        if (ArrayUtils.isEmpty(packageNames)) {
11465            return packageNames;
11466        }
11467
11468        // List of package names for whom the suspended state has changed.
11469        List<String> changedPackages = new ArrayList<>(packageNames.length);
11470        // List of package names for whom the suspended state is not set as requested in this
11471        // method.
11472        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11473        for (int i = 0; i < packageNames.length; i++) {
11474            String packageName = packageNames[i];
11475            long callingId = Binder.clearCallingIdentity();
11476            try {
11477                boolean changed = false;
11478                final int appId;
11479                synchronized (mPackages) {
11480                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11481                    if (pkgSetting == null) {
11482                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11483                                + "\". Skipping suspending/un-suspending.");
11484                        unactionedPackages.add(packageName);
11485                        continue;
11486                    }
11487                    appId = pkgSetting.appId;
11488                    if (pkgSetting.getSuspended(userId) != suspended) {
11489                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11490                            unactionedPackages.add(packageName);
11491                            continue;
11492                        }
11493                        pkgSetting.setSuspended(suspended, userId);
11494                        mSettings.writePackageRestrictionsLPr(userId);
11495                        changed = true;
11496                        changedPackages.add(packageName);
11497                    }
11498                }
11499
11500                if (changed && suspended) {
11501                    killApplication(packageName, UserHandle.getUid(userId, appId),
11502                            "suspending package");
11503                }
11504            } finally {
11505                Binder.restoreCallingIdentity(callingId);
11506            }
11507        }
11508
11509        if (!changedPackages.isEmpty()) {
11510            sendPackagesSuspendedForUser(changedPackages.toArray(
11511                    new String[changedPackages.size()]), userId, suspended);
11512        }
11513
11514        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11515    }
11516
11517    @Override
11518    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11519        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11520                true /* requireFullPermission */, false /* checkShell */,
11521                "isPackageSuspendedForUser for user " + userId);
11522        synchronized (mPackages) {
11523            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11524            if (pkgSetting == null) {
11525                throw new IllegalArgumentException("Unknown target package: " + packageName);
11526            }
11527            return pkgSetting.getSuspended(userId);
11528        }
11529    }
11530
11531    /**
11532     * TODO: cache and disallow blocking the active dialer.
11533     *
11534     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11535     */
11536    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11537        if (isPackageDeviceAdmin(packageName, userId)) {
11538            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11539                    + "\": has an active device admin");
11540            return false;
11541        }
11542
11543        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11544        if (packageName.equals(activeLauncherPackageName)) {
11545            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11546                    + "\": contains the active launcher");
11547            return false;
11548        }
11549
11550        if (packageName.equals(mRequiredInstallerPackage)) {
11551            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11552                    + "\": required for package installation");
11553            return false;
11554        }
11555
11556        if (packageName.equals(mRequiredVerifierPackage)) {
11557            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11558                    + "\": required for package verification");
11559            return false;
11560        }
11561
11562        final PackageParser.Package pkg = mPackages.get(packageName);
11563        if (pkg != null && isPrivilegedApp(pkg)) {
11564            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11565                    + "\": is a privileged app");
11566            return false;
11567        }
11568
11569        return true;
11570    }
11571
11572    private String getActiveLauncherPackageName(int userId) {
11573        Intent intent = new Intent(Intent.ACTION_MAIN);
11574        intent.addCategory(Intent.CATEGORY_HOME);
11575        ResolveInfo resolveInfo = resolveIntent(
11576                intent,
11577                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11578                PackageManager.MATCH_DEFAULT_ONLY,
11579                userId);
11580
11581        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11582    }
11583
11584    @Override
11585    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11586        mContext.enforceCallingOrSelfPermission(
11587                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11588                "Only package verification agents can verify applications");
11589
11590        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11591        final PackageVerificationResponse response = new PackageVerificationResponse(
11592                verificationCode, Binder.getCallingUid());
11593        msg.arg1 = id;
11594        msg.obj = response;
11595        mHandler.sendMessage(msg);
11596    }
11597
11598    @Override
11599    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11600            long millisecondsToDelay) {
11601        mContext.enforceCallingOrSelfPermission(
11602                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11603                "Only package verification agents can extend verification timeouts");
11604
11605        final PackageVerificationState state = mPendingVerification.get(id);
11606        final PackageVerificationResponse response = new PackageVerificationResponse(
11607                verificationCodeAtTimeout, Binder.getCallingUid());
11608
11609        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11610            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11611        }
11612        if (millisecondsToDelay < 0) {
11613            millisecondsToDelay = 0;
11614        }
11615        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11616                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11617            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11618        }
11619
11620        if ((state != null) && !state.timeoutExtended()) {
11621            state.extendTimeout();
11622
11623            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11624            msg.arg1 = id;
11625            msg.obj = response;
11626            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11627        }
11628    }
11629
11630    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11631            int verificationCode, UserHandle user) {
11632        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11633        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11634        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11635        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11636        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11637
11638        mContext.sendBroadcastAsUser(intent, user,
11639                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11640    }
11641
11642    private ComponentName matchComponentForVerifier(String packageName,
11643            List<ResolveInfo> receivers) {
11644        ActivityInfo targetReceiver = null;
11645
11646        final int NR = receivers.size();
11647        for (int i = 0; i < NR; i++) {
11648            final ResolveInfo info = receivers.get(i);
11649            if (info.activityInfo == null) {
11650                continue;
11651            }
11652
11653            if (packageName.equals(info.activityInfo.packageName)) {
11654                targetReceiver = info.activityInfo;
11655                break;
11656            }
11657        }
11658
11659        if (targetReceiver == null) {
11660            return null;
11661        }
11662
11663        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11664    }
11665
11666    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11667            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11668        if (pkgInfo.verifiers.length == 0) {
11669            return null;
11670        }
11671
11672        final int N = pkgInfo.verifiers.length;
11673        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11674        for (int i = 0; i < N; i++) {
11675            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11676
11677            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11678                    receivers);
11679            if (comp == null) {
11680                continue;
11681            }
11682
11683            final int verifierUid = getUidForVerifier(verifierInfo);
11684            if (verifierUid == -1) {
11685                continue;
11686            }
11687
11688            if (DEBUG_VERIFY) {
11689                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11690                        + " with the correct signature");
11691            }
11692            sufficientVerifiers.add(comp);
11693            verificationState.addSufficientVerifier(verifierUid);
11694        }
11695
11696        return sufficientVerifiers;
11697    }
11698
11699    private int getUidForVerifier(VerifierInfo verifierInfo) {
11700        synchronized (mPackages) {
11701            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11702            if (pkg == null) {
11703                return -1;
11704            } else if (pkg.mSignatures.length != 1) {
11705                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11706                        + " has more than one signature; ignoring");
11707                return -1;
11708            }
11709
11710            /*
11711             * If the public key of the package's signature does not match
11712             * our expected public key, then this is a different package and
11713             * we should skip.
11714             */
11715
11716            final byte[] expectedPublicKey;
11717            try {
11718                final Signature verifierSig = pkg.mSignatures[0];
11719                final PublicKey publicKey = verifierSig.getPublicKey();
11720                expectedPublicKey = publicKey.getEncoded();
11721            } catch (CertificateException e) {
11722                return -1;
11723            }
11724
11725            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11726
11727            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11728                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11729                        + " does not have the expected public key; ignoring");
11730                return -1;
11731            }
11732
11733            return pkg.applicationInfo.uid;
11734        }
11735    }
11736
11737    @Override
11738    public void finishPackageInstall(int token, boolean didLaunch) {
11739        enforceSystemOrRoot("Only the system is allowed to finish installs");
11740
11741        if (DEBUG_INSTALL) {
11742            Slog.v(TAG, "BM finishing package install for " + token);
11743        }
11744        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11745
11746        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11747        mHandler.sendMessage(msg);
11748    }
11749
11750    /**
11751     * Get the verification agent timeout.
11752     *
11753     * @return verification timeout in milliseconds
11754     */
11755    private long getVerificationTimeout() {
11756        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11757                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11758                DEFAULT_VERIFICATION_TIMEOUT);
11759    }
11760
11761    /**
11762     * Get the default verification agent response code.
11763     *
11764     * @return default verification response code
11765     */
11766    private int getDefaultVerificationResponse() {
11767        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11768                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11769                DEFAULT_VERIFICATION_RESPONSE);
11770    }
11771
11772    /**
11773     * Check whether or not package verification has been enabled.
11774     *
11775     * @return true if verification should be performed
11776     */
11777    private boolean isVerificationEnabled(int userId, int installFlags) {
11778        if (!DEFAULT_VERIFY_ENABLE) {
11779            return false;
11780        }
11781        // Ephemeral apps don't get the full verification treatment
11782        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11783            if (DEBUG_EPHEMERAL) {
11784                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11785            }
11786            return false;
11787        }
11788
11789        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11790
11791        // Check if installing from ADB
11792        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11793            // Do not run verification in a test harness environment
11794            if (ActivityManager.isRunningInTestHarness()) {
11795                return false;
11796            }
11797            if (ensureVerifyAppsEnabled) {
11798                return true;
11799            }
11800            // Check if the developer does not want package verification for ADB installs
11801            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11802                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11803                return false;
11804            }
11805        }
11806
11807        if (ensureVerifyAppsEnabled) {
11808            return true;
11809        }
11810
11811        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11812                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11813    }
11814
11815    @Override
11816    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11817            throws RemoteException {
11818        mContext.enforceCallingOrSelfPermission(
11819                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11820                "Only intentfilter verification agents can verify applications");
11821
11822        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11823        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11824                Binder.getCallingUid(), verificationCode, failedDomains);
11825        msg.arg1 = id;
11826        msg.obj = response;
11827        mHandler.sendMessage(msg);
11828    }
11829
11830    @Override
11831    public int getIntentVerificationStatus(String packageName, int userId) {
11832        synchronized (mPackages) {
11833            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11834        }
11835    }
11836
11837    @Override
11838    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11839        mContext.enforceCallingOrSelfPermission(
11840                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11841
11842        boolean result = false;
11843        synchronized (mPackages) {
11844            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11845        }
11846        if (result) {
11847            scheduleWritePackageRestrictionsLocked(userId);
11848        }
11849        return result;
11850    }
11851
11852    @Override
11853    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11854            String packageName) {
11855        synchronized (mPackages) {
11856            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11857        }
11858    }
11859
11860    @Override
11861    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11862        if (TextUtils.isEmpty(packageName)) {
11863            return ParceledListSlice.emptyList();
11864        }
11865        synchronized (mPackages) {
11866            PackageParser.Package pkg = mPackages.get(packageName);
11867            if (pkg == null || pkg.activities == null) {
11868                return ParceledListSlice.emptyList();
11869            }
11870            final int count = pkg.activities.size();
11871            ArrayList<IntentFilter> result = new ArrayList<>();
11872            for (int n=0; n<count; n++) {
11873                PackageParser.Activity activity = pkg.activities.get(n);
11874                if (activity.intents != null && activity.intents.size() > 0) {
11875                    result.addAll(activity.intents);
11876                }
11877            }
11878            return new ParceledListSlice<>(result);
11879        }
11880    }
11881
11882    @Override
11883    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11884        mContext.enforceCallingOrSelfPermission(
11885                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11886
11887        synchronized (mPackages) {
11888            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11889            if (packageName != null) {
11890                result |= updateIntentVerificationStatus(packageName,
11891                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11892                        userId);
11893                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11894                        packageName, userId);
11895            }
11896            return result;
11897        }
11898    }
11899
11900    @Override
11901    public String getDefaultBrowserPackageName(int userId) {
11902        synchronized (mPackages) {
11903            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11904        }
11905    }
11906
11907    /**
11908     * Get the "allow unknown sources" setting.
11909     *
11910     * @return the current "allow unknown sources" setting
11911     */
11912    private int getUnknownSourcesSettings() {
11913        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11914                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11915                -1);
11916    }
11917
11918    @Override
11919    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11920        final int uid = Binder.getCallingUid();
11921        // writer
11922        synchronized (mPackages) {
11923            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11924            if (targetPackageSetting == null) {
11925                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11926            }
11927
11928            PackageSetting installerPackageSetting;
11929            if (installerPackageName != null) {
11930                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11931                if (installerPackageSetting == null) {
11932                    throw new IllegalArgumentException("Unknown installer package: "
11933                            + installerPackageName);
11934                }
11935            } else {
11936                installerPackageSetting = null;
11937            }
11938
11939            Signature[] callerSignature;
11940            Object obj = mSettings.getUserIdLPr(uid);
11941            if (obj != null) {
11942                if (obj instanceof SharedUserSetting) {
11943                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11944                } else if (obj instanceof PackageSetting) {
11945                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11946                } else {
11947                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11948                }
11949            } else {
11950                throw new SecurityException("Unknown calling UID: " + uid);
11951            }
11952
11953            // Verify: can't set installerPackageName to a package that is
11954            // not signed with the same cert as the caller.
11955            if (installerPackageSetting != null) {
11956                if (compareSignatures(callerSignature,
11957                        installerPackageSetting.signatures.mSignatures)
11958                        != PackageManager.SIGNATURE_MATCH) {
11959                    throw new SecurityException(
11960                            "Caller does not have same cert as new installer package "
11961                            + installerPackageName);
11962                }
11963            }
11964
11965            // Verify: if target already has an installer package, it must
11966            // be signed with the same cert as the caller.
11967            if (targetPackageSetting.installerPackageName != null) {
11968                PackageSetting setting = mSettings.mPackages.get(
11969                        targetPackageSetting.installerPackageName);
11970                // If the currently set package isn't valid, then it's always
11971                // okay to change it.
11972                if (setting != null) {
11973                    if (compareSignatures(callerSignature,
11974                            setting.signatures.mSignatures)
11975                            != PackageManager.SIGNATURE_MATCH) {
11976                        throw new SecurityException(
11977                                "Caller does not have same cert as old installer package "
11978                                + targetPackageSetting.installerPackageName);
11979                    }
11980                }
11981            }
11982
11983            // Okay!
11984            targetPackageSetting.installerPackageName = installerPackageName;
11985            if (installerPackageName != null) {
11986                mSettings.mInstallerPackages.add(installerPackageName);
11987            }
11988            scheduleWriteSettingsLocked();
11989        }
11990    }
11991
11992    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11993        // Queue up an async operation since the package installation may take a little while.
11994        mHandler.post(new Runnable() {
11995            public void run() {
11996                mHandler.removeCallbacks(this);
11997                 // Result object to be returned
11998                PackageInstalledInfo res = new PackageInstalledInfo();
11999                res.setReturnCode(currentStatus);
12000                res.uid = -1;
12001                res.pkg = null;
12002                res.removedInfo = null;
12003                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12004                    args.doPreInstall(res.returnCode);
12005                    synchronized (mInstallLock) {
12006                        installPackageTracedLI(args, res);
12007                    }
12008                    args.doPostInstall(res.returnCode, res.uid);
12009                }
12010
12011                // A restore should be performed at this point if (a) the install
12012                // succeeded, (b) the operation is not an update, and (c) the new
12013                // package has not opted out of backup participation.
12014                final boolean update = res.removedInfo != null
12015                        && res.removedInfo.removedPackage != null;
12016                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12017                boolean doRestore = !update
12018                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12019
12020                // Set up the post-install work request bookkeeping.  This will be used
12021                // and cleaned up by the post-install event handling regardless of whether
12022                // there's a restore pass performed.  Token values are >= 1.
12023                int token;
12024                if (mNextInstallToken < 0) mNextInstallToken = 1;
12025                token = mNextInstallToken++;
12026
12027                PostInstallData data = new PostInstallData(args, res);
12028                mRunningInstalls.put(token, data);
12029                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12030
12031                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12032                    // Pass responsibility to the Backup Manager.  It will perform a
12033                    // restore if appropriate, then pass responsibility back to the
12034                    // Package Manager to run the post-install observer callbacks
12035                    // and broadcasts.
12036                    IBackupManager bm = IBackupManager.Stub.asInterface(
12037                            ServiceManager.getService(Context.BACKUP_SERVICE));
12038                    if (bm != null) {
12039                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12040                                + " to BM for possible restore");
12041                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12042                        try {
12043                            // TODO: http://b/22388012
12044                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12045                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12046                            } else {
12047                                doRestore = false;
12048                            }
12049                        } catch (RemoteException e) {
12050                            // can't happen; the backup manager is local
12051                        } catch (Exception e) {
12052                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12053                            doRestore = false;
12054                        }
12055                    } else {
12056                        Slog.e(TAG, "Backup Manager not found!");
12057                        doRestore = false;
12058                    }
12059                }
12060
12061                if (!doRestore) {
12062                    // No restore possible, or the Backup Manager was mysteriously not
12063                    // available -- just fire the post-install work request directly.
12064                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12065
12066                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12067
12068                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12069                    mHandler.sendMessage(msg);
12070                }
12071            }
12072        });
12073    }
12074
12075    /**
12076     * Callback from PackageSettings whenever an app is first transitioned out of the
12077     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12078     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12079     * here whether the app is the target of an ongoing install, and only send the
12080     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12081     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12082     * handling.
12083     */
12084    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12085        // Serialize this with the rest of the install-process message chain.  In the
12086        // restore-at-install case, this Runnable will necessarily run before the
12087        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12088        // are coherent.  In the non-restore case, the app has already completed install
12089        // and been launched through some other means, so it is not in a problematic
12090        // state for observers to see the FIRST_LAUNCH signal.
12091        mHandler.post(new Runnable() {
12092            @Override
12093            public void run() {
12094                for (int i = 0; i < mRunningInstalls.size(); i++) {
12095                    final PostInstallData data = mRunningInstalls.valueAt(i);
12096                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12097                        // right package; but is it for the right user?
12098                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12099                            if (userId == data.res.newUsers[uIndex]) {
12100                                if (DEBUG_BACKUP) {
12101                                    Slog.i(TAG, "Package " + pkgName
12102                                            + " being restored so deferring FIRST_LAUNCH");
12103                                }
12104                                return;
12105                            }
12106                        }
12107                    }
12108                }
12109                // didn't find it, so not being restored
12110                if (DEBUG_BACKUP) {
12111                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12112                }
12113                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12114            }
12115        });
12116    }
12117
12118    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12119        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12120                installerPkg, null, userIds);
12121    }
12122
12123    private abstract class HandlerParams {
12124        private static final int MAX_RETRIES = 4;
12125
12126        /**
12127         * Number of times startCopy() has been attempted and had a non-fatal
12128         * error.
12129         */
12130        private int mRetries = 0;
12131
12132        /** User handle for the user requesting the information or installation. */
12133        private final UserHandle mUser;
12134        String traceMethod;
12135        int traceCookie;
12136
12137        HandlerParams(UserHandle user) {
12138            mUser = user;
12139        }
12140
12141        UserHandle getUser() {
12142            return mUser;
12143        }
12144
12145        HandlerParams setTraceMethod(String traceMethod) {
12146            this.traceMethod = traceMethod;
12147            return this;
12148        }
12149
12150        HandlerParams setTraceCookie(int traceCookie) {
12151            this.traceCookie = traceCookie;
12152            return this;
12153        }
12154
12155        final boolean startCopy() {
12156            boolean res;
12157            try {
12158                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12159
12160                if (++mRetries > MAX_RETRIES) {
12161                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12162                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12163                    handleServiceError();
12164                    return false;
12165                } else {
12166                    handleStartCopy();
12167                    res = true;
12168                }
12169            } catch (RemoteException e) {
12170                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12171                mHandler.sendEmptyMessage(MCS_RECONNECT);
12172                res = false;
12173            }
12174            handleReturnCode();
12175            return res;
12176        }
12177
12178        final void serviceError() {
12179            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12180            handleServiceError();
12181            handleReturnCode();
12182        }
12183
12184        abstract void handleStartCopy() throws RemoteException;
12185        abstract void handleServiceError();
12186        abstract void handleReturnCode();
12187    }
12188
12189    class MeasureParams extends HandlerParams {
12190        private final PackageStats mStats;
12191        private boolean mSuccess;
12192
12193        private final IPackageStatsObserver mObserver;
12194
12195        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12196            super(new UserHandle(stats.userHandle));
12197            mObserver = observer;
12198            mStats = stats;
12199        }
12200
12201        @Override
12202        public String toString() {
12203            return "MeasureParams{"
12204                + Integer.toHexString(System.identityHashCode(this))
12205                + " " + mStats.packageName + "}";
12206        }
12207
12208        @Override
12209        void handleStartCopy() throws RemoteException {
12210            synchronized (mInstallLock) {
12211                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12212            }
12213
12214            if (mSuccess) {
12215                final boolean mounted;
12216                if (Environment.isExternalStorageEmulated()) {
12217                    mounted = true;
12218                } else {
12219                    final String status = Environment.getExternalStorageState();
12220                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12221                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12222                }
12223
12224                if (mounted) {
12225                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12226
12227                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12228                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12229
12230                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12231                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12232
12233                    // Always subtract cache size, since it's a subdirectory
12234                    mStats.externalDataSize -= mStats.externalCacheSize;
12235
12236                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12237                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12238
12239                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12240                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12241                }
12242            }
12243        }
12244
12245        @Override
12246        void handleReturnCode() {
12247            if (mObserver != null) {
12248                try {
12249                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12250                } catch (RemoteException e) {
12251                    Slog.i(TAG, "Observer no longer exists.");
12252                }
12253            }
12254        }
12255
12256        @Override
12257        void handleServiceError() {
12258            Slog.e(TAG, "Could not measure application " + mStats.packageName
12259                            + " external storage");
12260        }
12261    }
12262
12263    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12264            throws RemoteException {
12265        long result = 0;
12266        for (File path : paths) {
12267            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12268        }
12269        return result;
12270    }
12271
12272    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12273        for (File path : paths) {
12274            try {
12275                mcs.clearDirectory(path.getAbsolutePath());
12276            } catch (RemoteException e) {
12277            }
12278        }
12279    }
12280
12281    static class OriginInfo {
12282        /**
12283         * Location where install is coming from, before it has been
12284         * copied/renamed into place. This could be a single monolithic APK
12285         * file, or a cluster directory. This location may be untrusted.
12286         */
12287        final File file;
12288        final String cid;
12289
12290        /**
12291         * Flag indicating that {@link #file} or {@link #cid} has already been
12292         * staged, meaning downstream users don't need to defensively copy the
12293         * contents.
12294         */
12295        final boolean staged;
12296
12297        /**
12298         * Flag indicating that {@link #file} or {@link #cid} is an already
12299         * installed app that is being moved.
12300         */
12301        final boolean existing;
12302
12303        final String resolvedPath;
12304        final File resolvedFile;
12305
12306        static OriginInfo fromNothing() {
12307            return new OriginInfo(null, null, false, false);
12308        }
12309
12310        static OriginInfo fromUntrustedFile(File file) {
12311            return new OriginInfo(file, null, false, false);
12312        }
12313
12314        static OriginInfo fromExistingFile(File file) {
12315            return new OriginInfo(file, null, false, true);
12316        }
12317
12318        static OriginInfo fromStagedFile(File file) {
12319            return new OriginInfo(file, null, true, false);
12320        }
12321
12322        static OriginInfo fromStagedContainer(String cid) {
12323            return new OriginInfo(null, cid, true, false);
12324        }
12325
12326        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12327            this.file = file;
12328            this.cid = cid;
12329            this.staged = staged;
12330            this.existing = existing;
12331
12332            if (cid != null) {
12333                resolvedPath = PackageHelper.getSdDir(cid);
12334                resolvedFile = new File(resolvedPath);
12335            } else if (file != null) {
12336                resolvedPath = file.getAbsolutePath();
12337                resolvedFile = file;
12338            } else {
12339                resolvedPath = null;
12340                resolvedFile = null;
12341            }
12342        }
12343    }
12344
12345    static class MoveInfo {
12346        final int moveId;
12347        final String fromUuid;
12348        final String toUuid;
12349        final String packageName;
12350        final String dataAppName;
12351        final int appId;
12352        final String seinfo;
12353        final int targetSdkVersion;
12354
12355        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12356                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12357            this.moveId = moveId;
12358            this.fromUuid = fromUuid;
12359            this.toUuid = toUuid;
12360            this.packageName = packageName;
12361            this.dataAppName = dataAppName;
12362            this.appId = appId;
12363            this.seinfo = seinfo;
12364            this.targetSdkVersion = targetSdkVersion;
12365        }
12366    }
12367
12368    static class VerificationInfo {
12369        /** A constant used to indicate that a uid value is not present. */
12370        public static final int NO_UID = -1;
12371
12372        /** URI referencing where the package was downloaded from. */
12373        final Uri originatingUri;
12374
12375        /** HTTP referrer URI associated with the originatingURI. */
12376        final Uri referrer;
12377
12378        /** UID of the application that the install request originated from. */
12379        final int originatingUid;
12380
12381        /** UID of application requesting the install */
12382        final int installerUid;
12383
12384        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12385            this.originatingUri = originatingUri;
12386            this.referrer = referrer;
12387            this.originatingUid = originatingUid;
12388            this.installerUid = installerUid;
12389        }
12390    }
12391
12392    class InstallParams extends HandlerParams {
12393        final OriginInfo origin;
12394        final MoveInfo move;
12395        final IPackageInstallObserver2 observer;
12396        int installFlags;
12397        final String installerPackageName;
12398        final String volumeUuid;
12399        private InstallArgs mArgs;
12400        private int mRet;
12401        final String packageAbiOverride;
12402        final String[] grantedRuntimePermissions;
12403        final VerificationInfo verificationInfo;
12404        final Certificate[][] certificates;
12405
12406        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12407                int installFlags, String installerPackageName, String volumeUuid,
12408                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12409                String[] grantedPermissions, Certificate[][] certificates) {
12410            super(user);
12411            this.origin = origin;
12412            this.move = move;
12413            this.observer = observer;
12414            this.installFlags = installFlags;
12415            this.installerPackageName = installerPackageName;
12416            this.volumeUuid = volumeUuid;
12417            this.verificationInfo = verificationInfo;
12418            this.packageAbiOverride = packageAbiOverride;
12419            this.grantedRuntimePermissions = grantedPermissions;
12420            this.certificates = certificates;
12421        }
12422
12423        @Override
12424        public String toString() {
12425            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12426                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12427        }
12428
12429        private int installLocationPolicy(PackageInfoLite pkgLite) {
12430            String packageName = pkgLite.packageName;
12431            int installLocation = pkgLite.installLocation;
12432            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12433            // reader
12434            synchronized (mPackages) {
12435                // Currently installed package which the new package is attempting to replace or
12436                // null if no such package is installed.
12437                PackageParser.Package installedPkg = mPackages.get(packageName);
12438                // Package which currently owns the data which the new package will own if installed.
12439                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12440                // will be null whereas dataOwnerPkg will contain information about the package
12441                // which was uninstalled while keeping its data.
12442                PackageParser.Package dataOwnerPkg = installedPkg;
12443                if (dataOwnerPkg  == null) {
12444                    PackageSetting ps = mSettings.mPackages.get(packageName);
12445                    if (ps != null) {
12446                        dataOwnerPkg = ps.pkg;
12447                    }
12448                }
12449
12450                if (dataOwnerPkg != null) {
12451                    // If installed, the package will get access to data left on the device by its
12452                    // predecessor. As a security measure, this is permited only if this is not a
12453                    // version downgrade or if the predecessor package is marked as debuggable and
12454                    // a downgrade is explicitly requested.
12455                    //
12456                    // On debuggable platform builds, downgrades are permitted even for
12457                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12458                    // not offer security guarantees and thus it's OK to disable some security
12459                    // mechanisms to make debugging/testing easier on those builds. However, even on
12460                    // debuggable builds downgrades of packages are permitted only if requested via
12461                    // installFlags. This is because we aim to keep the behavior of debuggable
12462                    // platform builds as close as possible to the behavior of non-debuggable
12463                    // platform builds.
12464                    final boolean downgradeRequested =
12465                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12466                    final boolean packageDebuggable =
12467                                (dataOwnerPkg.applicationInfo.flags
12468                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12469                    final boolean downgradePermitted =
12470                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12471                    if (!downgradePermitted) {
12472                        try {
12473                            checkDowngrade(dataOwnerPkg, pkgLite);
12474                        } catch (PackageManagerException e) {
12475                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12476                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12477                        }
12478                    }
12479                }
12480
12481                if (installedPkg != null) {
12482                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12483                        // Check for updated system application.
12484                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12485                            if (onSd) {
12486                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12487                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12488                            }
12489                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12490                        } else {
12491                            if (onSd) {
12492                                // Install flag overrides everything.
12493                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12494                            }
12495                            // If current upgrade specifies particular preference
12496                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12497                                // Application explicitly specified internal.
12498                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12499                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12500                                // App explictly prefers external. Let policy decide
12501                            } else {
12502                                // Prefer previous location
12503                                if (isExternal(installedPkg)) {
12504                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12505                                }
12506                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12507                            }
12508                        }
12509                    } else {
12510                        // Invalid install. Return error code
12511                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12512                    }
12513                }
12514            }
12515            // All the special cases have been taken care of.
12516            // Return result based on recommended install location.
12517            if (onSd) {
12518                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12519            }
12520            return pkgLite.recommendedInstallLocation;
12521        }
12522
12523        /*
12524         * Invoke remote method to get package information and install
12525         * location values. Override install location based on default
12526         * policy if needed and then create install arguments based
12527         * on the install location.
12528         */
12529        public void handleStartCopy() throws RemoteException {
12530            int ret = PackageManager.INSTALL_SUCCEEDED;
12531
12532            // If we're already staged, we've firmly committed to an install location
12533            if (origin.staged) {
12534                if (origin.file != null) {
12535                    installFlags |= PackageManager.INSTALL_INTERNAL;
12536                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12537                } else if (origin.cid != null) {
12538                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12539                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12540                } else {
12541                    throw new IllegalStateException("Invalid stage location");
12542                }
12543            }
12544
12545            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12546            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12547            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12548            PackageInfoLite pkgLite = null;
12549
12550            if (onInt && onSd) {
12551                // Check if both bits are set.
12552                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12553                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12554            } else if (onSd && ephemeral) {
12555                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12556                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12557            } else {
12558                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12559                        packageAbiOverride);
12560
12561                if (DEBUG_EPHEMERAL && ephemeral) {
12562                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12563                }
12564
12565                /*
12566                 * If we have too little free space, try to free cache
12567                 * before giving up.
12568                 */
12569                if (!origin.staged && pkgLite.recommendedInstallLocation
12570                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12571                    // TODO: focus freeing disk space on the target device
12572                    final StorageManager storage = StorageManager.from(mContext);
12573                    final long lowThreshold = storage.getStorageLowBytes(
12574                            Environment.getDataDirectory());
12575
12576                    final long sizeBytes = mContainerService.calculateInstalledSize(
12577                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12578
12579                    try {
12580                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12581                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12582                                installFlags, packageAbiOverride);
12583                    } catch (InstallerException e) {
12584                        Slog.w(TAG, "Failed to free cache", e);
12585                    }
12586
12587                    /*
12588                     * The cache free must have deleted the file we
12589                     * downloaded to install.
12590                     *
12591                     * TODO: fix the "freeCache" call to not delete
12592                     *       the file we care about.
12593                     */
12594                    if (pkgLite.recommendedInstallLocation
12595                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12596                        pkgLite.recommendedInstallLocation
12597                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12598                    }
12599                }
12600            }
12601
12602            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12603                int loc = pkgLite.recommendedInstallLocation;
12604                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12605                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12606                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12607                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12608                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12609                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12610                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12611                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12612                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12613                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12614                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12615                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12616                } else {
12617                    // Override with defaults if needed.
12618                    loc = installLocationPolicy(pkgLite);
12619                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12620                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12621                    } else if (!onSd && !onInt) {
12622                        // Override install location with flags
12623                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12624                            // Set the flag to install on external media.
12625                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12626                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12627                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12628                            if (DEBUG_EPHEMERAL) {
12629                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12630                            }
12631                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12632                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12633                                    |PackageManager.INSTALL_INTERNAL);
12634                        } else {
12635                            // Make sure the flag for installing on external
12636                            // media is unset
12637                            installFlags |= PackageManager.INSTALL_INTERNAL;
12638                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12639                        }
12640                    }
12641                }
12642            }
12643
12644            final InstallArgs args = createInstallArgs(this);
12645            mArgs = args;
12646
12647            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12648                // TODO: http://b/22976637
12649                // Apps installed for "all" users use the device owner to verify the app
12650                UserHandle verifierUser = getUser();
12651                if (verifierUser == UserHandle.ALL) {
12652                    verifierUser = UserHandle.SYSTEM;
12653                }
12654
12655                /*
12656                 * Determine if we have any installed package verifiers. If we
12657                 * do, then we'll defer to them to verify the packages.
12658                 */
12659                final int requiredUid = mRequiredVerifierPackage == null ? -1
12660                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12661                                verifierUser.getIdentifier());
12662                if (!origin.existing && requiredUid != -1
12663                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12664                    final Intent verification = new Intent(
12665                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12666                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12667                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12668                            PACKAGE_MIME_TYPE);
12669                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12670
12671                    // Query all live verifiers based on current user state
12672                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12673                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12674
12675                    if (DEBUG_VERIFY) {
12676                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12677                                + verification.toString() + " with " + pkgLite.verifiers.length
12678                                + " optional verifiers");
12679                    }
12680
12681                    final int verificationId = mPendingVerificationToken++;
12682
12683                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12684
12685                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12686                            installerPackageName);
12687
12688                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12689                            installFlags);
12690
12691                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12692                            pkgLite.packageName);
12693
12694                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12695                            pkgLite.versionCode);
12696
12697                    if (verificationInfo != null) {
12698                        if (verificationInfo.originatingUri != null) {
12699                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12700                                    verificationInfo.originatingUri);
12701                        }
12702                        if (verificationInfo.referrer != null) {
12703                            verification.putExtra(Intent.EXTRA_REFERRER,
12704                                    verificationInfo.referrer);
12705                        }
12706                        if (verificationInfo.originatingUid >= 0) {
12707                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12708                                    verificationInfo.originatingUid);
12709                        }
12710                        if (verificationInfo.installerUid >= 0) {
12711                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12712                                    verificationInfo.installerUid);
12713                        }
12714                    }
12715
12716                    final PackageVerificationState verificationState = new PackageVerificationState(
12717                            requiredUid, args);
12718
12719                    mPendingVerification.append(verificationId, verificationState);
12720
12721                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12722                            receivers, verificationState);
12723
12724                    /*
12725                     * If any sufficient verifiers were listed in the package
12726                     * manifest, attempt to ask them.
12727                     */
12728                    if (sufficientVerifiers != null) {
12729                        final int N = sufficientVerifiers.size();
12730                        if (N == 0) {
12731                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12732                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12733                        } else {
12734                            for (int i = 0; i < N; i++) {
12735                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12736
12737                                final Intent sufficientIntent = new Intent(verification);
12738                                sufficientIntent.setComponent(verifierComponent);
12739                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12740                            }
12741                        }
12742                    }
12743
12744                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12745                            mRequiredVerifierPackage, receivers);
12746                    if (ret == PackageManager.INSTALL_SUCCEEDED
12747                            && mRequiredVerifierPackage != null) {
12748                        Trace.asyncTraceBegin(
12749                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12750                        /*
12751                         * Send the intent to the required verification agent,
12752                         * but only start the verification timeout after the
12753                         * target BroadcastReceivers have run.
12754                         */
12755                        verification.setComponent(requiredVerifierComponent);
12756                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12757                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12758                                new BroadcastReceiver() {
12759                                    @Override
12760                                    public void onReceive(Context context, Intent intent) {
12761                                        final Message msg = mHandler
12762                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12763                                        msg.arg1 = verificationId;
12764                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12765                                    }
12766                                }, null, 0, null, null);
12767
12768                        /*
12769                         * We don't want the copy to proceed until verification
12770                         * succeeds, so null out this field.
12771                         */
12772                        mArgs = null;
12773                    }
12774                } else {
12775                    /*
12776                     * No package verification is enabled, so immediately start
12777                     * the remote call to initiate copy using temporary file.
12778                     */
12779                    ret = args.copyApk(mContainerService, true);
12780                }
12781            }
12782
12783            mRet = ret;
12784        }
12785
12786        @Override
12787        void handleReturnCode() {
12788            // If mArgs is null, then MCS couldn't be reached. When it
12789            // reconnects, it will try again to install. At that point, this
12790            // will succeed.
12791            if (mArgs != null) {
12792                processPendingInstall(mArgs, mRet);
12793            }
12794        }
12795
12796        @Override
12797        void handleServiceError() {
12798            mArgs = createInstallArgs(this);
12799            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12800        }
12801
12802        public boolean isForwardLocked() {
12803            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12804        }
12805    }
12806
12807    /**
12808     * Used during creation of InstallArgs
12809     *
12810     * @param installFlags package installation flags
12811     * @return true if should be installed on external storage
12812     */
12813    private static boolean installOnExternalAsec(int installFlags) {
12814        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12815            return false;
12816        }
12817        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12818            return true;
12819        }
12820        return false;
12821    }
12822
12823    /**
12824     * Used during creation of InstallArgs
12825     *
12826     * @param installFlags package installation flags
12827     * @return true if should be installed as forward locked
12828     */
12829    private static boolean installForwardLocked(int installFlags) {
12830        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12831    }
12832
12833    private InstallArgs createInstallArgs(InstallParams params) {
12834        if (params.move != null) {
12835            return new MoveInstallArgs(params);
12836        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12837            return new AsecInstallArgs(params);
12838        } else {
12839            return new FileInstallArgs(params);
12840        }
12841    }
12842
12843    /**
12844     * Create args that describe an existing installed package. Typically used
12845     * when cleaning up old installs, or used as a move source.
12846     */
12847    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12848            String resourcePath, String[] instructionSets) {
12849        final boolean isInAsec;
12850        if (installOnExternalAsec(installFlags)) {
12851            /* Apps on SD card are always in ASEC containers. */
12852            isInAsec = true;
12853        } else if (installForwardLocked(installFlags)
12854                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12855            /*
12856             * Forward-locked apps are only in ASEC containers if they're the
12857             * new style
12858             */
12859            isInAsec = true;
12860        } else {
12861            isInAsec = false;
12862        }
12863
12864        if (isInAsec) {
12865            return new AsecInstallArgs(codePath, instructionSets,
12866                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12867        } else {
12868            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12869        }
12870    }
12871
12872    static abstract class InstallArgs {
12873        /** @see InstallParams#origin */
12874        final OriginInfo origin;
12875        /** @see InstallParams#move */
12876        final MoveInfo move;
12877
12878        final IPackageInstallObserver2 observer;
12879        // Always refers to PackageManager flags only
12880        final int installFlags;
12881        final String installerPackageName;
12882        final String volumeUuid;
12883        final UserHandle user;
12884        final String abiOverride;
12885        final String[] installGrantPermissions;
12886        /** If non-null, drop an async trace when the install completes */
12887        final String traceMethod;
12888        final int traceCookie;
12889        final Certificate[][] certificates;
12890
12891        // The list of instruction sets supported by this app. This is currently
12892        // only used during the rmdex() phase to clean up resources. We can get rid of this
12893        // if we move dex files under the common app path.
12894        /* nullable */ String[] instructionSets;
12895
12896        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12897                int installFlags, String installerPackageName, String volumeUuid,
12898                UserHandle user, String[] instructionSets,
12899                String abiOverride, String[] installGrantPermissions,
12900                String traceMethod, int traceCookie, Certificate[][] certificates) {
12901            this.origin = origin;
12902            this.move = move;
12903            this.installFlags = installFlags;
12904            this.observer = observer;
12905            this.installerPackageName = installerPackageName;
12906            this.volumeUuid = volumeUuid;
12907            this.user = user;
12908            this.instructionSets = instructionSets;
12909            this.abiOverride = abiOverride;
12910            this.installGrantPermissions = installGrantPermissions;
12911            this.traceMethod = traceMethod;
12912            this.traceCookie = traceCookie;
12913            this.certificates = certificates;
12914        }
12915
12916        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12917        abstract int doPreInstall(int status);
12918
12919        /**
12920         * Rename package into final resting place. All paths on the given
12921         * scanned package should be updated to reflect the rename.
12922         */
12923        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12924        abstract int doPostInstall(int status, int uid);
12925
12926        /** @see PackageSettingBase#codePathString */
12927        abstract String getCodePath();
12928        /** @see PackageSettingBase#resourcePathString */
12929        abstract String getResourcePath();
12930
12931        // Need installer lock especially for dex file removal.
12932        abstract void cleanUpResourcesLI();
12933        abstract boolean doPostDeleteLI(boolean delete);
12934
12935        /**
12936         * Called before the source arguments are copied. This is used mostly
12937         * for MoveParams when it needs to read the source file to put it in the
12938         * destination.
12939         */
12940        int doPreCopy() {
12941            return PackageManager.INSTALL_SUCCEEDED;
12942        }
12943
12944        /**
12945         * Called after the source arguments are copied. This is used mostly for
12946         * MoveParams when it needs to read the source file to put it in the
12947         * destination.
12948         */
12949        int doPostCopy(int uid) {
12950            return PackageManager.INSTALL_SUCCEEDED;
12951        }
12952
12953        protected boolean isFwdLocked() {
12954            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12955        }
12956
12957        protected boolean isExternalAsec() {
12958            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12959        }
12960
12961        protected boolean isEphemeral() {
12962            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12963        }
12964
12965        UserHandle getUser() {
12966            return user;
12967        }
12968    }
12969
12970    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12971        if (!allCodePaths.isEmpty()) {
12972            if (instructionSets == null) {
12973                throw new IllegalStateException("instructionSet == null");
12974            }
12975            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12976            for (String codePath : allCodePaths) {
12977                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12978                    try {
12979                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12980                    } catch (InstallerException ignored) {
12981                    }
12982                }
12983            }
12984        }
12985    }
12986
12987    /**
12988     * Logic to handle installation of non-ASEC applications, including copying
12989     * and renaming logic.
12990     */
12991    class FileInstallArgs extends InstallArgs {
12992        private File codeFile;
12993        private File resourceFile;
12994
12995        // Example topology:
12996        // /data/app/com.example/base.apk
12997        // /data/app/com.example/split_foo.apk
12998        // /data/app/com.example/lib/arm/libfoo.so
12999        // /data/app/com.example/lib/arm64/libfoo.so
13000        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13001
13002        /** New install */
13003        FileInstallArgs(InstallParams params) {
13004            super(params.origin, params.move, params.observer, params.installFlags,
13005                    params.installerPackageName, params.volumeUuid,
13006                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13007                    params.grantedRuntimePermissions,
13008                    params.traceMethod, params.traceCookie, params.certificates);
13009            if (isFwdLocked()) {
13010                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13011            }
13012        }
13013
13014        /** Existing install */
13015        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13016            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13017                    null, null, null, 0, null /*certificates*/);
13018            this.codeFile = (codePath != null) ? new File(codePath) : null;
13019            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13020        }
13021
13022        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13023            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13024            try {
13025                return doCopyApk(imcs, temp);
13026            } finally {
13027                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13028            }
13029        }
13030
13031        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13032            if (origin.staged) {
13033                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13034                codeFile = origin.file;
13035                resourceFile = origin.file;
13036                return PackageManager.INSTALL_SUCCEEDED;
13037            }
13038
13039            try {
13040                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13041                final File tempDir =
13042                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13043                codeFile = tempDir;
13044                resourceFile = tempDir;
13045            } catch (IOException e) {
13046                Slog.w(TAG, "Failed to create copy file: " + e);
13047                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13048            }
13049
13050            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13051                @Override
13052                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13053                    if (!FileUtils.isValidExtFilename(name)) {
13054                        throw new IllegalArgumentException("Invalid filename: " + name);
13055                    }
13056                    try {
13057                        final File file = new File(codeFile, name);
13058                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13059                                O_RDWR | O_CREAT, 0644);
13060                        Os.chmod(file.getAbsolutePath(), 0644);
13061                        return new ParcelFileDescriptor(fd);
13062                    } catch (ErrnoException e) {
13063                        throw new RemoteException("Failed to open: " + e.getMessage());
13064                    }
13065                }
13066            };
13067
13068            int ret = PackageManager.INSTALL_SUCCEEDED;
13069            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13070            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13071                Slog.e(TAG, "Failed to copy package");
13072                return ret;
13073            }
13074
13075            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13076            NativeLibraryHelper.Handle handle = null;
13077            try {
13078                handle = NativeLibraryHelper.Handle.create(codeFile);
13079                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13080                        abiOverride);
13081            } catch (IOException e) {
13082                Slog.e(TAG, "Copying native libraries failed", e);
13083                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13084            } finally {
13085                IoUtils.closeQuietly(handle);
13086            }
13087
13088            return ret;
13089        }
13090
13091        int doPreInstall(int status) {
13092            if (status != PackageManager.INSTALL_SUCCEEDED) {
13093                cleanUp();
13094            }
13095            return status;
13096        }
13097
13098        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13099            if (status != PackageManager.INSTALL_SUCCEEDED) {
13100                cleanUp();
13101                return false;
13102            }
13103
13104            final File targetDir = codeFile.getParentFile();
13105            final File beforeCodeFile = codeFile;
13106            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13107
13108            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13109            try {
13110                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13111            } catch (ErrnoException e) {
13112                Slog.w(TAG, "Failed to rename", e);
13113                return false;
13114            }
13115
13116            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13117                Slog.w(TAG, "Failed to restorecon");
13118                return false;
13119            }
13120
13121            // Reflect the rename internally
13122            codeFile = afterCodeFile;
13123            resourceFile = afterCodeFile;
13124
13125            // Reflect the rename in scanned details
13126            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13127            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13128                    afterCodeFile, pkg.baseCodePath));
13129            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13130                    afterCodeFile, pkg.splitCodePaths));
13131
13132            // Reflect the rename in app info
13133            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13134            pkg.setApplicationInfoCodePath(pkg.codePath);
13135            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13136            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13137            pkg.setApplicationInfoResourcePath(pkg.codePath);
13138            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13139            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13140
13141            return true;
13142        }
13143
13144        int doPostInstall(int status, int uid) {
13145            if (status != PackageManager.INSTALL_SUCCEEDED) {
13146                cleanUp();
13147            }
13148            return status;
13149        }
13150
13151        @Override
13152        String getCodePath() {
13153            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13154        }
13155
13156        @Override
13157        String getResourcePath() {
13158            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13159        }
13160
13161        private boolean cleanUp() {
13162            if (codeFile == null || !codeFile.exists()) {
13163                return false;
13164            }
13165
13166            removeCodePathLI(codeFile);
13167
13168            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13169                resourceFile.delete();
13170            }
13171
13172            return true;
13173        }
13174
13175        void cleanUpResourcesLI() {
13176            // Try enumerating all code paths before deleting
13177            List<String> allCodePaths = Collections.EMPTY_LIST;
13178            if (codeFile != null && codeFile.exists()) {
13179                try {
13180                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13181                    allCodePaths = pkg.getAllCodePaths();
13182                } catch (PackageParserException e) {
13183                    // Ignored; we tried our best
13184                }
13185            }
13186
13187            cleanUp();
13188            removeDexFiles(allCodePaths, instructionSets);
13189        }
13190
13191        boolean doPostDeleteLI(boolean delete) {
13192            // XXX err, shouldn't we respect the delete flag?
13193            cleanUpResourcesLI();
13194            return true;
13195        }
13196    }
13197
13198    private boolean isAsecExternal(String cid) {
13199        final String asecPath = PackageHelper.getSdFilesystem(cid);
13200        return !asecPath.startsWith(mAsecInternalPath);
13201    }
13202
13203    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13204            PackageManagerException {
13205        if (copyRet < 0) {
13206            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13207                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13208                throw new PackageManagerException(copyRet, message);
13209            }
13210        }
13211    }
13212
13213    /**
13214     * Extract the MountService "container ID" from the full code path of an
13215     * .apk.
13216     */
13217    static String cidFromCodePath(String fullCodePath) {
13218        int eidx = fullCodePath.lastIndexOf("/");
13219        String subStr1 = fullCodePath.substring(0, eidx);
13220        int sidx = subStr1.lastIndexOf("/");
13221        return subStr1.substring(sidx+1, eidx);
13222    }
13223
13224    /**
13225     * Logic to handle installation of ASEC applications, including copying and
13226     * renaming logic.
13227     */
13228    class AsecInstallArgs extends InstallArgs {
13229        static final String RES_FILE_NAME = "pkg.apk";
13230        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13231
13232        String cid;
13233        String packagePath;
13234        String resourcePath;
13235
13236        /** New install */
13237        AsecInstallArgs(InstallParams params) {
13238            super(params.origin, params.move, params.observer, params.installFlags,
13239                    params.installerPackageName, params.volumeUuid,
13240                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13241                    params.grantedRuntimePermissions,
13242                    params.traceMethod, params.traceCookie, params.certificates);
13243        }
13244
13245        /** Existing install */
13246        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13247                        boolean isExternal, boolean isForwardLocked) {
13248            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13249              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13250                    instructionSets, null, null, null, 0, null /*certificates*/);
13251            // Hackily pretend we're still looking at a full code path
13252            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13253                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13254            }
13255
13256            // Extract cid from fullCodePath
13257            int eidx = fullCodePath.lastIndexOf("/");
13258            String subStr1 = fullCodePath.substring(0, eidx);
13259            int sidx = subStr1.lastIndexOf("/");
13260            cid = subStr1.substring(sidx+1, eidx);
13261            setMountPath(subStr1);
13262        }
13263
13264        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13265            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13266              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13267                    instructionSets, null, null, null, 0, null /*certificates*/);
13268            this.cid = cid;
13269            setMountPath(PackageHelper.getSdDir(cid));
13270        }
13271
13272        void createCopyFile() {
13273            cid = mInstallerService.allocateExternalStageCidLegacy();
13274        }
13275
13276        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13277            if (origin.staged && origin.cid != null) {
13278                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13279                cid = origin.cid;
13280                setMountPath(PackageHelper.getSdDir(cid));
13281                return PackageManager.INSTALL_SUCCEEDED;
13282            }
13283
13284            if (temp) {
13285                createCopyFile();
13286            } else {
13287                /*
13288                 * Pre-emptively destroy the container since it's destroyed if
13289                 * copying fails due to it existing anyway.
13290                 */
13291                PackageHelper.destroySdDir(cid);
13292            }
13293
13294            final String newMountPath = imcs.copyPackageToContainer(
13295                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13296                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13297
13298            if (newMountPath != null) {
13299                setMountPath(newMountPath);
13300                return PackageManager.INSTALL_SUCCEEDED;
13301            } else {
13302                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13303            }
13304        }
13305
13306        @Override
13307        String getCodePath() {
13308            return packagePath;
13309        }
13310
13311        @Override
13312        String getResourcePath() {
13313            return resourcePath;
13314        }
13315
13316        int doPreInstall(int status) {
13317            if (status != PackageManager.INSTALL_SUCCEEDED) {
13318                // Destroy container
13319                PackageHelper.destroySdDir(cid);
13320            } else {
13321                boolean mounted = PackageHelper.isContainerMounted(cid);
13322                if (!mounted) {
13323                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13324                            Process.SYSTEM_UID);
13325                    if (newMountPath != null) {
13326                        setMountPath(newMountPath);
13327                    } else {
13328                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13329                    }
13330                }
13331            }
13332            return status;
13333        }
13334
13335        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13336            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13337            String newMountPath = null;
13338            if (PackageHelper.isContainerMounted(cid)) {
13339                // Unmount the container
13340                if (!PackageHelper.unMountSdDir(cid)) {
13341                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13342                    return false;
13343                }
13344            }
13345            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13346                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13347                        " which might be stale. Will try to clean up.");
13348                // Clean up the stale container and proceed to recreate.
13349                if (!PackageHelper.destroySdDir(newCacheId)) {
13350                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13351                    return false;
13352                }
13353                // Successfully cleaned up stale container. Try to rename again.
13354                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13355                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13356                            + " inspite of cleaning it up.");
13357                    return false;
13358                }
13359            }
13360            if (!PackageHelper.isContainerMounted(newCacheId)) {
13361                Slog.w(TAG, "Mounting container " + newCacheId);
13362                newMountPath = PackageHelper.mountSdDir(newCacheId,
13363                        getEncryptKey(), Process.SYSTEM_UID);
13364            } else {
13365                newMountPath = PackageHelper.getSdDir(newCacheId);
13366            }
13367            if (newMountPath == null) {
13368                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13369                return false;
13370            }
13371            Log.i(TAG, "Succesfully renamed " + cid +
13372                    " to " + newCacheId +
13373                    " at new path: " + newMountPath);
13374            cid = newCacheId;
13375
13376            final File beforeCodeFile = new File(packagePath);
13377            setMountPath(newMountPath);
13378            final File afterCodeFile = new File(packagePath);
13379
13380            // Reflect the rename in scanned details
13381            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13382            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13383                    afterCodeFile, pkg.baseCodePath));
13384            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13385                    afterCodeFile, pkg.splitCodePaths));
13386
13387            // Reflect the rename in app info
13388            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13389            pkg.setApplicationInfoCodePath(pkg.codePath);
13390            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13391            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13392            pkg.setApplicationInfoResourcePath(pkg.codePath);
13393            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13394            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13395
13396            return true;
13397        }
13398
13399        private void setMountPath(String mountPath) {
13400            final File mountFile = new File(mountPath);
13401
13402            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13403            if (monolithicFile.exists()) {
13404                packagePath = monolithicFile.getAbsolutePath();
13405                if (isFwdLocked()) {
13406                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13407                } else {
13408                    resourcePath = packagePath;
13409                }
13410            } else {
13411                packagePath = mountFile.getAbsolutePath();
13412                resourcePath = packagePath;
13413            }
13414        }
13415
13416        int doPostInstall(int status, int uid) {
13417            if (status != PackageManager.INSTALL_SUCCEEDED) {
13418                cleanUp();
13419            } else {
13420                final int groupOwner;
13421                final String protectedFile;
13422                if (isFwdLocked()) {
13423                    groupOwner = UserHandle.getSharedAppGid(uid);
13424                    protectedFile = RES_FILE_NAME;
13425                } else {
13426                    groupOwner = -1;
13427                    protectedFile = null;
13428                }
13429
13430                if (uid < Process.FIRST_APPLICATION_UID
13431                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13432                    Slog.e(TAG, "Failed to finalize " + cid);
13433                    PackageHelper.destroySdDir(cid);
13434                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13435                }
13436
13437                boolean mounted = PackageHelper.isContainerMounted(cid);
13438                if (!mounted) {
13439                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13440                }
13441            }
13442            return status;
13443        }
13444
13445        private void cleanUp() {
13446            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13447
13448            // Destroy secure container
13449            PackageHelper.destroySdDir(cid);
13450        }
13451
13452        private List<String> getAllCodePaths() {
13453            final File codeFile = new File(getCodePath());
13454            if (codeFile != null && codeFile.exists()) {
13455                try {
13456                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13457                    return pkg.getAllCodePaths();
13458                } catch (PackageParserException e) {
13459                    // Ignored; we tried our best
13460                }
13461            }
13462            return Collections.EMPTY_LIST;
13463        }
13464
13465        void cleanUpResourcesLI() {
13466            // Enumerate all code paths before deleting
13467            cleanUpResourcesLI(getAllCodePaths());
13468        }
13469
13470        private void cleanUpResourcesLI(List<String> allCodePaths) {
13471            cleanUp();
13472            removeDexFiles(allCodePaths, instructionSets);
13473        }
13474
13475        String getPackageName() {
13476            return getAsecPackageName(cid);
13477        }
13478
13479        boolean doPostDeleteLI(boolean delete) {
13480            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13481            final List<String> allCodePaths = getAllCodePaths();
13482            boolean mounted = PackageHelper.isContainerMounted(cid);
13483            if (mounted) {
13484                // Unmount first
13485                if (PackageHelper.unMountSdDir(cid)) {
13486                    mounted = false;
13487                }
13488            }
13489            if (!mounted && delete) {
13490                cleanUpResourcesLI(allCodePaths);
13491            }
13492            return !mounted;
13493        }
13494
13495        @Override
13496        int doPreCopy() {
13497            if (isFwdLocked()) {
13498                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13499                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13500                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13501                }
13502            }
13503
13504            return PackageManager.INSTALL_SUCCEEDED;
13505        }
13506
13507        @Override
13508        int doPostCopy(int uid) {
13509            if (isFwdLocked()) {
13510                if (uid < Process.FIRST_APPLICATION_UID
13511                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13512                                RES_FILE_NAME)) {
13513                    Slog.e(TAG, "Failed to finalize " + cid);
13514                    PackageHelper.destroySdDir(cid);
13515                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13516                }
13517            }
13518
13519            return PackageManager.INSTALL_SUCCEEDED;
13520        }
13521    }
13522
13523    /**
13524     * Logic to handle movement of existing installed applications.
13525     */
13526    class MoveInstallArgs extends InstallArgs {
13527        private File codeFile;
13528        private File resourceFile;
13529
13530        /** New install */
13531        MoveInstallArgs(InstallParams params) {
13532            super(params.origin, params.move, params.observer, params.installFlags,
13533                    params.installerPackageName, params.volumeUuid,
13534                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13535                    params.grantedRuntimePermissions,
13536                    params.traceMethod, params.traceCookie, params.certificates);
13537        }
13538
13539        int copyApk(IMediaContainerService imcs, boolean temp) {
13540            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13541                    + move.fromUuid + " to " + move.toUuid);
13542            synchronized (mInstaller) {
13543                try {
13544                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13545                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13546                } catch (InstallerException e) {
13547                    Slog.w(TAG, "Failed to move app", e);
13548                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13549                }
13550            }
13551
13552            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13553            resourceFile = codeFile;
13554            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13555
13556            return PackageManager.INSTALL_SUCCEEDED;
13557        }
13558
13559        int doPreInstall(int status) {
13560            if (status != PackageManager.INSTALL_SUCCEEDED) {
13561                cleanUp(move.toUuid);
13562            }
13563            return status;
13564        }
13565
13566        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13567            if (status != PackageManager.INSTALL_SUCCEEDED) {
13568                cleanUp(move.toUuid);
13569                return false;
13570            }
13571
13572            // Reflect the move in app info
13573            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13574            pkg.setApplicationInfoCodePath(pkg.codePath);
13575            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13576            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13577            pkg.setApplicationInfoResourcePath(pkg.codePath);
13578            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13579            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13580
13581            return true;
13582        }
13583
13584        int doPostInstall(int status, int uid) {
13585            if (status == PackageManager.INSTALL_SUCCEEDED) {
13586                cleanUp(move.fromUuid);
13587            } else {
13588                cleanUp(move.toUuid);
13589            }
13590            return status;
13591        }
13592
13593        @Override
13594        String getCodePath() {
13595            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13596        }
13597
13598        @Override
13599        String getResourcePath() {
13600            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13601        }
13602
13603        private boolean cleanUp(String volumeUuid) {
13604            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13605                    move.dataAppName);
13606            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13607            final int[] userIds = sUserManager.getUserIds();
13608            synchronized (mInstallLock) {
13609                // Clean up both app data and code
13610                // All package moves are frozen until finished
13611                for (int userId : userIds) {
13612                    try {
13613                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13614                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13615                    } catch (InstallerException e) {
13616                        Slog.w(TAG, String.valueOf(e));
13617                    }
13618                }
13619                removeCodePathLI(codeFile);
13620            }
13621            return true;
13622        }
13623
13624        void cleanUpResourcesLI() {
13625            throw new UnsupportedOperationException();
13626        }
13627
13628        boolean doPostDeleteLI(boolean delete) {
13629            throw new UnsupportedOperationException();
13630        }
13631    }
13632
13633    static String getAsecPackageName(String packageCid) {
13634        int idx = packageCid.lastIndexOf("-");
13635        if (idx == -1) {
13636            return packageCid;
13637        }
13638        return packageCid.substring(0, idx);
13639    }
13640
13641    // Utility method used to create code paths based on package name and available index.
13642    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13643        String idxStr = "";
13644        int idx = 1;
13645        // Fall back to default value of idx=1 if prefix is not
13646        // part of oldCodePath
13647        if (oldCodePath != null) {
13648            String subStr = oldCodePath;
13649            // Drop the suffix right away
13650            if (suffix != null && subStr.endsWith(suffix)) {
13651                subStr = subStr.substring(0, subStr.length() - suffix.length());
13652            }
13653            // If oldCodePath already contains prefix find out the
13654            // ending index to either increment or decrement.
13655            int sidx = subStr.lastIndexOf(prefix);
13656            if (sidx != -1) {
13657                subStr = subStr.substring(sidx + prefix.length());
13658                if (subStr != null) {
13659                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13660                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13661                    }
13662                    try {
13663                        idx = Integer.parseInt(subStr);
13664                        if (idx <= 1) {
13665                            idx++;
13666                        } else {
13667                            idx--;
13668                        }
13669                    } catch(NumberFormatException e) {
13670                    }
13671                }
13672            }
13673        }
13674        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13675        return prefix + idxStr;
13676    }
13677
13678    private File getNextCodePath(File targetDir, String packageName) {
13679        int suffix = 1;
13680        File result;
13681        do {
13682            result = new File(targetDir, packageName + "-" + suffix);
13683            suffix++;
13684        } while (result.exists());
13685        return result;
13686    }
13687
13688    // Utility method that returns the relative package path with respect
13689    // to the installation directory. Like say for /data/data/com.test-1.apk
13690    // string com.test-1 is returned.
13691    static String deriveCodePathName(String codePath) {
13692        if (codePath == null) {
13693            return null;
13694        }
13695        final File codeFile = new File(codePath);
13696        final String name = codeFile.getName();
13697        if (codeFile.isDirectory()) {
13698            return name;
13699        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13700            final int lastDot = name.lastIndexOf('.');
13701            return name.substring(0, lastDot);
13702        } else {
13703            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13704            return null;
13705        }
13706    }
13707
13708    static class PackageInstalledInfo {
13709        String name;
13710        int uid;
13711        // The set of users that originally had this package installed.
13712        int[] origUsers;
13713        // The set of users that now have this package installed.
13714        int[] newUsers;
13715        PackageParser.Package pkg;
13716        int returnCode;
13717        String returnMsg;
13718        PackageRemovedInfo removedInfo;
13719        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13720
13721        public void setError(int code, String msg) {
13722            setReturnCode(code);
13723            setReturnMessage(msg);
13724            Slog.w(TAG, msg);
13725        }
13726
13727        public void setError(String msg, PackageParserException e) {
13728            setReturnCode(e.error);
13729            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13730            Slog.w(TAG, msg, e);
13731        }
13732
13733        public void setError(String msg, PackageManagerException e) {
13734            returnCode = e.error;
13735            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13736            Slog.w(TAG, msg, e);
13737        }
13738
13739        public void setReturnCode(int returnCode) {
13740            this.returnCode = returnCode;
13741            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13742            for (int i = 0; i < childCount; i++) {
13743                addedChildPackages.valueAt(i).returnCode = returnCode;
13744            }
13745        }
13746
13747        private void setReturnMessage(String returnMsg) {
13748            this.returnMsg = returnMsg;
13749            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13750            for (int i = 0; i < childCount; i++) {
13751                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13752            }
13753        }
13754
13755        // In some error cases we want to convey more info back to the observer
13756        String origPackage;
13757        String origPermission;
13758    }
13759
13760    /*
13761     * Install a non-existing package.
13762     */
13763    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13764            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13765            PackageInstalledInfo res) {
13766        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13767
13768        // Remember this for later, in case we need to rollback this install
13769        String pkgName = pkg.packageName;
13770
13771        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13772
13773        synchronized(mPackages) {
13774            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13775                // A package with the same name is already installed, though
13776                // it has been renamed to an older name.  The package we
13777                // are trying to install should be installed as an update to
13778                // the existing one, but that has not been requested, so bail.
13779                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13780                        + " without first uninstalling package running as "
13781                        + mSettings.mRenamedPackages.get(pkgName));
13782                return;
13783            }
13784            if (mPackages.containsKey(pkgName)) {
13785                // Don't allow installation over an existing package with the same name.
13786                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13787                        + " without first uninstalling.");
13788                return;
13789            }
13790        }
13791
13792        try {
13793            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13794                    System.currentTimeMillis(), user);
13795
13796            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13797
13798            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13799                prepareAppDataAfterInstallLIF(newPackage);
13800
13801            } else {
13802                // Remove package from internal structures, but keep around any
13803                // data that might have already existed
13804                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13805                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13806            }
13807        } catch (PackageManagerException e) {
13808            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13809        }
13810
13811        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13812    }
13813
13814    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13815        // Can't rotate keys during boot or if sharedUser.
13816        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13817                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13818            return false;
13819        }
13820        // app is using upgradeKeySets; make sure all are valid
13821        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13822        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13823        for (int i = 0; i < upgradeKeySets.length; i++) {
13824            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13825                Slog.wtf(TAG, "Package "
13826                         + (oldPs.name != null ? oldPs.name : "<null>")
13827                         + " contains upgrade-key-set reference to unknown key-set: "
13828                         + upgradeKeySets[i]
13829                         + " reverting to signatures check.");
13830                return false;
13831            }
13832        }
13833        return true;
13834    }
13835
13836    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13837        // Upgrade keysets are being used.  Determine if new package has a superset of the
13838        // required keys.
13839        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13840        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13841        for (int i = 0; i < upgradeKeySets.length; i++) {
13842            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13843            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13844                return true;
13845            }
13846        }
13847        return false;
13848    }
13849
13850    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13851            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13852        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13853
13854        final PackageParser.Package oldPackage;
13855        final String pkgName = pkg.packageName;
13856        final int[] allUsers;
13857        final int[] installedUsers;
13858
13859        synchronized(mPackages) {
13860            oldPackage = mPackages.get(pkgName);
13861            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13862
13863            // don't allow upgrade to target a release SDK from a pre-release SDK
13864            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13865                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13866            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13867                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13868            if (oldTargetsPreRelease
13869                    && !newTargetsPreRelease
13870                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13871                Slog.w(TAG, "Can't install package targeting released sdk");
13872                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13873                return;
13874            }
13875
13876            // don't allow an upgrade from full to ephemeral
13877            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13878            if (isEphemeral && !oldIsEphemeral) {
13879                // can't downgrade from full to ephemeral
13880                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13881                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13882                return;
13883            }
13884
13885            // verify signatures are valid
13886            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13887            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13888                if (!checkUpgradeKeySetLP(ps, pkg)) {
13889                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13890                            "New package not signed by keys specified by upgrade-keysets: "
13891                                    + pkgName);
13892                    return;
13893                }
13894            } else {
13895                // default to original signature matching
13896                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13897                        != PackageManager.SIGNATURE_MATCH) {
13898                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13899                            "New package has a different signature: " + pkgName);
13900                    return;
13901                }
13902            }
13903
13904            // Check for shared user id changes
13905            String invalidPackageName =
13906                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13907            if (invalidPackageName != null) {
13908                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13909                        "Package " + invalidPackageName + " tried to change user "
13910                                + oldPackage.mSharedUserId);
13911                return;
13912            }
13913
13914            // In case of rollback, remember per-user/profile install state
13915            allUsers = sUserManager.getUserIds();
13916            installedUsers = ps.queryInstalledUsers(allUsers, true);
13917        }
13918
13919        // Update what is removed
13920        res.removedInfo = new PackageRemovedInfo();
13921        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13922        res.removedInfo.removedPackage = oldPackage.packageName;
13923        res.removedInfo.isUpdate = true;
13924        res.removedInfo.origUsers = installedUsers;
13925        final int childCount = (oldPackage.childPackages != null)
13926                ? oldPackage.childPackages.size() : 0;
13927        for (int i = 0; i < childCount; i++) {
13928            boolean childPackageUpdated = false;
13929            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13930            if (res.addedChildPackages != null) {
13931                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13932                if (childRes != null) {
13933                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13934                    childRes.removedInfo.removedPackage = childPkg.packageName;
13935                    childRes.removedInfo.isUpdate = true;
13936                    childPackageUpdated = true;
13937                }
13938            }
13939            if (!childPackageUpdated) {
13940                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13941                childRemovedRes.removedPackage = childPkg.packageName;
13942                childRemovedRes.isUpdate = false;
13943                childRemovedRes.dataRemoved = true;
13944                synchronized (mPackages) {
13945                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13946                    if (childPs != null) {
13947                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13948                    }
13949                }
13950                if (res.removedInfo.removedChildPackages == null) {
13951                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13952                }
13953                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13954            }
13955        }
13956
13957        boolean sysPkg = (isSystemApp(oldPackage));
13958        if (sysPkg) {
13959            // Set the system/privileged flags as needed
13960            final boolean privileged =
13961                    (oldPackage.applicationInfo.privateFlags
13962                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13963            final int systemPolicyFlags = policyFlags
13964                    | PackageParser.PARSE_IS_SYSTEM
13965                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13966
13967            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13968                    user, allUsers, installerPackageName, res);
13969        } else {
13970            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13971                    user, allUsers, installerPackageName, res);
13972        }
13973    }
13974
13975    public List<String> getPreviousCodePaths(String packageName) {
13976        final PackageSetting ps = mSettings.mPackages.get(packageName);
13977        final List<String> result = new ArrayList<String>();
13978        if (ps != null && ps.oldCodePaths != null) {
13979            result.addAll(ps.oldCodePaths);
13980        }
13981        return result;
13982    }
13983
13984    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13985            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13986            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13987        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13988                + deletedPackage);
13989
13990        String pkgName = deletedPackage.packageName;
13991        boolean deletedPkg = true;
13992        boolean addedPkg = false;
13993        boolean updatedSettings = false;
13994        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13995        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13996                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13997
13998        final long origUpdateTime = (pkg.mExtras != null)
13999                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14000
14001        // First delete the existing package while retaining the data directory
14002        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14003                res.removedInfo, true, pkg)) {
14004            // If the existing package wasn't successfully deleted
14005            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14006            deletedPkg = false;
14007        } else {
14008            // Successfully deleted the old package; proceed with replace.
14009
14010            // If deleted package lived in a container, give users a chance to
14011            // relinquish resources before killing.
14012            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14013                if (DEBUG_INSTALL) {
14014                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14015                }
14016                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14017                final ArrayList<String> pkgList = new ArrayList<String>(1);
14018                pkgList.add(deletedPackage.applicationInfo.packageName);
14019                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14020            }
14021
14022            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14023                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14024            clearAppProfilesLIF(pkg);
14025
14026            try {
14027                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14028                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14029                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14030
14031                // Update the in-memory copy of the previous code paths.
14032                PackageSetting ps = mSettings.mPackages.get(pkgName);
14033                if (!killApp) {
14034                    if (ps.oldCodePaths == null) {
14035                        ps.oldCodePaths = new ArraySet<>();
14036                    }
14037                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14038                    if (deletedPackage.splitCodePaths != null) {
14039                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14040                    }
14041                } else {
14042                    ps.oldCodePaths = null;
14043                }
14044                if (ps.childPackageNames != null) {
14045                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14046                        final String childPkgName = ps.childPackageNames.get(i);
14047                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14048                        childPs.oldCodePaths = ps.oldCodePaths;
14049                    }
14050                }
14051                prepareAppDataAfterInstallLIF(newPackage);
14052                addedPkg = true;
14053            } catch (PackageManagerException e) {
14054                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14055            }
14056        }
14057
14058        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14059            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14060
14061            // Revert all internal state mutations and added folders for the failed install
14062            if (addedPkg) {
14063                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14064                        res.removedInfo, true, null);
14065            }
14066
14067            // Restore the old package
14068            if (deletedPkg) {
14069                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14070                File restoreFile = new File(deletedPackage.codePath);
14071                // Parse old package
14072                boolean oldExternal = isExternal(deletedPackage);
14073                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14074                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14075                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14076                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14077                try {
14078                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14079                            null);
14080                } catch (PackageManagerException e) {
14081                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14082                            + e.getMessage());
14083                    return;
14084                }
14085
14086                synchronized (mPackages) {
14087                    // Ensure the installer package name up to date
14088                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14089
14090                    // Update permissions for restored package
14091                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14092
14093                    mSettings.writeLPr();
14094                }
14095
14096                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14097            }
14098        } else {
14099            synchronized (mPackages) {
14100                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14101                if (ps != null) {
14102                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14103                    if (res.removedInfo.removedChildPackages != null) {
14104                        final int childCount = res.removedInfo.removedChildPackages.size();
14105                        // Iterate in reverse as we may modify the collection
14106                        for (int i = childCount - 1; i >= 0; i--) {
14107                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14108                            if (res.addedChildPackages.containsKey(childPackageName)) {
14109                                res.removedInfo.removedChildPackages.removeAt(i);
14110                            } else {
14111                                PackageRemovedInfo childInfo = res.removedInfo
14112                                        .removedChildPackages.valueAt(i);
14113                                childInfo.removedForAllUsers = mPackages.get(
14114                                        childInfo.removedPackage) == null;
14115                            }
14116                        }
14117                    }
14118                }
14119            }
14120        }
14121    }
14122
14123    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14124            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14125            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14126        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14127                + ", old=" + deletedPackage);
14128
14129        final boolean disabledSystem;
14130
14131        // Remove existing system package
14132        removePackageLI(deletedPackage, true);
14133
14134        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14135        if (!disabledSystem) {
14136            // We didn't need to disable the .apk as a current system package,
14137            // which means we are replacing another update that is already
14138            // installed.  We need to make sure to delete the older one's .apk.
14139            res.removedInfo.args = createInstallArgsForExisting(0,
14140                    deletedPackage.applicationInfo.getCodePath(),
14141                    deletedPackage.applicationInfo.getResourcePath(),
14142                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14143        } else {
14144            res.removedInfo.args = null;
14145        }
14146
14147        // Successfully disabled the old package. Now proceed with re-installation
14148        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14149                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14150        clearAppProfilesLIF(pkg);
14151
14152        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14153        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14154                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14155
14156        PackageParser.Package newPackage = null;
14157        try {
14158            // Add the package to the internal data structures
14159            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14160
14161            // Set the update and install times
14162            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14163            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14164                    System.currentTimeMillis());
14165
14166            // Update the package dynamic state if succeeded
14167            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14168                // Now that the install succeeded make sure we remove data
14169                // directories for any child package the update removed.
14170                final int deletedChildCount = (deletedPackage.childPackages != null)
14171                        ? deletedPackage.childPackages.size() : 0;
14172                final int newChildCount = (newPackage.childPackages != null)
14173                        ? newPackage.childPackages.size() : 0;
14174                for (int i = 0; i < deletedChildCount; i++) {
14175                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14176                    boolean childPackageDeleted = true;
14177                    for (int j = 0; j < newChildCount; j++) {
14178                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14179                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14180                            childPackageDeleted = false;
14181                            break;
14182                        }
14183                    }
14184                    if (childPackageDeleted) {
14185                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14186                                deletedChildPkg.packageName);
14187                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14188                            PackageRemovedInfo removedChildRes = res.removedInfo
14189                                    .removedChildPackages.get(deletedChildPkg.packageName);
14190                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14191                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14192                        }
14193                    }
14194                }
14195
14196                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14197                prepareAppDataAfterInstallLIF(newPackage);
14198            }
14199        } catch (PackageManagerException e) {
14200            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14201            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14202        }
14203
14204        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14205            // Re installation failed. Restore old information
14206            // Remove new pkg information
14207            if (newPackage != null) {
14208                removeInstalledPackageLI(newPackage, true);
14209            }
14210            // Add back the old system package
14211            try {
14212                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14213            } catch (PackageManagerException e) {
14214                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14215            }
14216
14217            synchronized (mPackages) {
14218                if (disabledSystem) {
14219                    enableSystemPackageLPw(deletedPackage);
14220                }
14221
14222                // Ensure the installer package name up to date
14223                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14224
14225                // Update permissions for restored package
14226                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14227
14228                mSettings.writeLPr();
14229            }
14230
14231            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14232                    + " after failed upgrade");
14233        }
14234    }
14235
14236    /**
14237     * Checks whether the parent or any of the child packages have a change shared
14238     * user. For a package to be a valid update the shred users of the parent and
14239     * the children should match. We may later support changing child shared users.
14240     * @param oldPkg The updated package.
14241     * @param newPkg The update package.
14242     * @return The shared user that change between the versions.
14243     */
14244    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14245            PackageParser.Package newPkg) {
14246        // Check parent shared user
14247        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14248            return newPkg.packageName;
14249        }
14250        // Check child shared users
14251        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14252        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14253        for (int i = 0; i < newChildCount; i++) {
14254            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14255            // If this child was present, did it have the same shared user?
14256            for (int j = 0; j < oldChildCount; j++) {
14257                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14258                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14259                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14260                    return newChildPkg.packageName;
14261                }
14262            }
14263        }
14264        return null;
14265    }
14266
14267    private void removeNativeBinariesLI(PackageSetting ps) {
14268        // Remove the lib path for the parent package
14269        if (ps != null) {
14270            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14271            // Remove the lib path for the child packages
14272            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14273            for (int i = 0; i < childCount; i++) {
14274                PackageSetting childPs = null;
14275                synchronized (mPackages) {
14276                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14277                }
14278                if (childPs != null) {
14279                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14280                            .legacyNativeLibraryPathString);
14281                }
14282            }
14283        }
14284    }
14285
14286    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14287        // Enable the parent package
14288        mSettings.enableSystemPackageLPw(pkg.packageName);
14289        // Enable the child packages
14290        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14291        for (int i = 0; i < childCount; i++) {
14292            PackageParser.Package childPkg = pkg.childPackages.get(i);
14293            mSettings.enableSystemPackageLPw(childPkg.packageName);
14294        }
14295    }
14296
14297    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14298            PackageParser.Package newPkg) {
14299        // Disable the parent package (parent always replaced)
14300        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14301        // Disable the child packages
14302        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14303        for (int i = 0; i < childCount; i++) {
14304            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14305            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14306            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14307        }
14308        return disabled;
14309    }
14310
14311    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14312            String installerPackageName) {
14313        // Enable the parent package
14314        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14315        // Enable the child packages
14316        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14317        for (int i = 0; i < childCount; i++) {
14318            PackageParser.Package childPkg = pkg.childPackages.get(i);
14319            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14320        }
14321    }
14322
14323    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14324        // Collect all used permissions in the UID
14325        ArraySet<String> usedPermissions = new ArraySet<>();
14326        final int packageCount = su.packages.size();
14327        for (int i = 0; i < packageCount; i++) {
14328            PackageSetting ps = su.packages.valueAt(i);
14329            if (ps.pkg == null) {
14330                continue;
14331            }
14332            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14333            for (int j = 0; j < requestedPermCount; j++) {
14334                String permission = ps.pkg.requestedPermissions.get(j);
14335                BasePermission bp = mSettings.mPermissions.get(permission);
14336                if (bp != null) {
14337                    usedPermissions.add(permission);
14338                }
14339            }
14340        }
14341
14342        PermissionsState permissionsState = su.getPermissionsState();
14343        // Prune install permissions
14344        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14345        final int installPermCount = installPermStates.size();
14346        for (int i = installPermCount - 1; i >= 0;  i--) {
14347            PermissionState permissionState = installPermStates.get(i);
14348            if (!usedPermissions.contains(permissionState.getName())) {
14349                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14350                if (bp != null) {
14351                    permissionsState.revokeInstallPermission(bp);
14352                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14353                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14354                }
14355            }
14356        }
14357
14358        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14359
14360        // Prune runtime permissions
14361        for (int userId : allUserIds) {
14362            List<PermissionState> runtimePermStates = permissionsState
14363                    .getRuntimePermissionStates(userId);
14364            final int runtimePermCount = runtimePermStates.size();
14365            for (int i = runtimePermCount - 1; i >= 0; i--) {
14366                PermissionState permissionState = runtimePermStates.get(i);
14367                if (!usedPermissions.contains(permissionState.getName())) {
14368                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14369                    if (bp != null) {
14370                        permissionsState.revokeRuntimePermission(bp, userId);
14371                        permissionsState.updatePermissionFlags(bp, userId,
14372                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14373                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14374                                runtimePermissionChangedUserIds, userId);
14375                    }
14376                }
14377            }
14378        }
14379
14380        return runtimePermissionChangedUserIds;
14381    }
14382
14383    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14384            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14385        // Update the parent package setting
14386        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14387                res, user);
14388        // Update the child packages setting
14389        final int childCount = (newPackage.childPackages != null)
14390                ? newPackage.childPackages.size() : 0;
14391        for (int i = 0; i < childCount; i++) {
14392            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14393            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14394            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14395                    childRes.origUsers, childRes, user);
14396        }
14397    }
14398
14399    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14400            String installerPackageName, int[] allUsers, int[] installedForUsers,
14401            PackageInstalledInfo res, UserHandle user) {
14402        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14403
14404        String pkgName = newPackage.packageName;
14405        synchronized (mPackages) {
14406            //write settings. the installStatus will be incomplete at this stage.
14407            //note that the new package setting would have already been
14408            //added to mPackages. It hasn't been persisted yet.
14409            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14410            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14411            mSettings.writeLPr();
14412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14413        }
14414
14415        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14416        synchronized (mPackages) {
14417            updatePermissionsLPw(newPackage.packageName, newPackage,
14418                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14419                            ? UPDATE_PERMISSIONS_ALL : 0));
14420            // For system-bundled packages, we assume that installing an upgraded version
14421            // of the package implies that the user actually wants to run that new code,
14422            // so we enable the package.
14423            PackageSetting ps = mSettings.mPackages.get(pkgName);
14424            final int userId = user.getIdentifier();
14425            if (ps != null) {
14426                if (isSystemApp(newPackage)) {
14427                    if (DEBUG_INSTALL) {
14428                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14429                    }
14430                    // Enable system package for requested users
14431                    if (res.origUsers != null) {
14432                        for (int origUserId : res.origUsers) {
14433                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14434                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14435                                        origUserId, installerPackageName);
14436                            }
14437                        }
14438                    }
14439                    // Also convey the prior install/uninstall state
14440                    if (allUsers != null && installedForUsers != null) {
14441                        for (int currentUserId : allUsers) {
14442                            final boolean installed = ArrayUtils.contains(
14443                                    installedForUsers, currentUserId);
14444                            if (DEBUG_INSTALL) {
14445                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14446                            }
14447                            ps.setInstalled(installed, currentUserId);
14448                        }
14449                        // these install state changes will be persisted in the
14450                        // upcoming call to mSettings.writeLPr().
14451                    }
14452                }
14453                // It's implied that when a user requests installation, they want the app to be
14454                // installed and enabled.
14455                if (userId != UserHandle.USER_ALL) {
14456                    ps.setInstalled(true, userId);
14457                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14458                }
14459            }
14460            res.name = pkgName;
14461            res.uid = newPackage.applicationInfo.uid;
14462            res.pkg = newPackage;
14463            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14464            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14465            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14466            //to update install status
14467            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14468            mSettings.writeLPr();
14469            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14470        }
14471
14472        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14473    }
14474
14475    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14476        try {
14477            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14478            installPackageLI(args, res);
14479        } finally {
14480            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14481        }
14482    }
14483
14484    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14485        final int installFlags = args.installFlags;
14486        final String installerPackageName = args.installerPackageName;
14487        final String volumeUuid = args.volumeUuid;
14488        final File tmpPackageFile = new File(args.getCodePath());
14489        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14490        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14491                || (args.volumeUuid != null));
14492        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14493        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14494        boolean replace = false;
14495        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14496        if (args.move != null) {
14497            // moving a complete application; perform an initial scan on the new install location
14498            scanFlags |= SCAN_INITIAL;
14499        }
14500        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14501            scanFlags |= SCAN_DONT_KILL_APP;
14502        }
14503
14504        // Result object to be returned
14505        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14506
14507        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14508
14509        // Sanity check
14510        if (ephemeral && (forwardLocked || onExternal)) {
14511            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14512                    + " external=" + onExternal);
14513            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14514            return;
14515        }
14516
14517        // Retrieve PackageSettings and parse package
14518        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14519                | PackageParser.PARSE_ENFORCE_CODE
14520                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14521                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14522                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14523                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14524        PackageParser pp = new PackageParser();
14525        pp.setSeparateProcesses(mSeparateProcesses);
14526        pp.setDisplayMetrics(mMetrics);
14527
14528        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14529        final PackageParser.Package pkg;
14530        try {
14531            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14532        } catch (PackageParserException e) {
14533            res.setError("Failed parse during installPackageLI", e);
14534            return;
14535        } finally {
14536            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14537        }
14538
14539        // If we are installing a clustered package add results for the children
14540        if (pkg.childPackages != null) {
14541            synchronized (mPackages) {
14542                final int childCount = pkg.childPackages.size();
14543                for (int i = 0; i < childCount; i++) {
14544                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14545                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14546                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14547                    childRes.pkg = childPkg;
14548                    childRes.name = childPkg.packageName;
14549                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14550                    if (childPs != null) {
14551                        childRes.origUsers = childPs.queryInstalledUsers(
14552                                sUserManager.getUserIds(), true);
14553                    }
14554                    if ((mPackages.containsKey(childPkg.packageName))) {
14555                        childRes.removedInfo = new PackageRemovedInfo();
14556                        childRes.removedInfo.removedPackage = childPkg.packageName;
14557                    }
14558                    if (res.addedChildPackages == null) {
14559                        res.addedChildPackages = new ArrayMap<>();
14560                    }
14561                    res.addedChildPackages.put(childPkg.packageName, childRes);
14562                }
14563            }
14564        }
14565
14566        // If package doesn't declare API override, mark that we have an install
14567        // time CPU ABI override.
14568        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14569            pkg.cpuAbiOverride = args.abiOverride;
14570        }
14571
14572        String pkgName = res.name = pkg.packageName;
14573        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14574            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14575                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14576                return;
14577            }
14578        }
14579
14580        try {
14581            // either use what we've been given or parse directly from the APK
14582            if (args.certificates != null) {
14583                try {
14584                    PackageParser.populateCertificates(pkg, args.certificates);
14585                } catch (PackageParserException e) {
14586                    // there was something wrong with the certificates we were given;
14587                    // try to pull them from the APK
14588                    PackageParser.collectCertificates(pkg, parseFlags);
14589                }
14590            } else {
14591                PackageParser.collectCertificates(pkg, parseFlags);
14592            }
14593        } catch (PackageParserException e) {
14594            res.setError("Failed collect during installPackageLI", e);
14595            return;
14596        }
14597
14598        // Get rid of all references to package scan path via parser.
14599        pp = null;
14600        String oldCodePath = null;
14601        boolean systemApp = false;
14602        synchronized (mPackages) {
14603            // Check if installing already existing package
14604            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14605                String oldName = mSettings.mRenamedPackages.get(pkgName);
14606                if (pkg.mOriginalPackages != null
14607                        && pkg.mOriginalPackages.contains(oldName)
14608                        && mPackages.containsKey(oldName)) {
14609                    // This package is derived from an original package,
14610                    // and this device has been updating from that original
14611                    // name.  We must continue using the original name, so
14612                    // rename the new package here.
14613                    pkg.setPackageName(oldName);
14614                    pkgName = pkg.packageName;
14615                    replace = true;
14616                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14617                            + oldName + " pkgName=" + pkgName);
14618                } else if (mPackages.containsKey(pkgName)) {
14619                    // This package, under its official name, already exists
14620                    // on the device; we should replace it.
14621                    replace = true;
14622                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14623                }
14624
14625                // Child packages are installed through the parent package
14626                if (pkg.parentPackage != null) {
14627                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14628                            "Package " + pkg.packageName + " is child of package "
14629                                    + pkg.parentPackage.parentPackage + ". Child packages "
14630                                    + "can be updated only through the parent package.");
14631                    return;
14632                }
14633
14634                if (replace) {
14635                    // Prevent apps opting out from runtime permissions
14636                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14637                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14638                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14639                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14640                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14641                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14642                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14643                                        + " doesn't support runtime permissions but the old"
14644                                        + " target SDK " + oldTargetSdk + " does.");
14645                        return;
14646                    }
14647
14648                    // Prevent installing of child packages
14649                    if (oldPackage.parentPackage != null) {
14650                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14651                                "Package " + pkg.packageName + " is child of package "
14652                                        + oldPackage.parentPackage + ". Child packages "
14653                                        + "can be updated only through the parent package.");
14654                        return;
14655                    }
14656                }
14657            }
14658
14659            PackageSetting ps = mSettings.mPackages.get(pkgName);
14660            if (ps != null) {
14661                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14662
14663                // Quick sanity check that we're signed correctly if updating;
14664                // we'll check this again later when scanning, but we want to
14665                // bail early here before tripping over redefined permissions.
14666                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14667                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14668                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14669                                + pkg.packageName + " upgrade keys do not match the "
14670                                + "previously installed version");
14671                        return;
14672                    }
14673                } else {
14674                    try {
14675                        verifySignaturesLP(ps, pkg);
14676                    } catch (PackageManagerException e) {
14677                        res.setError(e.error, e.getMessage());
14678                        return;
14679                    }
14680                }
14681
14682                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14683                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14684                    systemApp = (ps.pkg.applicationInfo.flags &
14685                            ApplicationInfo.FLAG_SYSTEM) != 0;
14686                }
14687                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14688            }
14689
14690            // Check whether the newly-scanned package wants to define an already-defined perm
14691            int N = pkg.permissions.size();
14692            for (int i = N-1; i >= 0; i--) {
14693                PackageParser.Permission perm = pkg.permissions.get(i);
14694                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14695                if (bp != null) {
14696                    // If the defining package is signed with our cert, it's okay.  This
14697                    // also includes the "updating the same package" case, of course.
14698                    // "updating same package" could also involve key-rotation.
14699                    final boolean sigsOk;
14700                    if (bp.sourcePackage.equals(pkg.packageName)
14701                            && (bp.packageSetting instanceof PackageSetting)
14702                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14703                                    scanFlags))) {
14704                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14705                    } else {
14706                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14707                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14708                    }
14709                    if (!sigsOk) {
14710                        // If the owning package is the system itself, we log but allow
14711                        // install to proceed; we fail the install on all other permission
14712                        // redefinitions.
14713                        if (!bp.sourcePackage.equals("android")) {
14714                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14715                                    + pkg.packageName + " attempting to redeclare permission "
14716                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14717                            res.origPermission = perm.info.name;
14718                            res.origPackage = bp.sourcePackage;
14719                            return;
14720                        } else {
14721                            Slog.w(TAG, "Package " + pkg.packageName
14722                                    + " attempting to redeclare system permission "
14723                                    + perm.info.name + "; ignoring new declaration");
14724                            pkg.permissions.remove(i);
14725                        }
14726                    }
14727                }
14728            }
14729        }
14730
14731        if (systemApp) {
14732            if (onExternal) {
14733                // Abort update; system app can't be replaced with app on sdcard
14734                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14735                        "Cannot install updates to system apps on sdcard");
14736                return;
14737            } else if (ephemeral) {
14738                // Abort update; system app can't be replaced with an ephemeral app
14739                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14740                        "Cannot update a system app with an ephemeral app");
14741                return;
14742            }
14743        }
14744
14745        if (args.move != null) {
14746            // We did an in-place move, so dex is ready to roll
14747            scanFlags |= SCAN_NO_DEX;
14748            scanFlags |= SCAN_MOVE;
14749
14750            synchronized (mPackages) {
14751                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14752                if (ps == null) {
14753                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14754                            "Missing settings for moved package " + pkgName);
14755                }
14756
14757                // We moved the entire application as-is, so bring over the
14758                // previously derived ABI information.
14759                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14760                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14761            }
14762
14763        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14764            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14765            scanFlags |= SCAN_NO_DEX;
14766
14767            try {
14768                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14769                    args.abiOverride : pkg.cpuAbiOverride);
14770                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14771                        true /* extract libs */);
14772            } catch (PackageManagerException pme) {
14773                Slog.e(TAG, "Error deriving application ABI", pme);
14774                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14775                return;
14776            }
14777
14778            // Shared libraries for the package need to be updated.
14779            synchronized (mPackages) {
14780                try {
14781                    updateSharedLibrariesLPw(pkg, null);
14782                } catch (PackageManagerException e) {
14783                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14784                }
14785            }
14786            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14787            // Do not run PackageDexOptimizer through the local performDexOpt
14788            // method because `pkg` is not in `mPackages` yet.
14789            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14790                    null /* instructionSets */, false /* checkProfiles */,
14791                    getCompilerFilterForReason(REASON_INSTALL));
14792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14793            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14794                String msg = "Extracting package failed for " + pkgName;
14795                res.setError(INSTALL_FAILED_DEXOPT, msg);
14796                return;
14797            }
14798
14799            // Notify BackgroundDexOptService that the package has been changed.
14800            // If this is an update of a package which used to fail to compile,
14801            // BDOS will remove it from its blacklist.
14802            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14803        }
14804
14805        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14806            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14807            return;
14808        }
14809
14810        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14811
14812        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14813                "installPackageLI")) {
14814            if (replace) {
14815                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14816                        installerPackageName, res);
14817            } else {
14818                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14819                        args.user, installerPackageName, volumeUuid, res);
14820            }
14821        }
14822        synchronized (mPackages) {
14823            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14824            if (ps != null) {
14825                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14826            }
14827
14828            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14829            for (int i = 0; i < childCount; i++) {
14830                PackageParser.Package childPkg = pkg.childPackages.get(i);
14831                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14832                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14833                if (childPs != null) {
14834                    childRes.newUsers = childPs.queryInstalledUsers(
14835                            sUserManager.getUserIds(), true);
14836                }
14837            }
14838        }
14839    }
14840
14841    private void startIntentFilterVerifications(int userId, boolean replacing,
14842            PackageParser.Package pkg) {
14843        if (mIntentFilterVerifierComponent == null) {
14844            Slog.w(TAG, "No IntentFilter verification will not be done as "
14845                    + "there is no IntentFilterVerifier available!");
14846            return;
14847        }
14848
14849        final int verifierUid = getPackageUid(
14850                mIntentFilterVerifierComponent.getPackageName(),
14851                MATCH_DEBUG_TRIAGED_MISSING,
14852                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14853
14854        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14855        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14856        mHandler.sendMessage(msg);
14857
14858        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14859        for (int i = 0; i < childCount; i++) {
14860            PackageParser.Package childPkg = pkg.childPackages.get(i);
14861            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14862            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14863            mHandler.sendMessage(msg);
14864        }
14865    }
14866
14867    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14868            PackageParser.Package pkg) {
14869        int size = pkg.activities.size();
14870        if (size == 0) {
14871            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14872                    "No activity, so no need to verify any IntentFilter!");
14873            return;
14874        }
14875
14876        final boolean hasDomainURLs = hasDomainURLs(pkg);
14877        if (!hasDomainURLs) {
14878            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14879                    "No domain URLs, so no need to verify any IntentFilter!");
14880            return;
14881        }
14882
14883        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14884                + " if any IntentFilter from the " + size
14885                + " Activities needs verification ...");
14886
14887        int count = 0;
14888        final String packageName = pkg.packageName;
14889
14890        synchronized (mPackages) {
14891            // If this is a new install and we see that we've already run verification for this
14892            // package, we have nothing to do: it means the state was restored from backup.
14893            if (!replacing) {
14894                IntentFilterVerificationInfo ivi =
14895                        mSettings.getIntentFilterVerificationLPr(packageName);
14896                if (ivi != null) {
14897                    if (DEBUG_DOMAIN_VERIFICATION) {
14898                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14899                                + ivi.getStatusString());
14900                    }
14901                    return;
14902                }
14903            }
14904
14905            // If any filters need to be verified, then all need to be.
14906            boolean needToVerify = false;
14907            for (PackageParser.Activity a : pkg.activities) {
14908                for (ActivityIntentInfo filter : a.intents) {
14909                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14910                        if (DEBUG_DOMAIN_VERIFICATION) {
14911                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14912                        }
14913                        needToVerify = true;
14914                        break;
14915                    }
14916                }
14917            }
14918
14919            if (needToVerify) {
14920                final int verificationId = mIntentFilterVerificationToken++;
14921                for (PackageParser.Activity a : pkg.activities) {
14922                    for (ActivityIntentInfo filter : a.intents) {
14923                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14924                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14925                                    "Verification needed for IntentFilter:" + filter.toString());
14926                            mIntentFilterVerifier.addOneIntentFilterVerification(
14927                                    verifierUid, userId, verificationId, filter, packageName);
14928                            count++;
14929                        }
14930                    }
14931                }
14932            }
14933        }
14934
14935        if (count > 0) {
14936            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14937                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14938                    +  " for userId:" + userId);
14939            mIntentFilterVerifier.startVerifications(userId);
14940        } else {
14941            if (DEBUG_DOMAIN_VERIFICATION) {
14942                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14943            }
14944        }
14945    }
14946
14947    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14948        final ComponentName cn  = filter.activity.getComponentName();
14949        final String packageName = cn.getPackageName();
14950
14951        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14952                packageName);
14953        if (ivi == null) {
14954            return true;
14955        }
14956        int status = ivi.getStatus();
14957        switch (status) {
14958            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14959            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14960                return true;
14961
14962            default:
14963                // Nothing to do
14964                return false;
14965        }
14966    }
14967
14968    private static boolean isMultiArch(ApplicationInfo info) {
14969        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14970    }
14971
14972    private static boolean isExternal(PackageParser.Package pkg) {
14973        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14974    }
14975
14976    private static boolean isExternal(PackageSetting ps) {
14977        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14978    }
14979
14980    private static boolean isEphemeral(PackageParser.Package pkg) {
14981        return pkg.applicationInfo.isEphemeralApp();
14982    }
14983
14984    private static boolean isEphemeral(PackageSetting ps) {
14985        return ps.pkg != null && isEphemeral(ps.pkg);
14986    }
14987
14988    private static boolean isSystemApp(PackageParser.Package pkg) {
14989        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14990    }
14991
14992    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14993        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14994    }
14995
14996    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14997        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14998    }
14999
15000    private static boolean isSystemApp(PackageSetting ps) {
15001        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15002    }
15003
15004    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15005        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15006    }
15007
15008    private int packageFlagsToInstallFlags(PackageSetting ps) {
15009        int installFlags = 0;
15010        if (isEphemeral(ps)) {
15011            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15012        }
15013        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15014            // This existing package was an external ASEC install when we have
15015            // the external flag without a UUID
15016            installFlags |= PackageManager.INSTALL_EXTERNAL;
15017        }
15018        if (ps.isForwardLocked()) {
15019            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15020        }
15021        return installFlags;
15022    }
15023
15024    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15025        if (isExternal(pkg)) {
15026            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15027                return StorageManager.UUID_PRIMARY_PHYSICAL;
15028            } else {
15029                return pkg.volumeUuid;
15030            }
15031        } else {
15032            return StorageManager.UUID_PRIVATE_INTERNAL;
15033        }
15034    }
15035
15036    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15037        if (isExternal(pkg)) {
15038            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15039                return mSettings.getExternalVersion();
15040            } else {
15041                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15042            }
15043        } else {
15044            return mSettings.getInternalVersion();
15045        }
15046    }
15047
15048    private void deleteTempPackageFiles() {
15049        final FilenameFilter filter = new FilenameFilter() {
15050            public boolean accept(File dir, String name) {
15051                return name.startsWith("vmdl") && name.endsWith(".tmp");
15052            }
15053        };
15054        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15055            file.delete();
15056        }
15057    }
15058
15059    @Override
15060    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15061            int flags) {
15062        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15063                flags);
15064    }
15065
15066    @Override
15067    public void deletePackage(final String packageName,
15068            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15069        mContext.enforceCallingOrSelfPermission(
15070                android.Manifest.permission.DELETE_PACKAGES, null);
15071        Preconditions.checkNotNull(packageName);
15072        Preconditions.checkNotNull(observer);
15073        final int uid = Binder.getCallingUid();
15074        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15075        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15076        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15077            mContext.enforceCallingOrSelfPermission(
15078                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15079                    "deletePackage for user " + userId);
15080        }
15081
15082        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15083            try {
15084                observer.onPackageDeleted(packageName,
15085                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15086            } catch (RemoteException re) {
15087            }
15088            return;
15089        }
15090
15091        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15092            try {
15093                observer.onPackageDeleted(packageName,
15094                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15095            } catch (RemoteException re) {
15096            }
15097            return;
15098        }
15099
15100        if (DEBUG_REMOVE) {
15101            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15102                    + " deleteAllUsers: " + deleteAllUsers );
15103        }
15104        // Queue up an async operation since the package deletion may take a little while.
15105        mHandler.post(new Runnable() {
15106            public void run() {
15107                mHandler.removeCallbacks(this);
15108                int returnCode;
15109                if (!deleteAllUsers) {
15110                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15111                } else {
15112                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15113                    // If nobody is blocking uninstall, proceed with delete for all users
15114                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15115                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15116                    } else {
15117                        // Otherwise uninstall individually for users with blockUninstalls=false
15118                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15119                        for (int userId : users) {
15120                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15121                                returnCode = deletePackageX(packageName, userId, userFlags);
15122                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15123                                    Slog.w(TAG, "Package delete failed for user " + userId
15124                                            + ", returnCode " + returnCode);
15125                                }
15126                            }
15127                        }
15128                        // The app has only been marked uninstalled for certain users.
15129                        // We still need to report that delete was blocked
15130                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15131                    }
15132                }
15133                try {
15134                    observer.onPackageDeleted(packageName, returnCode, null);
15135                } catch (RemoteException e) {
15136                    Log.i(TAG, "Observer no longer exists.");
15137                } //end catch
15138            } //end run
15139        });
15140    }
15141
15142    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15143        int[] result = EMPTY_INT_ARRAY;
15144        for (int userId : userIds) {
15145            if (getBlockUninstallForUser(packageName, userId)) {
15146                result = ArrayUtils.appendInt(result, userId);
15147            }
15148        }
15149        return result;
15150    }
15151
15152    @Override
15153    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15154        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15155    }
15156
15157    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15158        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15159                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15160        try {
15161            if (dpm != null) {
15162                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15163                        /* callingUserOnly =*/ false);
15164                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15165                        : deviceOwnerComponentName.getPackageName();
15166                // Does the package contains the device owner?
15167                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15168                // this check is probably not needed, since DO should be registered as a device
15169                // admin on some user too. (Original bug for this: b/17657954)
15170                if (packageName.equals(deviceOwnerPackageName)) {
15171                    return true;
15172                }
15173                // Does it contain a device admin for any user?
15174                int[] users;
15175                if (userId == UserHandle.USER_ALL) {
15176                    users = sUserManager.getUserIds();
15177                } else {
15178                    users = new int[]{userId};
15179                }
15180                for (int i = 0; i < users.length; ++i) {
15181                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15182                        return true;
15183                    }
15184                }
15185            }
15186        } catch (RemoteException e) {
15187        }
15188        return false;
15189    }
15190
15191    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15192        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15193    }
15194
15195    /**
15196     *  This method is an internal method that could be get invoked either
15197     *  to delete an installed package or to clean up a failed installation.
15198     *  After deleting an installed package, a broadcast is sent to notify any
15199     *  listeners that the package has been removed. For cleaning up a failed
15200     *  installation, the broadcast is not necessary since the package's
15201     *  installation wouldn't have sent the initial broadcast either
15202     *  The key steps in deleting a package are
15203     *  deleting the package information in internal structures like mPackages,
15204     *  deleting the packages base directories through installd
15205     *  updating mSettings to reflect current status
15206     *  persisting settings for later use
15207     *  sending a broadcast if necessary
15208     */
15209    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15210        final PackageRemovedInfo info = new PackageRemovedInfo();
15211        final boolean res;
15212
15213        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15214                ? UserHandle.ALL : new UserHandle(userId);
15215
15216        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15217            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15218            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15219        }
15220
15221        PackageSetting uninstalledPs = null;
15222
15223        // for the uninstall-updates case and restricted profiles, remember the per-
15224        // user handle installed state
15225        int[] allUsers;
15226        synchronized (mPackages) {
15227            uninstalledPs = mSettings.mPackages.get(packageName);
15228            if (uninstalledPs == null) {
15229                Slog.w(TAG, "Not removing non-existent package " + packageName);
15230                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15231            }
15232            allUsers = sUserManager.getUserIds();
15233            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15234        }
15235
15236        synchronized (mInstallLock) {
15237            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15238            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15239                    "deletePackageX")) {
15240                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15241                        deleteFlags | REMOVE_CHATTY, info, true, null);
15242            }
15243            synchronized (mPackages) {
15244                if (res) {
15245                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15246                }
15247            }
15248        }
15249
15250        if (res) {
15251            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15252            info.sendPackageRemovedBroadcasts(killApp);
15253            info.sendSystemPackageUpdatedBroadcasts();
15254            info.sendSystemPackageAppearedBroadcasts();
15255        }
15256        // Force a gc here.
15257        Runtime.getRuntime().gc();
15258        // Delete the resources here after sending the broadcast to let
15259        // other processes clean up before deleting resources.
15260        if (info.args != null) {
15261            synchronized (mInstallLock) {
15262                info.args.doPostDeleteLI(true);
15263            }
15264        }
15265
15266        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15267    }
15268
15269    class PackageRemovedInfo {
15270        String removedPackage;
15271        int uid = -1;
15272        int removedAppId = -1;
15273        int[] origUsers;
15274        int[] removedUsers = null;
15275        boolean isRemovedPackageSystemUpdate = false;
15276        boolean isUpdate;
15277        boolean dataRemoved;
15278        boolean removedForAllUsers;
15279        // Clean up resources deleted packages.
15280        InstallArgs args = null;
15281        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15282        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15283
15284        void sendPackageRemovedBroadcasts(boolean killApp) {
15285            sendPackageRemovedBroadcastInternal(killApp);
15286            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15287            for (int i = 0; i < childCount; i++) {
15288                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15289                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15290            }
15291        }
15292
15293        void sendSystemPackageUpdatedBroadcasts() {
15294            if (isRemovedPackageSystemUpdate) {
15295                sendSystemPackageUpdatedBroadcastsInternal();
15296                final int childCount = (removedChildPackages != null)
15297                        ? removedChildPackages.size() : 0;
15298                for (int i = 0; i < childCount; i++) {
15299                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15300                    if (childInfo.isRemovedPackageSystemUpdate) {
15301                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15302                    }
15303                }
15304            }
15305        }
15306
15307        void sendSystemPackageAppearedBroadcasts() {
15308            final int packageCount = (appearedChildPackages != null)
15309                    ? appearedChildPackages.size() : 0;
15310            for (int i = 0; i < packageCount; i++) {
15311                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15312                for (int userId : installedInfo.newUsers) {
15313                    sendPackageAddedForUser(installedInfo.name, true,
15314                            UserHandle.getAppId(installedInfo.uid), userId);
15315                }
15316            }
15317        }
15318
15319        private void sendSystemPackageUpdatedBroadcastsInternal() {
15320            Bundle extras = new Bundle(2);
15321            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15322            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15323            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15324                    extras, 0, null, null, null);
15325            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15326                    extras, 0, null, null, null);
15327            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15328                    null, 0, removedPackage, null, null);
15329        }
15330
15331        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15332            Bundle extras = new Bundle(2);
15333            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15334            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15335            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15336            if (isUpdate || isRemovedPackageSystemUpdate) {
15337                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15338            }
15339            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15340            if (removedPackage != null) {
15341                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15342                        extras, 0, null, null, removedUsers);
15343                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15344                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15345                            removedPackage, extras, 0, null, null, removedUsers);
15346                }
15347            }
15348            if (removedAppId >= 0) {
15349                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15350                        removedUsers);
15351            }
15352        }
15353    }
15354
15355    /*
15356     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15357     * flag is not set, the data directory is removed as well.
15358     * make sure this flag is set for partially installed apps. If not its meaningless to
15359     * delete a partially installed application.
15360     */
15361    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15362            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15363        String packageName = ps.name;
15364        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15365        // Retrieve object to delete permissions for shared user later on
15366        final PackageParser.Package deletedPkg;
15367        final PackageSetting deletedPs;
15368        // reader
15369        synchronized (mPackages) {
15370            deletedPkg = mPackages.get(packageName);
15371            deletedPs = mSettings.mPackages.get(packageName);
15372            if (outInfo != null) {
15373                outInfo.removedPackage = packageName;
15374                outInfo.removedUsers = deletedPs != null
15375                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15376                        : null;
15377            }
15378        }
15379
15380        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15381
15382        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15383            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15384                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15385            destroyAppProfilesLIF(deletedPkg);
15386            if (outInfo != null) {
15387                outInfo.dataRemoved = true;
15388            }
15389            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15390        }
15391
15392        // writer
15393        synchronized (mPackages) {
15394            if (deletedPs != null) {
15395                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15396                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15397                    clearDefaultBrowserIfNeeded(packageName);
15398                    if (outInfo != null) {
15399                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15400                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15401                    }
15402                    updatePermissionsLPw(deletedPs.name, null, 0);
15403                    if (deletedPs.sharedUser != null) {
15404                        // Remove permissions associated with package. Since runtime
15405                        // permissions are per user we have to kill the removed package
15406                        // or packages running under the shared user of the removed
15407                        // package if revoking the permissions requested only by the removed
15408                        // package is successful and this causes a change in gids.
15409                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15410                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15411                                    userId);
15412                            if (userIdToKill == UserHandle.USER_ALL
15413                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15414                                // If gids changed for this user, kill all affected packages.
15415                                mHandler.post(new Runnable() {
15416                                    @Override
15417                                    public void run() {
15418                                        // This has to happen with no lock held.
15419                                        killApplication(deletedPs.name, deletedPs.appId,
15420                                                KILL_APP_REASON_GIDS_CHANGED);
15421                                    }
15422                                });
15423                                break;
15424                            }
15425                        }
15426                    }
15427                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15428                }
15429                // make sure to preserve per-user disabled state if this removal was just
15430                // a downgrade of a system app to the factory package
15431                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15432                    if (DEBUG_REMOVE) {
15433                        Slog.d(TAG, "Propagating install state across downgrade");
15434                    }
15435                    for (int userId : allUserHandles) {
15436                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15437                        if (DEBUG_REMOVE) {
15438                            Slog.d(TAG, "    user " + userId + " => " + installed);
15439                        }
15440                        ps.setInstalled(installed, userId);
15441                    }
15442                }
15443            }
15444            // can downgrade to reader
15445            if (writeSettings) {
15446                // Save settings now
15447                mSettings.writeLPr();
15448            }
15449        }
15450        if (outInfo != null) {
15451            // A user ID was deleted here. Go through all users and remove it
15452            // from KeyStore.
15453            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15454        }
15455    }
15456
15457    static boolean locationIsPrivileged(File path) {
15458        try {
15459            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15460                    .getCanonicalPath();
15461            return path.getCanonicalPath().startsWith(privilegedAppDir);
15462        } catch (IOException e) {
15463            Slog.e(TAG, "Unable to access code path " + path);
15464        }
15465        return false;
15466    }
15467
15468    /*
15469     * Tries to delete system package.
15470     */
15471    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15472            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15473            boolean writeSettings) {
15474        if (deletedPs.parentPackageName != null) {
15475            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15476            return false;
15477        }
15478
15479        final boolean applyUserRestrictions
15480                = (allUserHandles != null) && (outInfo.origUsers != null);
15481        final PackageSetting disabledPs;
15482        // Confirm if the system package has been updated
15483        // An updated system app can be deleted. This will also have to restore
15484        // the system pkg from system partition
15485        // reader
15486        synchronized (mPackages) {
15487            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15488        }
15489
15490        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15491                + " disabledPs=" + disabledPs);
15492
15493        if (disabledPs == null) {
15494            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15495            return false;
15496        } else if (DEBUG_REMOVE) {
15497            Slog.d(TAG, "Deleting system pkg from data partition");
15498        }
15499
15500        if (DEBUG_REMOVE) {
15501            if (applyUserRestrictions) {
15502                Slog.d(TAG, "Remembering install states:");
15503                for (int userId : allUserHandles) {
15504                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15505                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15506                }
15507            }
15508        }
15509
15510        // Delete the updated package
15511        outInfo.isRemovedPackageSystemUpdate = true;
15512        if (outInfo.removedChildPackages != null) {
15513            final int childCount = (deletedPs.childPackageNames != null)
15514                    ? deletedPs.childPackageNames.size() : 0;
15515            for (int i = 0; i < childCount; i++) {
15516                String childPackageName = deletedPs.childPackageNames.get(i);
15517                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15518                        .contains(childPackageName)) {
15519                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15520                            childPackageName);
15521                    if (childInfo != null) {
15522                        childInfo.isRemovedPackageSystemUpdate = true;
15523                    }
15524                }
15525            }
15526        }
15527
15528        if (disabledPs.versionCode < deletedPs.versionCode) {
15529            // Delete data for downgrades
15530            flags &= ~PackageManager.DELETE_KEEP_DATA;
15531        } else {
15532            // Preserve data by setting flag
15533            flags |= PackageManager.DELETE_KEEP_DATA;
15534        }
15535
15536        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15537                outInfo, writeSettings, disabledPs.pkg);
15538        if (!ret) {
15539            return false;
15540        }
15541
15542        // writer
15543        synchronized (mPackages) {
15544            // Reinstate the old system package
15545            enableSystemPackageLPw(disabledPs.pkg);
15546            // Remove any native libraries from the upgraded package.
15547            removeNativeBinariesLI(deletedPs);
15548        }
15549
15550        // Install the system package
15551        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15552        int parseFlags = mDefParseFlags
15553                | PackageParser.PARSE_MUST_BE_APK
15554                | PackageParser.PARSE_IS_SYSTEM
15555                | PackageParser.PARSE_IS_SYSTEM_DIR;
15556        if (locationIsPrivileged(disabledPs.codePath)) {
15557            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15558        }
15559
15560        final PackageParser.Package newPkg;
15561        try {
15562            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15563        } catch (PackageManagerException e) {
15564            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15565                    + e.getMessage());
15566            return false;
15567        }
15568
15569        prepareAppDataAfterInstallLIF(newPkg);
15570
15571        // writer
15572        synchronized (mPackages) {
15573            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15574
15575            // Propagate the permissions state as we do not want to drop on the floor
15576            // runtime permissions. The update permissions method below will take
15577            // care of removing obsolete permissions and grant install permissions.
15578            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15579            updatePermissionsLPw(newPkg.packageName, newPkg,
15580                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15581
15582            if (applyUserRestrictions) {
15583                if (DEBUG_REMOVE) {
15584                    Slog.d(TAG, "Propagating install state across reinstall");
15585                }
15586                for (int userId : allUserHandles) {
15587                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15588                    if (DEBUG_REMOVE) {
15589                        Slog.d(TAG, "    user " + userId + " => " + installed);
15590                    }
15591                    ps.setInstalled(installed, userId);
15592
15593                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15594                }
15595                // Regardless of writeSettings we need to ensure that this restriction
15596                // state propagation is persisted
15597                mSettings.writeAllUsersPackageRestrictionsLPr();
15598            }
15599            // can downgrade to reader here
15600            if (writeSettings) {
15601                mSettings.writeLPr();
15602            }
15603        }
15604        return true;
15605    }
15606
15607    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15608            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15609            PackageRemovedInfo outInfo, boolean writeSettings,
15610            PackageParser.Package replacingPackage) {
15611        synchronized (mPackages) {
15612            if (outInfo != null) {
15613                outInfo.uid = ps.appId;
15614            }
15615
15616            if (outInfo != null && outInfo.removedChildPackages != null) {
15617                final int childCount = (ps.childPackageNames != null)
15618                        ? ps.childPackageNames.size() : 0;
15619                for (int i = 0; i < childCount; i++) {
15620                    String childPackageName = ps.childPackageNames.get(i);
15621                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15622                    if (childPs == null) {
15623                        return false;
15624                    }
15625                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15626                            childPackageName);
15627                    if (childInfo != null) {
15628                        childInfo.uid = childPs.appId;
15629                    }
15630                }
15631            }
15632        }
15633
15634        // Delete package data from internal structures and also remove data if flag is set
15635        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15636
15637        // Delete the child packages data
15638        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15639        for (int i = 0; i < childCount; i++) {
15640            PackageSetting childPs;
15641            synchronized (mPackages) {
15642                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15643            }
15644            if (childPs != null) {
15645                PackageRemovedInfo childOutInfo = (outInfo != null
15646                        && outInfo.removedChildPackages != null)
15647                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15648                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15649                        && (replacingPackage != null
15650                        && !replacingPackage.hasChildPackage(childPs.name))
15651                        ? flags & ~DELETE_KEEP_DATA : flags;
15652                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15653                        deleteFlags, writeSettings);
15654            }
15655        }
15656
15657        // Delete application code and resources only for parent packages
15658        if (ps.parentPackageName == null) {
15659            if (deleteCodeAndResources && (outInfo != null)) {
15660                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15661                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15662                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15663            }
15664        }
15665
15666        return true;
15667    }
15668
15669    @Override
15670    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15671            int userId) {
15672        mContext.enforceCallingOrSelfPermission(
15673                android.Manifest.permission.DELETE_PACKAGES, null);
15674        synchronized (mPackages) {
15675            PackageSetting ps = mSettings.mPackages.get(packageName);
15676            if (ps == null) {
15677                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15678                return false;
15679            }
15680            if (!ps.getInstalled(userId)) {
15681                // Can't block uninstall for an app that is not installed or enabled.
15682                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15683                return false;
15684            }
15685            ps.setBlockUninstall(blockUninstall, userId);
15686            mSettings.writePackageRestrictionsLPr(userId);
15687        }
15688        return true;
15689    }
15690
15691    @Override
15692    public boolean getBlockUninstallForUser(String packageName, int userId) {
15693        synchronized (mPackages) {
15694            PackageSetting ps = mSettings.mPackages.get(packageName);
15695            if (ps == null) {
15696                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15697                return false;
15698            }
15699            return ps.getBlockUninstall(userId);
15700        }
15701    }
15702
15703    @Override
15704    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15705        int callingUid = Binder.getCallingUid();
15706        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15707            throw new SecurityException(
15708                    "setRequiredForSystemUser can only be run by the system or root");
15709        }
15710        synchronized (mPackages) {
15711            PackageSetting ps = mSettings.mPackages.get(packageName);
15712            if (ps == null) {
15713                Log.w(TAG, "Package doesn't exist: " + packageName);
15714                return false;
15715            }
15716            if (systemUserApp) {
15717                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15718            } else {
15719                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15720            }
15721            mSettings.writeLPr();
15722        }
15723        return true;
15724    }
15725
15726    /*
15727     * This method handles package deletion in general
15728     */
15729    private boolean deletePackageLIF(String packageName, UserHandle user,
15730            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15731            PackageRemovedInfo outInfo, boolean writeSettings,
15732            PackageParser.Package replacingPackage) {
15733        if (packageName == null) {
15734            Slog.w(TAG, "Attempt to delete null packageName.");
15735            return false;
15736        }
15737
15738        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15739
15740        PackageSetting ps;
15741
15742        synchronized (mPackages) {
15743            ps = mSettings.mPackages.get(packageName);
15744            if (ps == null) {
15745                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15746                return false;
15747            }
15748
15749            if (ps.parentPackageName != null && (!isSystemApp(ps)
15750                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15751                if (DEBUG_REMOVE) {
15752                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15753                            + ((user == null) ? UserHandle.USER_ALL : user));
15754                }
15755                final int removedUserId = (user != null) ? user.getIdentifier()
15756                        : UserHandle.USER_ALL;
15757                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15758                    return false;
15759                }
15760                markPackageUninstalledForUserLPw(ps, user);
15761                scheduleWritePackageRestrictionsLocked(user);
15762                return true;
15763            }
15764        }
15765
15766        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15767                && user.getIdentifier() != UserHandle.USER_ALL)) {
15768            // The caller is asking that the package only be deleted for a single
15769            // user.  To do this, we just mark its uninstalled state and delete
15770            // its data. If this is a system app, we only allow this to happen if
15771            // they have set the special DELETE_SYSTEM_APP which requests different
15772            // semantics than normal for uninstalling system apps.
15773            markPackageUninstalledForUserLPw(ps, user);
15774
15775            if (!isSystemApp(ps)) {
15776                // Do not uninstall the APK if an app should be cached
15777                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15778                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15779                    // Other user still have this package installed, so all
15780                    // we need to do is clear this user's data and save that
15781                    // it is uninstalled.
15782                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15783                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15784                        return false;
15785                    }
15786                    scheduleWritePackageRestrictionsLocked(user);
15787                    return true;
15788                } else {
15789                    // We need to set it back to 'installed' so the uninstall
15790                    // broadcasts will be sent correctly.
15791                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15792                    ps.setInstalled(true, user.getIdentifier());
15793                }
15794            } else {
15795                // This is a system app, so we assume that the
15796                // other users still have this package installed, so all
15797                // we need to do is clear this user's data and save that
15798                // it is uninstalled.
15799                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15800                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15801                    return false;
15802                }
15803                scheduleWritePackageRestrictionsLocked(user);
15804                return true;
15805            }
15806        }
15807
15808        // If we are deleting a composite package for all users, keep track
15809        // of result for each child.
15810        if (ps.childPackageNames != null && outInfo != null) {
15811            synchronized (mPackages) {
15812                final int childCount = ps.childPackageNames.size();
15813                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15814                for (int i = 0; i < childCount; i++) {
15815                    String childPackageName = ps.childPackageNames.get(i);
15816                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15817                    childInfo.removedPackage = childPackageName;
15818                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15819                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15820                    if (childPs != null) {
15821                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15822                    }
15823                }
15824            }
15825        }
15826
15827        boolean ret = false;
15828        if (isSystemApp(ps)) {
15829            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15830            // When an updated system application is deleted we delete the existing resources
15831            // as well and fall back to existing code in system partition
15832            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15833        } else {
15834            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15835            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15836                    outInfo, writeSettings, replacingPackage);
15837        }
15838
15839        // Take a note whether we deleted the package for all users
15840        if (outInfo != null) {
15841            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15842            if (outInfo.removedChildPackages != null) {
15843                synchronized (mPackages) {
15844                    final int childCount = outInfo.removedChildPackages.size();
15845                    for (int i = 0; i < childCount; i++) {
15846                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15847                        if (childInfo != null) {
15848                            childInfo.removedForAllUsers = mPackages.get(
15849                                    childInfo.removedPackage) == null;
15850                        }
15851                    }
15852                }
15853            }
15854            // If we uninstalled an update to a system app there may be some
15855            // child packages that appeared as they are declared in the system
15856            // app but were not declared in the update.
15857            if (isSystemApp(ps)) {
15858                synchronized (mPackages) {
15859                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15860                    final int childCount = (updatedPs.childPackageNames != null)
15861                            ? updatedPs.childPackageNames.size() : 0;
15862                    for (int i = 0; i < childCount; i++) {
15863                        String childPackageName = updatedPs.childPackageNames.get(i);
15864                        if (outInfo.removedChildPackages == null
15865                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15866                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15867                            if (childPs == null) {
15868                                continue;
15869                            }
15870                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15871                            installRes.name = childPackageName;
15872                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15873                            installRes.pkg = mPackages.get(childPackageName);
15874                            installRes.uid = childPs.pkg.applicationInfo.uid;
15875                            if (outInfo.appearedChildPackages == null) {
15876                                outInfo.appearedChildPackages = new ArrayMap<>();
15877                            }
15878                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15879                        }
15880                    }
15881                }
15882            }
15883        }
15884
15885        return ret;
15886    }
15887
15888    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15889        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15890                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15891        for (int nextUserId : userIds) {
15892            if (DEBUG_REMOVE) {
15893                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15894            }
15895            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15896                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15897                    false /*hidden*/, false /*suspended*/, null, null, null,
15898                    false /*blockUninstall*/,
15899                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15900        }
15901    }
15902
15903    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15904            PackageRemovedInfo outInfo) {
15905        final PackageParser.Package pkg;
15906        synchronized (mPackages) {
15907            pkg = mPackages.get(ps.name);
15908        }
15909
15910        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15911                : new int[] {userId};
15912        for (int nextUserId : userIds) {
15913            if (DEBUG_REMOVE) {
15914                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15915                        + nextUserId);
15916            }
15917
15918            destroyAppDataLIF(pkg, userId,
15919                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15920            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15921            schedulePackageCleaning(ps.name, nextUserId, false);
15922            synchronized (mPackages) {
15923                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15924                    scheduleWritePackageRestrictionsLocked(nextUserId);
15925                }
15926                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15927            }
15928        }
15929
15930        if (outInfo != null) {
15931            outInfo.removedPackage = ps.name;
15932            outInfo.removedAppId = ps.appId;
15933            outInfo.removedUsers = userIds;
15934        }
15935
15936        return true;
15937    }
15938
15939    private final class ClearStorageConnection implements ServiceConnection {
15940        IMediaContainerService mContainerService;
15941
15942        @Override
15943        public void onServiceConnected(ComponentName name, IBinder service) {
15944            synchronized (this) {
15945                mContainerService = IMediaContainerService.Stub.asInterface(service);
15946                notifyAll();
15947            }
15948        }
15949
15950        @Override
15951        public void onServiceDisconnected(ComponentName name) {
15952        }
15953    }
15954
15955    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15956        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15957
15958        final boolean mounted;
15959        if (Environment.isExternalStorageEmulated()) {
15960            mounted = true;
15961        } else {
15962            final String status = Environment.getExternalStorageState();
15963
15964            mounted = status.equals(Environment.MEDIA_MOUNTED)
15965                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15966        }
15967
15968        if (!mounted) {
15969            return;
15970        }
15971
15972        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15973        int[] users;
15974        if (userId == UserHandle.USER_ALL) {
15975            users = sUserManager.getUserIds();
15976        } else {
15977            users = new int[] { userId };
15978        }
15979        final ClearStorageConnection conn = new ClearStorageConnection();
15980        if (mContext.bindServiceAsUser(
15981                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15982            try {
15983                for (int curUser : users) {
15984                    long timeout = SystemClock.uptimeMillis() + 5000;
15985                    synchronized (conn) {
15986                        long now = SystemClock.uptimeMillis();
15987                        while (conn.mContainerService == null && now < timeout) {
15988                            try {
15989                                conn.wait(timeout - now);
15990                            } catch (InterruptedException e) {
15991                            }
15992                        }
15993                    }
15994                    if (conn.mContainerService == null) {
15995                        return;
15996                    }
15997
15998                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15999                    clearDirectory(conn.mContainerService,
16000                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16001                    if (allData) {
16002                        clearDirectory(conn.mContainerService,
16003                                userEnv.buildExternalStorageAppDataDirs(packageName));
16004                        clearDirectory(conn.mContainerService,
16005                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16006                    }
16007                }
16008            } finally {
16009                mContext.unbindService(conn);
16010            }
16011        }
16012    }
16013
16014    @Override
16015    public void clearApplicationProfileData(String packageName) {
16016        enforceSystemOrRoot("Only the system can clear all profile data");
16017
16018        final PackageParser.Package pkg;
16019        synchronized (mPackages) {
16020            pkg = mPackages.get(packageName);
16021        }
16022
16023        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16024            synchronized (mInstallLock) {
16025                clearAppProfilesLIF(pkg);
16026            }
16027        }
16028    }
16029
16030    @Override
16031    public void clearApplicationUserData(final String packageName,
16032            final IPackageDataObserver observer, final int userId) {
16033        mContext.enforceCallingOrSelfPermission(
16034                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16035
16036        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16037                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16038
16039        final DevicePolicyManagerInternal dpmi = LocalServices
16040                .getService(DevicePolicyManagerInternal.class);
16041        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16042            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16043        }
16044        // Queue up an async operation since the package deletion may take a little while.
16045        mHandler.post(new Runnable() {
16046            public void run() {
16047                mHandler.removeCallbacks(this);
16048                final boolean succeeded;
16049                try (PackageFreezer freezer = freezePackage(packageName,
16050                        "clearApplicationUserData")) {
16051                    synchronized (mInstallLock) {
16052                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16053                    }
16054                    clearExternalStorageDataSync(packageName, userId, true);
16055                }
16056                if (succeeded) {
16057                    // invoke DeviceStorageMonitor's update method to clear any notifications
16058                    DeviceStorageMonitorInternal dsm = LocalServices
16059                            .getService(DeviceStorageMonitorInternal.class);
16060                    if (dsm != null) {
16061                        dsm.checkMemory();
16062                    }
16063                }
16064                if(observer != null) {
16065                    try {
16066                        observer.onRemoveCompleted(packageName, succeeded);
16067                    } catch (RemoteException e) {
16068                        Log.i(TAG, "Observer no longer exists.");
16069                    }
16070                } //end if observer
16071            } //end run
16072        });
16073    }
16074
16075    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16076        if (packageName == null) {
16077            Slog.w(TAG, "Attempt to delete null packageName.");
16078            return false;
16079        }
16080
16081        // Try finding details about the requested package
16082        PackageParser.Package pkg;
16083        synchronized (mPackages) {
16084            pkg = mPackages.get(packageName);
16085            if (pkg == null) {
16086                final PackageSetting ps = mSettings.mPackages.get(packageName);
16087                if (ps != null) {
16088                    pkg = ps.pkg;
16089                }
16090            }
16091
16092            if (pkg == null) {
16093                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16094                return false;
16095            }
16096
16097            PackageSetting ps = (PackageSetting) pkg.mExtras;
16098            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16099        }
16100
16101        clearAppDataLIF(pkg, userId,
16102                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16103
16104        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16105        removeKeystoreDataIfNeeded(userId, appId);
16106
16107        final UserManager um = mContext.getSystemService(UserManager.class);
16108        final int flags;
16109        if (um.isUserUnlocked(userId)) {
16110            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16111        } else if (um.isUserRunning(userId)) {
16112            flags = StorageManager.FLAG_STORAGE_DE;
16113        } else {
16114            flags = 0;
16115        }
16116        prepareAppDataContentsLIF(pkg, userId, flags);
16117
16118        return true;
16119    }
16120
16121    /**
16122     * Reverts user permission state changes (permissions and flags) in
16123     * all packages for a given user.
16124     *
16125     * @param userId The device user for which to do a reset.
16126     */
16127    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16128        final int packageCount = mPackages.size();
16129        for (int i = 0; i < packageCount; i++) {
16130            PackageParser.Package pkg = mPackages.valueAt(i);
16131            PackageSetting ps = (PackageSetting) pkg.mExtras;
16132            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16133        }
16134    }
16135
16136    /**
16137     * Reverts user permission state changes (permissions and flags).
16138     *
16139     * @param ps The package for which to reset.
16140     * @param userId The device user for which to do a reset.
16141     */
16142    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16143            final PackageSetting ps, final int userId) {
16144        if (ps.pkg == null) {
16145            return;
16146        }
16147
16148        // These are flags that can change base on user actions.
16149        final int userSettableMask = FLAG_PERMISSION_USER_SET
16150                | FLAG_PERMISSION_USER_FIXED
16151                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16152                | FLAG_PERMISSION_REVIEW_REQUIRED;
16153
16154        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16155                | FLAG_PERMISSION_POLICY_FIXED;
16156
16157        boolean writeInstallPermissions = false;
16158        boolean writeRuntimePermissions = false;
16159
16160        final int permissionCount = ps.pkg.requestedPermissions.size();
16161        for (int i = 0; i < permissionCount; i++) {
16162            String permission = ps.pkg.requestedPermissions.get(i);
16163
16164            BasePermission bp = mSettings.mPermissions.get(permission);
16165            if (bp == null) {
16166                continue;
16167            }
16168
16169            // If shared user we just reset the state to which only this app contributed.
16170            if (ps.sharedUser != null) {
16171                boolean used = false;
16172                final int packageCount = ps.sharedUser.packages.size();
16173                for (int j = 0; j < packageCount; j++) {
16174                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16175                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16176                            && pkg.pkg.requestedPermissions.contains(permission)) {
16177                        used = true;
16178                        break;
16179                    }
16180                }
16181                if (used) {
16182                    continue;
16183                }
16184            }
16185
16186            PermissionsState permissionsState = ps.getPermissionsState();
16187
16188            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16189
16190            // Always clear the user settable flags.
16191            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16192                    bp.name) != null;
16193            // If permission review is enabled and this is a legacy app, mark the
16194            // permission as requiring a review as this is the initial state.
16195            int flags = 0;
16196            if (Build.PERMISSIONS_REVIEW_REQUIRED
16197                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16198                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16199            }
16200            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16201                if (hasInstallState) {
16202                    writeInstallPermissions = true;
16203                } else {
16204                    writeRuntimePermissions = true;
16205                }
16206            }
16207
16208            // Below is only runtime permission handling.
16209            if (!bp.isRuntime()) {
16210                continue;
16211            }
16212
16213            // Never clobber system or policy.
16214            if ((oldFlags & policyOrSystemFlags) != 0) {
16215                continue;
16216            }
16217
16218            // If this permission was granted by default, make sure it is.
16219            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16220                if (permissionsState.grantRuntimePermission(bp, userId)
16221                        != PERMISSION_OPERATION_FAILURE) {
16222                    writeRuntimePermissions = true;
16223                }
16224            // If permission review is enabled the permissions for a legacy apps
16225            // are represented as constantly granted runtime ones, so don't revoke.
16226            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16227                // Otherwise, reset the permission.
16228                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16229                switch (revokeResult) {
16230                    case PERMISSION_OPERATION_SUCCESS:
16231                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16232                        writeRuntimePermissions = true;
16233                        final int appId = ps.appId;
16234                        mHandler.post(new Runnable() {
16235                            @Override
16236                            public void run() {
16237                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16238                            }
16239                        });
16240                    } break;
16241                }
16242            }
16243        }
16244
16245        // Synchronously write as we are taking permissions away.
16246        if (writeRuntimePermissions) {
16247            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16248        }
16249
16250        // Synchronously write as we are taking permissions away.
16251        if (writeInstallPermissions) {
16252            mSettings.writeLPr();
16253        }
16254    }
16255
16256    /**
16257     * Remove entries from the keystore daemon. Will only remove it if the
16258     * {@code appId} is valid.
16259     */
16260    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16261        if (appId < 0) {
16262            return;
16263        }
16264
16265        final KeyStore keyStore = KeyStore.getInstance();
16266        if (keyStore != null) {
16267            if (userId == UserHandle.USER_ALL) {
16268                for (final int individual : sUserManager.getUserIds()) {
16269                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16270                }
16271            } else {
16272                keyStore.clearUid(UserHandle.getUid(userId, appId));
16273            }
16274        } else {
16275            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16276        }
16277    }
16278
16279    @Override
16280    public void deleteApplicationCacheFiles(final String packageName,
16281            final IPackageDataObserver observer) {
16282        final int userId = UserHandle.getCallingUserId();
16283        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16284    }
16285
16286    @Override
16287    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16288            final IPackageDataObserver observer) {
16289        mContext.enforceCallingOrSelfPermission(
16290                android.Manifest.permission.DELETE_CACHE_FILES, null);
16291        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16292                /* requireFullPermission= */ true, /* checkShell= */ false,
16293                "delete application cache files");
16294
16295        final PackageParser.Package pkg;
16296        synchronized (mPackages) {
16297            pkg = mPackages.get(packageName);
16298        }
16299
16300        // Queue up an async operation since the package deletion may take a little while.
16301        mHandler.post(new Runnable() {
16302            public void run() {
16303                synchronized (mInstallLock) {
16304                    final int flags = StorageManager.FLAG_STORAGE_DE
16305                            | StorageManager.FLAG_STORAGE_CE;
16306                    // We're only clearing cache files, so we don't care if the
16307                    // app is unfrozen and still able to run
16308                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16309                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16310                }
16311                clearExternalStorageDataSync(packageName, userId, false);
16312                if (observer != null) {
16313                    try {
16314                        observer.onRemoveCompleted(packageName, true);
16315                    } catch (RemoteException e) {
16316                        Log.i(TAG, "Observer no longer exists.");
16317                    }
16318                }
16319            }
16320        });
16321    }
16322
16323    @Override
16324    public void getPackageSizeInfo(final String packageName, int userHandle,
16325            final IPackageStatsObserver observer) {
16326        mContext.enforceCallingOrSelfPermission(
16327                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16328        if (packageName == null) {
16329            throw new IllegalArgumentException("Attempt to get size of null packageName");
16330        }
16331
16332        PackageStats stats = new PackageStats(packageName, userHandle);
16333
16334        /*
16335         * Queue up an async operation since the package measurement may take a
16336         * little while.
16337         */
16338        Message msg = mHandler.obtainMessage(INIT_COPY);
16339        msg.obj = new MeasureParams(stats, observer);
16340        mHandler.sendMessage(msg);
16341    }
16342
16343    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16344        final PackageSetting ps;
16345        synchronized (mPackages) {
16346            ps = mSettings.mPackages.get(packageName);
16347            if (ps == null) {
16348                Slog.w(TAG, "Failed to find settings for " + packageName);
16349                return false;
16350            }
16351        }
16352        try {
16353            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16354                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16355                    ps.getCeDataInode(userId), ps.codePathString, stats);
16356        } catch (InstallerException e) {
16357            Slog.w(TAG, String.valueOf(e));
16358            return false;
16359        }
16360
16361        // For now, ignore code size of packages on system partition
16362        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16363            stats.codeSize = 0;
16364        }
16365
16366        return true;
16367    }
16368
16369    private int getUidTargetSdkVersionLockedLPr(int uid) {
16370        Object obj = mSettings.getUserIdLPr(uid);
16371        if (obj instanceof SharedUserSetting) {
16372            final SharedUserSetting sus = (SharedUserSetting) obj;
16373            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16374            final Iterator<PackageSetting> it = sus.packages.iterator();
16375            while (it.hasNext()) {
16376                final PackageSetting ps = it.next();
16377                if (ps.pkg != null) {
16378                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16379                    if (v < vers) vers = v;
16380                }
16381            }
16382            return vers;
16383        } else if (obj instanceof PackageSetting) {
16384            final PackageSetting ps = (PackageSetting) obj;
16385            if (ps.pkg != null) {
16386                return ps.pkg.applicationInfo.targetSdkVersion;
16387            }
16388        }
16389        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16390    }
16391
16392    @Override
16393    public void addPreferredActivity(IntentFilter filter, int match,
16394            ComponentName[] set, ComponentName activity, int userId) {
16395        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16396                "Adding preferred");
16397    }
16398
16399    private void addPreferredActivityInternal(IntentFilter filter, int match,
16400            ComponentName[] set, ComponentName activity, boolean always, int userId,
16401            String opname) {
16402        // writer
16403        int callingUid = Binder.getCallingUid();
16404        enforceCrossUserPermission(callingUid, userId,
16405                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16406        if (filter.countActions() == 0) {
16407            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16408            return;
16409        }
16410        synchronized (mPackages) {
16411            if (mContext.checkCallingOrSelfPermission(
16412                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16413                    != PackageManager.PERMISSION_GRANTED) {
16414                if (getUidTargetSdkVersionLockedLPr(callingUid)
16415                        < Build.VERSION_CODES.FROYO) {
16416                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16417                            + callingUid);
16418                    return;
16419                }
16420                mContext.enforceCallingOrSelfPermission(
16421                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16422            }
16423
16424            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16425            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16426                    + userId + ":");
16427            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16428            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16429            scheduleWritePackageRestrictionsLocked(userId);
16430        }
16431    }
16432
16433    @Override
16434    public void replacePreferredActivity(IntentFilter filter, int match,
16435            ComponentName[] set, ComponentName activity, int userId) {
16436        if (filter.countActions() != 1) {
16437            throw new IllegalArgumentException(
16438                    "replacePreferredActivity expects filter to have only 1 action.");
16439        }
16440        if (filter.countDataAuthorities() != 0
16441                || filter.countDataPaths() != 0
16442                || filter.countDataSchemes() > 1
16443                || filter.countDataTypes() != 0) {
16444            throw new IllegalArgumentException(
16445                    "replacePreferredActivity expects filter to have no data authorities, " +
16446                    "paths, or types; and at most one scheme.");
16447        }
16448
16449        final int callingUid = Binder.getCallingUid();
16450        enforceCrossUserPermission(callingUid, userId,
16451                true /* requireFullPermission */, false /* checkShell */,
16452                "replace preferred activity");
16453        synchronized (mPackages) {
16454            if (mContext.checkCallingOrSelfPermission(
16455                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16456                    != PackageManager.PERMISSION_GRANTED) {
16457                if (getUidTargetSdkVersionLockedLPr(callingUid)
16458                        < Build.VERSION_CODES.FROYO) {
16459                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16460                            + Binder.getCallingUid());
16461                    return;
16462                }
16463                mContext.enforceCallingOrSelfPermission(
16464                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16465            }
16466
16467            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16468            if (pir != null) {
16469                // Get all of the existing entries that exactly match this filter.
16470                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16471                if (existing != null && existing.size() == 1) {
16472                    PreferredActivity cur = existing.get(0);
16473                    if (DEBUG_PREFERRED) {
16474                        Slog.i(TAG, "Checking replace of preferred:");
16475                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16476                        if (!cur.mPref.mAlways) {
16477                            Slog.i(TAG, "  -- CUR; not mAlways!");
16478                        } else {
16479                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16480                            Slog.i(TAG, "  -- CUR: mSet="
16481                                    + Arrays.toString(cur.mPref.mSetComponents));
16482                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16483                            Slog.i(TAG, "  -- NEW: mMatch="
16484                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16485                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16486                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16487                        }
16488                    }
16489                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16490                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16491                            && cur.mPref.sameSet(set)) {
16492                        // Setting the preferred activity to what it happens to be already
16493                        if (DEBUG_PREFERRED) {
16494                            Slog.i(TAG, "Replacing with same preferred activity "
16495                                    + cur.mPref.mShortComponent + " for user "
16496                                    + userId + ":");
16497                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16498                        }
16499                        return;
16500                    }
16501                }
16502
16503                if (existing != null) {
16504                    if (DEBUG_PREFERRED) {
16505                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16506                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16507                    }
16508                    for (int i = 0; i < existing.size(); i++) {
16509                        PreferredActivity pa = existing.get(i);
16510                        if (DEBUG_PREFERRED) {
16511                            Slog.i(TAG, "Removing existing preferred activity "
16512                                    + pa.mPref.mComponent + ":");
16513                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16514                        }
16515                        pir.removeFilter(pa);
16516                    }
16517                }
16518            }
16519            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16520                    "Replacing preferred");
16521        }
16522    }
16523
16524    @Override
16525    public void clearPackagePreferredActivities(String packageName) {
16526        final int uid = Binder.getCallingUid();
16527        // writer
16528        synchronized (mPackages) {
16529            PackageParser.Package pkg = mPackages.get(packageName);
16530            if (pkg == null || pkg.applicationInfo.uid != uid) {
16531                if (mContext.checkCallingOrSelfPermission(
16532                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16533                        != PackageManager.PERMISSION_GRANTED) {
16534                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16535                            < Build.VERSION_CODES.FROYO) {
16536                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16537                                + Binder.getCallingUid());
16538                        return;
16539                    }
16540                    mContext.enforceCallingOrSelfPermission(
16541                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16542                }
16543            }
16544
16545            int user = UserHandle.getCallingUserId();
16546            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16547                scheduleWritePackageRestrictionsLocked(user);
16548            }
16549        }
16550    }
16551
16552    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16553    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16554        ArrayList<PreferredActivity> removed = null;
16555        boolean changed = false;
16556        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16557            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16558            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16559            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16560                continue;
16561            }
16562            Iterator<PreferredActivity> it = pir.filterIterator();
16563            while (it.hasNext()) {
16564                PreferredActivity pa = it.next();
16565                // Mark entry for removal only if it matches the package name
16566                // and the entry is of type "always".
16567                if (packageName == null ||
16568                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16569                                && pa.mPref.mAlways)) {
16570                    if (removed == null) {
16571                        removed = new ArrayList<PreferredActivity>();
16572                    }
16573                    removed.add(pa);
16574                }
16575            }
16576            if (removed != null) {
16577                for (int j=0; j<removed.size(); j++) {
16578                    PreferredActivity pa = removed.get(j);
16579                    pir.removeFilter(pa);
16580                }
16581                changed = true;
16582            }
16583        }
16584        return changed;
16585    }
16586
16587    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16588    private void clearIntentFilterVerificationsLPw(int userId) {
16589        final int packageCount = mPackages.size();
16590        for (int i = 0; i < packageCount; i++) {
16591            PackageParser.Package pkg = mPackages.valueAt(i);
16592            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16593        }
16594    }
16595
16596    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16597    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16598        if (userId == UserHandle.USER_ALL) {
16599            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16600                    sUserManager.getUserIds())) {
16601                for (int oneUserId : sUserManager.getUserIds()) {
16602                    scheduleWritePackageRestrictionsLocked(oneUserId);
16603                }
16604            }
16605        } else {
16606            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16607                scheduleWritePackageRestrictionsLocked(userId);
16608            }
16609        }
16610    }
16611
16612    void clearDefaultBrowserIfNeeded(String packageName) {
16613        for (int oneUserId : sUserManager.getUserIds()) {
16614            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16615            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16616            if (packageName.equals(defaultBrowserPackageName)) {
16617                setDefaultBrowserPackageName(null, oneUserId);
16618            }
16619        }
16620    }
16621
16622    @Override
16623    public void resetApplicationPreferences(int userId) {
16624        mContext.enforceCallingOrSelfPermission(
16625                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16626        // writer
16627        synchronized (mPackages) {
16628            final long identity = Binder.clearCallingIdentity();
16629            try {
16630                clearPackagePreferredActivitiesLPw(null, userId);
16631                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16632                // TODO: We have to reset the default SMS and Phone. This requires
16633                // significant refactoring to keep all default apps in the package
16634                // manager (cleaner but more work) or have the services provide
16635                // callbacks to the package manager to request a default app reset.
16636                applyFactoryDefaultBrowserLPw(userId);
16637                clearIntentFilterVerificationsLPw(userId);
16638                primeDomainVerificationsLPw(userId);
16639                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16640                scheduleWritePackageRestrictionsLocked(userId);
16641            } finally {
16642                Binder.restoreCallingIdentity(identity);
16643            }
16644        }
16645    }
16646
16647    @Override
16648    public int getPreferredActivities(List<IntentFilter> outFilters,
16649            List<ComponentName> outActivities, String packageName) {
16650
16651        int num = 0;
16652        final int userId = UserHandle.getCallingUserId();
16653        // reader
16654        synchronized (mPackages) {
16655            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16656            if (pir != null) {
16657                final Iterator<PreferredActivity> it = pir.filterIterator();
16658                while (it.hasNext()) {
16659                    final PreferredActivity pa = it.next();
16660                    if (packageName == null
16661                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16662                                    && pa.mPref.mAlways)) {
16663                        if (outFilters != null) {
16664                            outFilters.add(new IntentFilter(pa));
16665                        }
16666                        if (outActivities != null) {
16667                            outActivities.add(pa.mPref.mComponent);
16668                        }
16669                    }
16670                }
16671            }
16672        }
16673
16674        return num;
16675    }
16676
16677    @Override
16678    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16679            int userId) {
16680        int callingUid = Binder.getCallingUid();
16681        if (callingUid != Process.SYSTEM_UID) {
16682            throw new SecurityException(
16683                    "addPersistentPreferredActivity can only be run by the system");
16684        }
16685        if (filter.countActions() == 0) {
16686            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16687            return;
16688        }
16689        synchronized (mPackages) {
16690            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16691                    ":");
16692            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16693            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16694                    new PersistentPreferredActivity(filter, activity));
16695            scheduleWritePackageRestrictionsLocked(userId);
16696        }
16697    }
16698
16699    @Override
16700    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16701        int callingUid = Binder.getCallingUid();
16702        if (callingUid != Process.SYSTEM_UID) {
16703            throw new SecurityException(
16704                    "clearPackagePersistentPreferredActivities can only be run by the system");
16705        }
16706        ArrayList<PersistentPreferredActivity> removed = null;
16707        boolean changed = false;
16708        synchronized (mPackages) {
16709            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16710                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16711                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16712                        .valueAt(i);
16713                if (userId != thisUserId) {
16714                    continue;
16715                }
16716                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16717                while (it.hasNext()) {
16718                    PersistentPreferredActivity ppa = it.next();
16719                    // Mark entry for removal only if it matches the package name.
16720                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16721                        if (removed == null) {
16722                            removed = new ArrayList<PersistentPreferredActivity>();
16723                        }
16724                        removed.add(ppa);
16725                    }
16726                }
16727                if (removed != null) {
16728                    for (int j=0; j<removed.size(); j++) {
16729                        PersistentPreferredActivity ppa = removed.get(j);
16730                        ppir.removeFilter(ppa);
16731                    }
16732                    changed = true;
16733                }
16734            }
16735
16736            if (changed) {
16737                scheduleWritePackageRestrictionsLocked(userId);
16738            }
16739        }
16740    }
16741
16742    /**
16743     * Common machinery for picking apart a restored XML blob and passing
16744     * it to a caller-supplied functor to be applied to the running system.
16745     */
16746    private void restoreFromXml(XmlPullParser parser, int userId,
16747            String expectedStartTag, BlobXmlRestorer functor)
16748            throws IOException, XmlPullParserException {
16749        int type;
16750        while ((type = parser.next()) != XmlPullParser.START_TAG
16751                && type != XmlPullParser.END_DOCUMENT) {
16752        }
16753        if (type != XmlPullParser.START_TAG) {
16754            // oops didn't find a start tag?!
16755            if (DEBUG_BACKUP) {
16756                Slog.e(TAG, "Didn't find start tag during restore");
16757            }
16758            return;
16759        }
16760Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16761        // this is supposed to be TAG_PREFERRED_BACKUP
16762        if (!expectedStartTag.equals(parser.getName())) {
16763            if (DEBUG_BACKUP) {
16764                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16765            }
16766            return;
16767        }
16768
16769        // skip interfering stuff, then we're aligned with the backing implementation
16770        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16771Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16772        functor.apply(parser, userId);
16773    }
16774
16775    private interface BlobXmlRestorer {
16776        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16777    }
16778
16779    /**
16780     * Non-Binder method, support for the backup/restore mechanism: write the
16781     * full set of preferred activities in its canonical XML format.  Returns the
16782     * XML output as a byte array, or null if there is none.
16783     */
16784    @Override
16785    public byte[] getPreferredActivityBackup(int userId) {
16786        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16787            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16788        }
16789
16790        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16791        try {
16792            final XmlSerializer serializer = new FastXmlSerializer();
16793            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16794            serializer.startDocument(null, true);
16795            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16796
16797            synchronized (mPackages) {
16798                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16799            }
16800
16801            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16802            serializer.endDocument();
16803            serializer.flush();
16804        } catch (Exception e) {
16805            if (DEBUG_BACKUP) {
16806                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16807            }
16808            return null;
16809        }
16810
16811        return dataStream.toByteArray();
16812    }
16813
16814    @Override
16815    public void restorePreferredActivities(byte[] backup, int userId) {
16816        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16817            throw new SecurityException("Only the system may call restorePreferredActivities()");
16818        }
16819
16820        try {
16821            final XmlPullParser parser = Xml.newPullParser();
16822            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16823            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16824                    new BlobXmlRestorer() {
16825                        @Override
16826                        public void apply(XmlPullParser parser, int userId)
16827                                throws XmlPullParserException, IOException {
16828                            synchronized (mPackages) {
16829                                mSettings.readPreferredActivitiesLPw(parser, userId);
16830                            }
16831                        }
16832                    } );
16833        } catch (Exception e) {
16834            if (DEBUG_BACKUP) {
16835                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16836            }
16837        }
16838    }
16839
16840    /**
16841     * Non-Binder method, support for the backup/restore mechanism: write the
16842     * default browser (etc) settings in its canonical XML format.  Returns the default
16843     * browser XML representation as a byte array, or null if there is none.
16844     */
16845    @Override
16846    public byte[] getDefaultAppsBackup(int userId) {
16847        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16848            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16849        }
16850
16851        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16852        try {
16853            final XmlSerializer serializer = new FastXmlSerializer();
16854            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16855            serializer.startDocument(null, true);
16856            serializer.startTag(null, TAG_DEFAULT_APPS);
16857
16858            synchronized (mPackages) {
16859                mSettings.writeDefaultAppsLPr(serializer, userId);
16860            }
16861
16862            serializer.endTag(null, TAG_DEFAULT_APPS);
16863            serializer.endDocument();
16864            serializer.flush();
16865        } catch (Exception e) {
16866            if (DEBUG_BACKUP) {
16867                Slog.e(TAG, "Unable to write default apps for backup", e);
16868            }
16869            return null;
16870        }
16871
16872        return dataStream.toByteArray();
16873    }
16874
16875    @Override
16876    public void restoreDefaultApps(byte[] backup, int userId) {
16877        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16878            throw new SecurityException("Only the system may call restoreDefaultApps()");
16879        }
16880
16881        try {
16882            final XmlPullParser parser = Xml.newPullParser();
16883            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16884            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16885                    new BlobXmlRestorer() {
16886                        @Override
16887                        public void apply(XmlPullParser parser, int userId)
16888                                throws XmlPullParserException, IOException {
16889                            synchronized (mPackages) {
16890                                mSettings.readDefaultAppsLPw(parser, userId);
16891                            }
16892                        }
16893                    } );
16894        } catch (Exception e) {
16895            if (DEBUG_BACKUP) {
16896                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16897            }
16898        }
16899    }
16900
16901    @Override
16902    public byte[] getIntentFilterVerificationBackup(int userId) {
16903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16904            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16905        }
16906
16907        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16908        try {
16909            final XmlSerializer serializer = new FastXmlSerializer();
16910            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16911            serializer.startDocument(null, true);
16912            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16913
16914            synchronized (mPackages) {
16915                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16916            }
16917
16918            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16919            serializer.endDocument();
16920            serializer.flush();
16921        } catch (Exception e) {
16922            if (DEBUG_BACKUP) {
16923                Slog.e(TAG, "Unable to write default apps for backup", e);
16924            }
16925            return null;
16926        }
16927
16928        return dataStream.toByteArray();
16929    }
16930
16931    @Override
16932    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16933        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16934            throw new SecurityException("Only the system may call restorePreferredActivities()");
16935        }
16936
16937        try {
16938            final XmlPullParser parser = Xml.newPullParser();
16939            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16940            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16941                    new BlobXmlRestorer() {
16942                        @Override
16943                        public void apply(XmlPullParser parser, int userId)
16944                                throws XmlPullParserException, IOException {
16945                            synchronized (mPackages) {
16946                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16947                                mSettings.writeLPr();
16948                            }
16949                        }
16950                    } );
16951        } catch (Exception e) {
16952            if (DEBUG_BACKUP) {
16953                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16954            }
16955        }
16956    }
16957
16958    @Override
16959    public byte[] getPermissionGrantBackup(int userId) {
16960        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16961            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16962        }
16963
16964        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16965        try {
16966            final XmlSerializer serializer = new FastXmlSerializer();
16967            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16968            serializer.startDocument(null, true);
16969            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16970
16971            synchronized (mPackages) {
16972                serializeRuntimePermissionGrantsLPr(serializer, userId);
16973            }
16974
16975            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16976            serializer.endDocument();
16977            serializer.flush();
16978        } catch (Exception e) {
16979            if (DEBUG_BACKUP) {
16980                Slog.e(TAG, "Unable to write default apps for backup", e);
16981            }
16982            return null;
16983        }
16984
16985        return dataStream.toByteArray();
16986    }
16987
16988    @Override
16989    public void restorePermissionGrants(byte[] backup, int userId) {
16990        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16991            throw new SecurityException("Only the system may call restorePermissionGrants()");
16992        }
16993
16994        try {
16995            final XmlPullParser parser = Xml.newPullParser();
16996            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16997            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16998                    new BlobXmlRestorer() {
16999                        @Override
17000                        public void apply(XmlPullParser parser, int userId)
17001                                throws XmlPullParserException, IOException {
17002                            synchronized (mPackages) {
17003                                processRestoredPermissionGrantsLPr(parser, userId);
17004                            }
17005                        }
17006                    } );
17007        } catch (Exception e) {
17008            if (DEBUG_BACKUP) {
17009                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17010            }
17011        }
17012    }
17013
17014    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17015            throws IOException {
17016        serializer.startTag(null, TAG_ALL_GRANTS);
17017
17018        final int N = mSettings.mPackages.size();
17019        for (int i = 0; i < N; i++) {
17020            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17021            boolean pkgGrantsKnown = false;
17022
17023            PermissionsState packagePerms = ps.getPermissionsState();
17024
17025            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17026                final int grantFlags = state.getFlags();
17027                // only look at grants that are not system/policy fixed
17028                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17029                    final boolean isGranted = state.isGranted();
17030                    // And only back up the user-twiddled state bits
17031                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17032                        final String packageName = mSettings.mPackages.keyAt(i);
17033                        if (!pkgGrantsKnown) {
17034                            serializer.startTag(null, TAG_GRANT);
17035                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17036                            pkgGrantsKnown = true;
17037                        }
17038
17039                        final boolean userSet =
17040                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17041                        final boolean userFixed =
17042                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17043                        final boolean revoke =
17044                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17045
17046                        serializer.startTag(null, TAG_PERMISSION);
17047                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17048                        if (isGranted) {
17049                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17050                        }
17051                        if (userSet) {
17052                            serializer.attribute(null, ATTR_USER_SET, "true");
17053                        }
17054                        if (userFixed) {
17055                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17056                        }
17057                        if (revoke) {
17058                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17059                        }
17060                        serializer.endTag(null, TAG_PERMISSION);
17061                    }
17062                }
17063            }
17064
17065            if (pkgGrantsKnown) {
17066                serializer.endTag(null, TAG_GRANT);
17067            }
17068        }
17069
17070        serializer.endTag(null, TAG_ALL_GRANTS);
17071    }
17072
17073    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17074            throws XmlPullParserException, IOException {
17075        String pkgName = null;
17076        int outerDepth = parser.getDepth();
17077        int type;
17078        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17079                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17080            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17081                continue;
17082            }
17083
17084            final String tagName = parser.getName();
17085            if (tagName.equals(TAG_GRANT)) {
17086                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17087                if (DEBUG_BACKUP) {
17088                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17089                }
17090            } else if (tagName.equals(TAG_PERMISSION)) {
17091
17092                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17093                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17094
17095                int newFlagSet = 0;
17096                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17097                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17098                }
17099                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17100                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17101                }
17102                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17103                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17104                }
17105                if (DEBUG_BACKUP) {
17106                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17107                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17108                }
17109                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17110                if (ps != null) {
17111                    // Already installed so we apply the grant immediately
17112                    if (DEBUG_BACKUP) {
17113                        Slog.v(TAG, "        + already installed; applying");
17114                    }
17115                    PermissionsState perms = ps.getPermissionsState();
17116                    BasePermission bp = mSettings.mPermissions.get(permName);
17117                    if (bp != null) {
17118                        if (isGranted) {
17119                            perms.grantRuntimePermission(bp, userId);
17120                        }
17121                        if (newFlagSet != 0) {
17122                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17123                        }
17124                    }
17125                } else {
17126                    // Need to wait for post-restore install to apply the grant
17127                    if (DEBUG_BACKUP) {
17128                        Slog.v(TAG, "        - not yet installed; saving for later");
17129                    }
17130                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17131                            isGranted, newFlagSet, userId);
17132                }
17133            } else {
17134                PackageManagerService.reportSettingsProblem(Log.WARN,
17135                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17136                XmlUtils.skipCurrentTag(parser);
17137            }
17138        }
17139
17140        scheduleWriteSettingsLocked();
17141        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17142    }
17143
17144    @Override
17145    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17146            int sourceUserId, int targetUserId, int flags) {
17147        mContext.enforceCallingOrSelfPermission(
17148                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17149        int callingUid = Binder.getCallingUid();
17150        enforceOwnerRights(ownerPackage, callingUid);
17151        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17152        if (intentFilter.countActions() == 0) {
17153            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17154            return;
17155        }
17156        synchronized (mPackages) {
17157            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17158                    ownerPackage, targetUserId, flags);
17159            CrossProfileIntentResolver resolver =
17160                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17161            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17162            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17163            if (existing != null) {
17164                int size = existing.size();
17165                for (int i = 0; i < size; i++) {
17166                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17167                        return;
17168                    }
17169                }
17170            }
17171            resolver.addFilter(newFilter);
17172            scheduleWritePackageRestrictionsLocked(sourceUserId);
17173        }
17174    }
17175
17176    @Override
17177    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17178        mContext.enforceCallingOrSelfPermission(
17179                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17180        int callingUid = Binder.getCallingUid();
17181        enforceOwnerRights(ownerPackage, callingUid);
17182        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17183        synchronized (mPackages) {
17184            CrossProfileIntentResolver resolver =
17185                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17186            ArraySet<CrossProfileIntentFilter> set =
17187                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17188            for (CrossProfileIntentFilter filter : set) {
17189                if (filter.getOwnerPackage().equals(ownerPackage)) {
17190                    resolver.removeFilter(filter);
17191                }
17192            }
17193            scheduleWritePackageRestrictionsLocked(sourceUserId);
17194        }
17195    }
17196
17197    // Enforcing that callingUid is owning pkg on userId
17198    private void enforceOwnerRights(String pkg, int callingUid) {
17199        // The system owns everything.
17200        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17201            return;
17202        }
17203        int callingUserId = UserHandle.getUserId(callingUid);
17204        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17205        if (pi == null) {
17206            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17207                    + callingUserId);
17208        }
17209        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17210            throw new SecurityException("Calling uid " + callingUid
17211                    + " does not own package " + pkg);
17212        }
17213    }
17214
17215    @Override
17216    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17217        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17218    }
17219
17220    private Intent getHomeIntent() {
17221        Intent intent = new Intent(Intent.ACTION_MAIN);
17222        intent.addCategory(Intent.CATEGORY_HOME);
17223        return intent;
17224    }
17225
17226    private IntentFilter getHomeFilter() {
17227        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17228        filter.addCategory(Intent.CATEGORY_HOME);
17229        filter.addCategory(Intent.CATEGORY_DEFAULT);
17230        return filter;
17231    }
17232
17233    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17234            int userId) {
17235        Intent intent  = getHomeIntent();
17236        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17237                PackageManager.GET_META_DATA, userId);
17238        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17239                true, false, false, userId);
17240
17241        allHomeCandidates.clear();
17242        if (list != null) {
17243            for (ResolveInfo ri : list) {
17244                allHomeCandidates.add(ri);
17245            }
17246        }
17247        return (preferred == null || preferred.activityInfo == null)
17248                ? null
17249                : new ComponentName(preferred.activityInfo.packageName,
17250                        preferred.activityInfo.name);
17251    }
17252
17253    @Override
17254    public void setHomeActivity(ComponentName comp, int userId) {
17255        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17256        getHomeActivitiesAsUser(homeActivities, userId);
17257
17258        boolean found = false;
17259
17260        final int size = homeActivities.size();
17261        final ComponentName[] set = new ComponentName[size];
17262        for (int i = 0; i < size; i++) {
17263            final ResolveInfo candidate = homeActivities.get(i);
17264            final ActivityInfo info = candidate.activityInfo;
17265            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17266            set[i] = activityName;
17267            if (!found && activityName.equals(comp)) {
17268                found = true;
17269            }
17270        }
17271        if (!found) {
17272            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17273                    + userId);
17274        }
17275        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17276                set, comp, userId);
17277    }
17278
17279    private @Nullable String getSetupWizardPackageName() {
17280        final Intent intent = new Intent(Intent.ACTION_MAIN);
17281        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17282
17283        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17284                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17285                        | MATCH_DISABLED_COMPONENTS,
17286                UserHandle.myUserId());
17287        if (matches.size() == 1) {
17288            return matches.get(0).getComponentInfo().packageName;
17289        } else {
17290            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17291                    + ": matches=" + matches);
17292            return null;
17293        }
17294    }
17295
17296    @Override
17297    public void setApplicationEnabledSetting(String appPackageName,
17298            int newState, int flags, int userId, String callingPackage) {
17299        if (!sUserManager.exists(userId)) return;
17300        if (callingPackage == null) {
17301            callingPackage = Integer.toString(Binder.getCallingUid());
17302        }
17303        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17304    }
17305
17306    @Override
17307    public void setComponentEnabledSetting(ComponentName componentName,
17308            int newState, int flags, int userId) {
17309        if (!sUserManager.exists(userId)) return;
17310        setEnabledSetting(componentName.getPackageName(),
17311                componentName.getClassName(), newState, flags, userId, null);
17312    }
17313
17314    private void setEnabledSetting(final String packageName, String className, int newState,
17315            final int flags, int userId, String callingPackage) {
17316        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17317              || newState == COMPONENT_ENABLED_STATE_ENABLED
17318              || newState == COMPONENT_ENABLED_STATE_DISABLED
17319              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17320              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17321            throw new IllegalArgumentException("Invalid new component state: "
17322                    + newState);
17323        }
17324        PackageSetting pkgSetting;
17325        final int uid = Binder.getCallingUid();
17326        final int permission;
17327        if (uid == Process.SYSTEM_UID) {
17328            permission = PackageManager.PERMISSION_GRANTED;
17329        } else {
17330            permission = mContext.checkCallingOrSelfPermission(
17331                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17332        }
17333        enforceCrossUserPermission(uid, userId,
17334                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17335        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17336        boolean sendNow = false;
17337        boolean isApp = (className == null);
17338        String componentName = isApp ? packageName : className;
17339        int packageUid = -1;
17340        ArrayList<String> components;
17341
17342        // writer
17343        synchronized (mPackages) {
17344            pkgSetting = mSettings.mPackages.get(packageName);
17345            if (pkgSetting == null) {
17346                if (className == null) {
17347                    throw new IllegalArgumentException("Unknown package: " + packageName);
17348                }
17349                throw new IllegalArgumentException(
17350                        "Unknown component: " + packageName + "/" + className);
17351            }
17352            // Allow root and verify that userId is not being specified by a different user
17353            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17354                throw new SecurityException(
17355                        "Permission Denial: attempt to change component state from pid="
17356                        + Binder.getCallingPid()
17357                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17358            }
17359            if (className == null) {
17360                // We're dealing with an application/package level state change
17361                if (pkgSetting.getEnabled(userId) == newState) {
17362                    // Nothing to do
17363                    return;
17364                }
17365                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17366                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17367                    // Don't care about who enables an app.
17368                    callingPackage = null;
17369                }
17370                pkgSetting.setEnabled(newState, userId, callingPackage);
17371                // pkgSetting.pkg.mSetEnabled = newState;
17372            } else {
17373                // We're dealing with a component level state change
17374                // First, verify that this is a valid class name.
17375                PackageParser.Package pkg = pkgSetting.pkg;
17376                if (pkg == null || !pkg.hasComponentClassName(className)) {
17377                    if (pkg != null &&
17378                            pkg.applicationInfo.targetSdkVersion >=
17379                                    Build.VERSION_CODES.JELLY_BEAN) {
17380                        throw new IllegalArgumentException("Component class " + className
17381                                + " does not exist in " + packageName);
17382                    } else {
17383                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17384                                + className + " does not exist in " + packageName);
17385                    }
17386                }
17387                switch (newState) {
17388                case COMPONENT_ENABLED_STATE_ENABLED:
17389                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17390                        return;
17391                    }
17392                    break;
17393                case COMPONENT_ENABLED_STATE_DISABLED:
17394                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17395                        return;
17396                    }
17397                    break;
17398                case COMPONENT_ENABLED_STATE_DEFAULT:
17399                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17400                        return;
17401                    }
17402                    break;
17403                default:
17404                    Slog.e(TAG, "Invalid new component state: " + newState);
17405                    return;
17406                }
17407            }
17408            scheduleWritePackageRestrictionsLocked(userId);
17409            components = mPendingBroadcasts.get(userId, packageName);
17410            final boolean newPackage = components == null;
17411            if (newPackage) {
17412                components = new ArrayList<String>();
17413            }
17414            if (!components.contains(componentName)) {
17415                components.add(componentName);
17416            }
17417            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17418                sendNow = true;
17419                // Purge entry from pending broadcast list if another one exists already
17420                // since we are sending one right away.
17421                mPendingBroadcasts.remove(userId, packageName);
17422            } else {
17423                if (newPackage) {
17424                    mPendingBroadcasts.put(userId, packageName, components);
17425                }
17426                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17427                    // Schedule a message
17428                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17429                }
17430            }
17431        }
17432
17433        long callingId = Binder.clearCallingIdentity();
17434        try {
17435            if (sendNow) {
17436                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17437                sendPackageChangedBroadcast(packageName,
17438                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17439            }
17440        } finally {
17441            Binder.restoreCallingIdentity(callingId);
17442        }
17443    }
17444
17445    @Override
17446    public void flushPackageRestrictionsAsUser(int userId) {
17447        if (!sUserManager.exists(userId)) {
17448            return;
17449        }
17450        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17451                false /* checkShell */, "flushPackageRestrictions");
17452        synchronized (mPackages) {
17453            mSettings.writePackageRestrictionsLPr(userId);
17454            mDirtyUsers.remove(userId);
17455            if (mDirtyUsers.isEmpty()) {
17456                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17457            }
17458        }
17459    }
17460
17461    private void sendPackageChangedBroadcast(String packageName,
17462            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17463        if (DEBUG_INSTALL)
17464            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17465                    + componentNames);
17466        Bundle extras = new Bundle(4);
17467        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17468        String nameList[] = new String[componentNames.size()];
17469        componentNames.toArray(nameList);
17470        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17471        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17472        extras.putInt(Intent.EXTRA_UID, packageUid);
17473        // If this is not reporting a change of the overall package, then only send it
17474        // to registered receivers.  We don't want to launch a swath of apps for every
17475        // little component state change.
17476        final int flags = !componentNames.contains(packageName)
17477                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17478        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17479                new int[] {UserHandle.getUserId(packageUid)});
17480    }
17481
17482    @Override
17483    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17484        if (!sUserManager.exists(userId)) return;
17485        final int uid = Binder.getCallingUid();
17486        final int permission = mContext.checkCallingOrSelfPermission(
17487                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17488        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17489        enforceCrossUserPermission(uid, userId,
17490                true /* requireFullPermission */, true /* checkShell */, "stop package");
17491        // writer
17492        synchronized (mPackages) {
17493            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17494                    allowedByPermission, uid, userId)) {
17495                scheduleWritePackageRestrictionsLocked(userId);
17496            }
17497        }
17498    }
17499
17500    @Override
17501    public String getInstallerPackageName(String packageName) {
17502        // reader
17503        synchronized (mPackages) {
17504            return mSettings.getInstallerPackageNameLPr(packageName);
17505        }
17506    }
17507
17508    @Override
17509    public int getApplicationEnabledSetting(String packageName, int userId) {
17510        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17511        int uid = Binder.getCallingUid();
17512        enforceCrossUserPermission(uid, userId,
17513                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17514        // reader
17515        synchronized (mPackages) {
17516            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17517        }
17518    }
17519
17520    @Override
17521    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17522        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17523        int uid = Binder.getCallingUid();
17524        enforceCrossUserPermission(uid, userId,
17525                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17526        // reader
17527        synchronized (mPackages) {
17528            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17529        }
17530    }
17531
17532    @Override
17533    public void enterSafeMode() {
17534        enforceSystemOrRoot("Only the system can request entering safe mode");
17535
17536        if (!mSystemReady) {
17537            mSafeMode = true;
17538        }
17539    }
17540
17541    @Override
17542    public void systemReady() {
17543        mSystemReady = true;
17544
17545        // Read the compatibilty setting when the system is ready.
17546        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17547                mContext.getContentResolver(),
17548                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17549        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17550        if (DEBUG_SETTINGS) {
17551            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17552        }
17553
17554        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17555
17556        synchronized (mPackages) {
17557            // Verify that all of the preferred activity components actually
17558            // exist.  It is possible for applications to be updated and at
17559            // that point remove a previously declared activity component that
17560            // had been set as a preferred activity.  We try to clean this up
17561            // the next time we encounter that preferred activity, but it is
17562            // possible for the user flow to never be able to return to that
17563            // situation so here we do a sanity check to make sure we haven't
17564            // left any junk around.
17565            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17566            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17567                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17568                removed.clear();
17569                for (PreferredActivity pa : pir.filterSet()) {
17570                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17571                        removed.add(pa);
17572                    }
17573                }
17574                if (removed.size() > 0) {
17575                    for (int r=0; r<removed.size(); r++) {
17576                        PreferredActivity pa = removed.get(r);
17577                        Slog.w(TAG, "Removing dangling preferred activity: "
17578                                + pa.mPref.mComponent);
17579                        pir.removeFilter(pa);
17580                    }
17581                    mSettings.writePackageRestrictionsLPr(
17582                            mSettings.mPreferredActivities.keyAt(i));
17583                }
17584            }
17585
17586            for (int userId : UserManagerService.getInstance().getUserIds()) {
17587                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17588                    grantPermissionsUserIds = ArrayUtils.appendInt(
17589                            grantPermissionsUserIds, userId);
17590                }
17591            }
17592        }
17593        sUserManager.systemReady();
17594
17595        // If we upgraded grant all default permissions before kicking off.
17596        for (int userId : grantPermissionsUserIds) {
17597            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17598        }
17599
17600        // Kick off any messages waiting for system ready
17601        if (mPostSystemReadyMessages != null) {
17602            for (Message msg : mPostSystemReadyMessages) {
17603                msg.sendToTarget();
17604            }
17605            mPostSystemReadyMessages = null;
17606        }
17607
17608        // Watch for external volumes that come and go over time
17609        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17610        storage.registerListener(mStorageListener);
17611
17612        mInstallerService.systemReady();
17613        mPackageDexOptimizer.systemReady();
17614
17615        MountServiceInternal mountServiceInternal = LocalServices.getService(
17616                MountServiceInternal.class);
17617        mountServiceInternal.addExternalStoragePolicy(
17618                new MountServiceInternal.ExternalStorageMountPolicy() {
17619            @Override
17620            public int getMountMode(int uid, String packageName) {
17621                if (Process.isIsolated(uid)) {
17622                    return Zygote.MOUNT_EXTERNAL_NONE;
17623                }
17624                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17625                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17626                }
17627                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17628                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17629                }
17630                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17631                    return Zygote.MOUNT_EXTERNAL_READ;
17632                }
17633                return Zygote.MOUNT_EXTERNAL_WRITE;
17634            }
17635
17636            @Override
17637            public boolean hasExternalStorage(int uid, String packageName) {
17638                return true;
17639            }
17640        });
17641
17642        // Now that we're mostly running, clean up stale users and apps
17643        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17644        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17645    }
17646
17647    @Override
17648    public boolean isSafeMode() {
17649        return mSafeMode;
17650    }
17651
17652    @Override
17653    public boolean hasSystemUidErrors() {
17654        return mHasSystemUidErrors;
17655    }
17656
17657    static String arrayToString(int[] array) {
17658        StringBuffer buf = new StringBuffer(128);
17659        buf.append('[');
17660        if (array != null) {
17661            for (int i=0; i<array.length; i++) {
17662                if (i > 0) buf.append(", ");
17663                buf.append(array[i]);
17664            }
17665        }
17666        buf.append(']');
17667        return buf.toString();
17668    }
17669
17670    static class DumpState {
17671        public static final int DUMP_LIBS = 1 << 0;
17672        public static final int DUMP_FEATURES = 1 << 1;
17673        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17674        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17675        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17676        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17677        public static final int DUMP_PERMISSIONS = 1 << 6;
17678        public static final int DUMP_PACKAGES = 1 << 7;
17679        public static final int DUMP_SHARED_USERS = 1 << 8;
17680        public static final int DUMP_MESSAGES = 1 << 9;
17681        public static final int DUMP_PROVIDERS = 1 << 10;
17682        public static final int DUMP_VERIFIERS = 1 << 11;
17683        public static final int DUMP_PREFERRED = 1 << 12;
17684        public static final int DUMP_PREFERRED_XML = 1 << 13;
17685        public static final int DUMP_KEYSETS = 1 << 14;
17686        public static final int DUMP_VERSION = 1 << 15;
17687        public static final int DUMP_INSTALLS = 1 << 16;
17688        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17689        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17690        public static final int DUMP_FROZEN = 1 << 19;
17691
17692        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17693
17694        private int mTypes;
17695
17696        private int mOptions;
17697
17698        private boolean mTitlePrinted;
17699
17700        private SharedUserSetting mSharedUser;
17701
17702        public boolean isDumping(int type) {
17703            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17704                return true;
17705            }
17706
17707            return (mTypes & type) != 0;
17708        }
17709
17710        public void setDump(int type) {
17711            mTypes |= type;
17712        }
17713
17714        public boolean isOptionEnabled(int option) {
17715            return (mOptions & option) != 0;
17716        }
17717
17718        public void setOptionEnabled(int option) {
17719            mOptions |= option;
17720        }
17721
17722        public boolean onTitlePrinted() {
17723            final boolean printed = mTitlePrinted;
17724            mTitlePrinted = true;
17725            return printed;
17726        }
17727
17728        public boolean getTitlePrinted() {
17729            return mTitlePrinted;
17730        }
17731
17732        public void setTitlePrinted(boolean enabled) {
17733            mTitlePrinted = enabled;
17734        }
17735
17736        public SharedUserSetting getSharedUser() {
17737            return mSharedUser;
17738        }
17739
17740        public void setSharedUser(SharedUserSetting user) {
17741            mSharedUser = user;
17742        }
17743    }
17744
17745    @Override
17746    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17747            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17748        (new PackageManagerShellCommand(this)).exec(
17749                this, in, out, err, args, resultReceiver);
17750    }
17751
17752    @Override
17753    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17754        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17755                != PackageManager.PERMISSION_GRANTED) {
17756            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17757                    + Binder.getCallingPid()
17758                    + ", uid=" + Binder.getCallingUid()
17759                    + " without permission "
17760                    + android.Manifest.permission.DUMP);
17761            return;
17762        }
17763
17764        DumpState dumpState = new DumpState();
17765        boolean fullPreferred = false;
17766        boolean checkin = false;
17767
17768        String packageName = null;
17769        ArraySet<String> permissionNames = null;
17770
17771        int opti = 0;
17772        while (opti < args.length) {
17773            String opt = args[opti];
17774            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17775                break;
17776            }
17777            opti++;
17778
17779            if ("-a".equals(opt)) {
17780                // Right now we only know how to print all.
17781            } else if ("-h".equals(opt)) {
17782                pw.println("Package manager dump options:");
17783                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17784                pw.println("    --checkin: dump for a checkin");
17785                pw.println("    -f: print details of intent filters");
17786                pw.println("    -h: print this help");
17787                pw.println("  cmd may be one of:");
17788                pw.println("    l[ibraries]: list known shared libraries");
17789                pw.println("    f[eatures]: list device features");
17790                pw.println("    k[eysets]: print known keysets");
17791                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17792                pw.println("    perm[issions]: dump permissions");
17793                pw.println("    permission [name ...]: dump declaration and use of given permission");
17794                pw.println("    pref[erred]: print preferred package settings");
17795                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17796                pw.println("    prov[iders]: dump content providers");
17797                pw.println("    p[ackages]: dump installed packages");
17798                pw.println("    s[hared-users]: dump shared user IDs");
17799                pw.println("    m[essages]: print collected runtime messages");
17800                pw.println("    v[erifiers]: print package verifier info");
17801                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17802                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17803                pw.println("    version: print database version info");
17804                pw.println("    write: write current settings now");
17805                pw.println("    installs: details about install sessions");
17806                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17807                pw.println("    <package.name>: info about given package");
17808                return;
17809            } else if ("--checkin".equals(opt)) {
17810                checkin = true;
17811            } else if ("-f".equals(opt)) {
17812                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17813            } else {
17814                pw.println("Unknown argument: " + opt + "; use -h for help");
17815            }
17816        }
17817
17818        // Is the caller requesting to dump a particular piece of data?
17819        if (opti < args.length) {
17820            String cmd = args[opti];
17821            opti++;
17822            // Is this a package name?
17823            if ("android".equals(cmd) || cmd.contains(".")) {
17824                packageName = cmd;
17825                // When dumping a single package, we always dump all of its
17826                // filter information since the amount of data will be reasonable.
17827                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17828            } else if ("check-permission".equals(cmd)) {
17829                if (opti >= args.length) {
17830                    pw.println("Error: check-permission missing permission argument");
17831                    return;
17832                }
17833                String perm = args[opti];
17834                opti++;
17835                if (opti >= args.length) {
17836                    pw.println("Error: check-permission missing package argument");
17837                    return;
17838                }
17839                String pkg = args[opti];
17840                opti++;
17841                int user = UserHandle.getUserId(Binder.getCallingUid());
17842                if (opti < args.length) {
17843                    try {
17844                        user = Integer.parseInt(args[opti]);
17845                    } catch (NumberFormatException e) {
17846                        pw.println("Error: check-permission user argument is not a number: "
17847                                + args[opti]);
17848                        return;
17849                    }
17850                }
17851                pw.println(checkPermission(perm, pkg, user));
17852                return;
17853            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17854                dumpState.setDump(DumpState.DUMP_LIBS);
17855            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17856                dumpState.setDump(DumpState.DUMP_FEATURES);
17857            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17858                if (opti >= args.length) {
17859                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17860                            | DumpState.DUMP_SERVICE_RESOLVERS
17861                            | DumpState.DUMP_RECEIVER_RESOLVERS
17862                            | DumpState.DUMP_CONTENT_RESOLVERS);
17863                } else {
17864                    while (opti < args.length) {
17865                        String name = args[opti];
17866                        if ("a".equals(name) || "activity".equals(name)) {
17867                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17868                        } else if ("s".equals(name) || "service".equals(name)) {
17869                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17870                        } else if ("r".equals(name) || "receiver".equals(name)) {
17871                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17872                        } else if ("c".equals(name) || "content".equals(name)) {
17873                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17874                        } else {
17875                            pw.println("Error: unknown resolver table type: " + name);
17876                            return;
17877                        }
17878                        opti++;
17879                    }
17880                }
17881            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17882                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17883            } else if ("permission".equals(cmd)) {
17884                if (opti >= args.length) {
17885                    pw.println("Error: permission requires permission name");
17886                    return;
17887                }
17888                permissionNames = new ArraySet<>();
17889                while (opti < args.length) {
17890                    permissionNames.add(args[opti]);
17891                    opti++;
17892                }
17893                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17894                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17895            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17896                dumpState.setDump(DumpState.DUMP_PREFERRED);
17897            } else if ("preferred-xml".equals(cmd)) {
17898                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17899                if (opti < args.length && "--full".equals(args[opti])) {
17900                    fullPreferred = true;
17901                    opti++;
17902                }
17903            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17904                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17905            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17906                dumpState.setDump(DumpState.DUMP_PACKAGES);
17907            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17908                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17909            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17910                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17911            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17912                dumpState.setDump(DumpState.DUMP_MESSAGES);
17913            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17914                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17915            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17916                    || "intent-filter-verifiers".equals(cmd)) {
17917                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17918            } else if ("version".equals(cmd)) {
17919                dumpState.setDump(DumpState.DUMP_VERSION);
17920            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17921                dumpState.setDump(DumpState.DUMP_KEYSETS);
17922            } else if ("installs".equals(cmd)) {
17923                dumpState.setDump(DumpState.DUMP_INSTALLS);
17924            } else if ("frozen".equals(cmd)) {
17925                dumpState.setDump(DumpState.DUMP_FROZEN);
17926            } else if ("write".equals(cmd)) {
17927                synchronized (mPackages) {
17928                    mSettings.writeLPr();
17929                    pw.println("Settings written.");
17930                    return;
17931                }
17932            }
17933        }
17934
17935        if (checkin) {
17936            pw.println("vers,1");
17937        }
17938
17939        // reader
17940        synchronized (mPackages) {
17941            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17942                if (!checkin) {
17943                    if (dumpState.onTitlePrinted())
17944                        pw.println();
17945                    pw.println("Database versions:");
17946                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17947                }
17948            }
17949
17950            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17951                if (!checkin) {
17952                    if (dumpState.onTitlePrinted())
17953                        pw.println();
17954                    pw.println("Verifiers:");
17955                    pw.print("  Required: ");
17956                    pw.print(mRequiredVerifierPackage);
17957                    pw.print(" (uid=");
17958                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17959                            UserHandle.USER_SYSTEM));
17960                    pw.println(")");
17961                } else if (mRequiredVerifierPackage != null) {
17962                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17963                    pw.print(",");
17964                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17965                            UserHandle.USER_SYSTEM));
17966                }
17967            }
17968
17969            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17970                    packageName == null) {
17971                if (mIntentFilterVerifierComponent != null) {
17972                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17973                    if (!checkin) {
17974                        if (dumpState.onTitlePrinted())
17975                            pw.println();
17976                        pw.println("Intent Filter Verifier:");
17977                        pw.print("  Using: ");
17978                        pw.print(verifierPackageName);
17979                        pw.print(" (uid=");
17980                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17981                                UserHandle.USER_SYSTEM));
17982                        pw.println(")");
17983                    } else if (verifierPackageName != null) {
17984                        pw.print("ifv,"); pw.print(verifierPackageName);
17985                        pw.print(",");
17986                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17987                                UserHandle.USER_SYSTEM));
17988                    }
17989                } else {
17990                    pw.println();
17991                    pw.println("No Intent Filter Verifier available!");
17992                }
17993            }
17994
17995            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17996                boolean printedHeader = false;
17997                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17998                while (it.hasNext()) {
17999                    String name = it.next();
18000                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18001                    if (!checkin) {
18002                        if (!printedHeader) {
18003                            if (dumpState.onTitlePrinted())
18004                                pw.println();
18005                            pw.println("Libraries:");
18006                            printedHeader = true;
18007                        }
18008                        pw.print("  ");
18009                    } else {
18010                        pw.print("lib,");
18011                    }
18012                    pw.print(name);
18013                    if (!checkin) {
18014                        pw.print(" -> ");
18015                    }
18016                    if (ent.path != null) {
18017                        if (!checkin) {
18018                            pw.print("(jar) ");
18019                            pw.print(ent.path);
18020                        } else {
18021                            pw.print(",jar,");
18022                            pw.print(ent.path);
18023                        }
18024                    } else {
18025                        if (!checkin) {
18026                            pw.print("(apk) ");
18027                            pw.print(ent.apk);
18028                        } else {
18029                            pw.print(",apk,");
18030                            pw.print(ent.apk);
18031                        }
18032                    }
18033                    pw.println();
18034                }
18035            }
18036
18037            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18038                if (dumpState.onTitlePrinted())
18039                    pw.println();
18040                if (!checkin) {
18041                    pw.println("Features:");
18042                }
18043
18044                for (FeatureInfo feat : mAvailableFeatures.values()) {
18045                    if (checkin) {
18046                        pw.print("feat,");
18047                        pw.print(feat.name);
18048                        pw.print(",");
18049                        pw.println(feat.version);
18050                    } else {
18051                        pw.print("  ");
18052                        pw.print(feat.name);
18053                        if (feat.version > 0) {
18054                            pw.print(" version=");
18055                            pw.print(feat.version);
18056                        }
18057                        pw.println();
18058                    }
18059                }
18060            }
18061
18062            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18063                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18064                        : "Activity Resolver Table:", "  ", packageName,
18065                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18066                    dumpState.setTitlePrinted(true);
18067                }
18068            }
18069            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18070                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18071                        : "Receiver Resolver Table:", "  ", packageName,
18072                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18073                    dumpState.setTitlePrinted(true);
18074                }
18075            }
18076            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18077                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18078                        : "Service Resolver Table:", "  ", packageName,
18079                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18080                    dumpState.setTitlePrinted(true);
18081                }
18082            }
18083            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18084                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18085                        : "Provider Resolver Table:", "  ", packageName,
18086                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18087                    dumpState.setTitlePrinted(true);
18088                }
18089            }
18090
18091            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18092                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18093                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18094                    int user = mSettings.mPreferredActivities.keyAt(i);
18095                    if (pir.dump(pw,
18096                            dumpState.getTitlePrinted()
18097                                ? "\nPreferred Activities User " + user + ":"
18098                                : "Preferred Activities User " + user + ":", "  ",
18099                            packageName, true, false)) {
18100                        dumpState.setTitlePrinted(true);
18101                    }
18102                }
18103            }
18104
18105            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18106                pw.flush();
18107                FileOutputStream fout = new FileOutputStream(fd);
18108                BufferedOutputStream str = new BufferedOutputStream(fout);
18109                XmlSerializer serializer = new FastXmlSerializer();
18110                try {
18111                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18112                    serializer.startDocument(null, true);
18113                    serializer.setFeature(
18114                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18115                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18116                    serializer.endDocument();
18117                    serializer.flush();
18118                } catch (IllegalArgumentException e) {
18119                    pw.println("Failed writing: " + e);
18120                } catch (IllegalStateException e) {
18121                    pw.println("Failed writing: " + e);
18122                } catch (IOException e) {
18123                    pw.println("Failed writing: " + e);
18124                }
18125            }
18126
18127            if (!checkin
18128                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18129                    && packageName == null) {
18130                pw.println();
18131                int count = mSettings.mPackages.size();
18132                if (count == 0) {
18133                    pw.println("No applications!");
18134                    pw.println();
18135                } else {
18136                    final String prefix = "  ";
18137                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18138                    if (allPackageSettings.size() == 0) {
18139                        pw.println("No domain preferred apps!");
18140                        pw.println();
18141                    } else {
18142                        pw.println("App verification status:");
18143                        pw.println();
18144                        count = 0;
18145                        for (PackageSetting ps : allPackageSettings) {
18146                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18147                            if (ivi == null || ivi.getPackageName() == null) continue;
18148                            pw.println(prefix + "Package: " + ivi.getPackageName());
18149                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18150                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18151                            pw.println();
18152                            count++;
18153                        }
18154                        if (count == 0) {
18155                            pw.println(prefix + "No app verification established.");
18156                            pw.println();
18157                        }
18158                        for (int userId : sUserManager.getUserIds()) {
18159                            pw.println("App linkages for user " + userId + ":");
18160                            pw.println();
18161                            count = 0;
18162                            for (PackageSetting ps : allPackageSettings) {
18163                                final long status = ps.getDomainVerificationStatusForUser(userId);
18164                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18165                                    continue;
18166                                }
18167                                pw.println(prefix + "Package: " + ps.name);
18168                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18169                                String statusStr = IntentFilterVerificationInfo.
18170                                        getStatusStringFromValue(status);
18171                                pw.println(prefix + "Status:  " + statusStr);
18172                                pw.println();
18173                                count++;
18174                            }
18175                            if (count == 0) {
18176                                pw.println(prefix + "No configured app linkages.");
18177                                pw.println();
18178                            }
18179                        }
18180                    }
18181                }
18182            }
18183
18184            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18185                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18186                if (packageName == null && permissionNames == null) {
18187                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18188                        if (iperm == 0) {
18189                            if (dumpState.onTitlePrinted())
18190                                pw.println();
18191                            pw.println("AppOp Permissions:");
18192                        }
18193                        pw.print("  AppOp Permission ");
18194                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18195                        pw.println(":");
18196                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18197                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18198                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18199                        }
18200                    }
18201                }
18202            }
18203
18204            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18205                boolean printedSomething = false;
18206                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18207                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18208                        continue;
18209                    }
18210                    if (!printedSomething) {
18211                        if (dumpState.onTitlePrinted())
18212                            pw.println();
18213                        pw.println("Registered ContentProviders:");
18214                        printedSomething = true;
18215                    }
18216                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18217                    pw.print("    "); pw.println(p.toString());
18218                }
18219                printedSomething = false;
18220                for (Map.Entry<String, PackageParser.Provider> entry :
18221                        mProvidersByAuthority.entrySet()) {
18222                    PackageParser.Provider p = entry.getValue();
18223                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18224                        continue;
18225                    }
18226                    if (!printedSomething) {
18227                        if (dumpState.onTitlePrinted())
18228                            pw.println();
18229                        pw.println("ContentProvider Authorities:");
18230                        printedSomething = true;
18231                    }
18232                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18233                    pw.print("    "); pw.println(p.toString());
18234                    if (p.info != null && p.info.applicationInfo != null) {
18235                        final String appInfo = p.info.applicationInfo.toString();
18236                        pw.print("      applicationInfo="); pw.println(appInfo);
18237                    }
18238                }
18239            }
18240
18241            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18242                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18243            }
18244
18245            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18246                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18247            }
18248
18249            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18250                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18251            }
18252
18253            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18254                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18255            }
18256
18257            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18258                // XXX should handle packageName != null by dumping only install data that
18259                // the given package is involved with.
18260                if (dumpState.onTitlePrinted()) pw.println();
18261                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18262            }
18263
18264            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18265                // XXX should handle packageName != null by dumping only install data that
18266                // the given package is involved with.
18267                if (dumpState.onTitlePrinted()) pw.println();
18268
18269                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18270                ipw.println();
18271                ipw.println("Frozen packages:");
18272                ipw.increaseIndent();
18273                if (mFrozenPackages.size() == 0) {
18274                    ipw.println("(none)");
18275                } else {
18276                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18277                        ipw.println(mFrozenPackages.valueAt(i));
18278                    }
18279                }
18280                ipw.decreaseIndent();
18281            }
18282
18283            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18284                if (dumpState.onTitlePrinted()) pw.println();
18285                mSettings.dumpReadMessagesLPr(pw, dumpState);
18286
18287                pw.println();
18288                pw.println("Package warning messages:");
18289                BufferedReader in = null;
18290                String line = null;
18291                try {
18292                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18293                    while ((line = in.readLine()) != null) {
18294                        if (line.contains("ignored: updated version")) continue;
18295                        pw.println(line);
18296                    }
18297                } catch (IOException ignored) {
18298                } finally {
18299                    IoUtils.closeQuietly(in);
18300                }
18301            }
18302
18303            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18304                BufferedReader in = null;
18305                String line = null;
18306                try {
18307                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18308                    while ((line = in.readLine()) != null) {
18309                        if (line.contains("ignored: updated version")) continue;
18310                        pw.print("msg,");
18311                        pw.println(line);
18312                    }
18313                } catch (IOException ignored) {
18314                } finally {
18315                    IoUtils.closeQuietly(in);
18316                }
18317            }
18318        }
18319    }
18320
18321    private String dumpDomainString(String packageName) {
18322        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18323                .getList();
18324        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18325
18326        ArraySet<String> result = new ArraySet<>();
18327        if (iviList.size() > 0) {
18328            for (IntentFilterVerificationInfo ivi : iviList) {
18329                for (String host : ivi.getDomains()) {
18330                    result.add(host);
18331                }
18332            }
18333        }
18334        if (filters != null && filters.size() > 0) {
18335            for (IntentFilter filter : filters) {
18336                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18337                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18338                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18339                    result.addAll(filter.getHostsList());
18340                }
18341            }
18342        }
18343
18344        StringBuilder sb = new StringBuilder(result.size() * 16);
18345        for (String domain : result) {
18346            if (sb.length() > 0) sb.append(" ");
18347            sb.append(domain);
18348        }
18349        return sb.toString();
18350    }
18351
18352    // ------- apps on sdcard specific code -------
18353    static final boolean DEBUG_SD_INSTALL = false;
18354
18355    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18356
18357    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18358
18359    private boolean mMediaMounted = false;
18360
18361    static String getEncryptKey() {
18362        try {
18363            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18364                    SD_ENCRYPTION_KEYSTORE_NAME);
18365            if (sdEncKey == null) {
18366                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18367                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18368                if (sdEncKey == null) {
18369                    Slog.e(TAG, "Failed to create encryption keys");
18370                    return null;
18371                }
18372            }
18373            return sdEncKey;
18374        } catch (NoSuchAlgorithmException nsae) {
18375            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18376            return null;
18377        } catch (IOException ioe) {
18378            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18379            return null;
18380        }
18381    }
18382
18383    /*
18384     * Update media status on PackageManager.
18385     */
18386    @Override
18387    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18388        int callingUid = Binder.getCallingUid();
18389        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18390            throw new SecurityException("Media status can only be updated by the system");
18391        }
18392        // reader; this apparently protects mMediaMounted, but should probably
18393        // be a different lock in that case.
18394        synchronized (mPackages) {
18395            Log.i(TAG, "Updating external media status from "
18396                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18397                    + (mediaStatus ? "mounted" : "unmounted"));
18398            if (DEBUG_SD_INSTALL)
18399                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18400                        + ", mMediaMounted=" + mMediaMounted);
18401            if (mediaStatus == mMediaMounted) {
18402                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18403                        : 0, -1);
18404                mHandler.sendMessage(msg);
18405                return;
18406            }
18407            mMediaMounted = mediaStatus;
18408        }
18409        // Queue up an async operation since the package installation may take a
18410        // little while.
18411        mHandler.post(new Runnable() {
18412            public void run() {
18413                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18414            }
18415        });
18416    }
18417
18418    /**
18419     * Called by MountService when the initial ASECs to scan are available.
18420     * Should block until all the ASEC containers are finished being scanned.
18421     */
18422    public void scanAvailableAsecs() {
18423        updateExternalMediaStatusInner(true, false, false);
18424    }
18425
18426    /*
18427     * Collect information of applications on external media, map them against
18428     * existing containers and update information based on current mount status.
18429     * Please note that we always have to report status if reportStatus has been
18430     * set to true especially when unloading packages.
18431     */
18432    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18433            boolean externalStorage) {
18434        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18435        int[] uidArr = EmptyArray.INT;
18436
18437        final String[] list = PackageHelper.getSecureContainerList();
18438        if (ArrayUtils.isEmpty(list)) {
18439            Log.i(TAG, "No secure containers found");
18440        } else {
18441            // Process list of secure containers and categorize them
18442            // as active or stale based on their package internal state.
18443
18444            // reader
18445            synchronized (mPackages) {
18446                for (String cid : list) {
18447                    // Leave stages untouched for now; installer service owns them
18448                    if (PackageInstallerService.isStageName(cid)) continue;
18449
18450                    if (DEBUG_SD_INSTALL)
18451                        Log.i(TAG, "Processing container " + cid);
18452                    String pkgName = getAsecPackageName(cid);
18453                    if (pkgName == null) {
18454                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18455                        continue;
18456                    }
18457                    if (DEBUG_SD_INSTALL)
18458                        Log.i(TAG, "Looking for pkg : " + pkgName);
18459
18460                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18461                    if (ps == null) {
18462                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18463                        continue;
18464                    }
18465
18466                    /*
18467                     * Skip packages that are not external if we're unmounting
18468                     * external storage.
18469                     */
18470                    if (externalStorage && !isMounted && !isExternal(ps)) {
18471                        continue;
18472                    }
18473
18474                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18475                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18476                    // The package status is changed only if the code path
18477                    // matches between settings and the container id.
18478                    if (ps.codePathString != null
18479                            && ps.codePathString.startsWith(args.getCodePath())) {
18480                        if (DEBUG_SD_INSTALL) {
18481                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18482                                    + " at code path: " + ps.codePathString);
18483                        }
18484
18485                        // We do have a valid package installed on sdcard
18486                        processCids.put(args, ps.codePathString);
18487                        final int uid = ps.appId;
18488                        if (uid != -1) {
18489                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18490                        }
18491                    } else {
18492                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18493                                + ps.codePathString);
18494                    }
18495                }
18496            }
18497
18498            Arrays.sort(uidArr);
18499        }
18500
18501        // Process packages with valid entries.
18502        if (isMounted) {
18503            if (DEBUG_SD_INSTALL)
18504                Log.i(TAG, "Loading packages");
18505            loadMediaPackages(processCids, uidArr, externalStorage);
18506            startCleaningPackages();
18507            mInstallerService.onSecureContainersAvailable();
18508        } else {
18509            if (DEBUG_SD_INSTALL)
18510                Log.i(TAG, "Unloading packages");
18511            unloadMediaPackages(processCids, uidArr, reportStatus);
18512        }
18513    }
18514
18515    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18516            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18517        final int size = infos.size();
18518        final String[] packageNames = new String[size];
18519        final int[] packageUids = new int[size];
18520        for (int i = 0; i < size; i++) {
18521            final ApplicationInfo info = infos.get(i);
18522            packageNames[i] = info.packageName;
18523            packageUids[i] = info.uid;
18524        }
18525        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18526                finishedReceiver);
18527    }
18528
18529    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18530            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18531        sendResourcesChangedBroadcast(mediaStatus, replacing,
18532                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18533    }
18534
18535    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18536            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18537        int size = pkgList.length;
18538        if (size > 0) {
18539            // Send broadcasts here
18540            Bundle extras = new Bundle();
18541            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18542            if (uidArr != null) {
18543                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18544            }
18545            if (replacing) {
18546                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18547            }
18548            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18549                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18550            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18551        }
18552    }
18553
18554   /*
18555     * Look at potentially valid container ids from processCids If package
18556     * information doesn't match the one on record or package scanning fails,
18557     * the cid is added to list of removeCids. We currently don't delete stale
18558     * containers.
18559     */
18560    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18561            boolean externalStorage) {
18562        ArrayList<String> pkgList = new ArrayList<String>();
18563        Set<AsecInstallArgs> keys = processCids.keySet();
18564
18565        for (AsecInstallArgs args : keys) {
18566            String codePath = processCids.get(args);
18567            if (DEBUG_SD_INSTALL)
18568                Log.i(TAG, "Loading container : " + args.cid);
18569            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18570            try {
18571                // Make sure there are no container errors first.
18572                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18573                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18574                            + " when installing from sdcard");
18575                    continue;
18576                }
18577                // Check code path here.
18578                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18579                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18580                            + " does not match one in settings " + codePath);
18581                    continue;
18582                }
18583                // Parse package
18584                int parseFlags = mDefParseFlags;
18585                if (args.isExternalAsec()) {
18586                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18587                }
18588                if (args.isFwdLocked()) {
18589                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18590                }
18591
18592                synchronized (mInstallLock) {
18593                    PackageParser.Package pkg = null;
18594                    try {
18595                        // Sadly we don't know the package name yet to freeze it
18596                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18597                                SCAN_IGNORE_FROZEN, 0, null);
18598                    } catch (PackageManagerException e) {
18599                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18600                    }
18601                    // Scan the package
18602                    if (pkg != null) {
18603                        /*
18604                         * TODO why is the lock being held? doPostInstall is
18605                         * called in other places without the lock. This needs
18606                         * to be straightened out.
18607                         */
18608                        // writer
18609                        synchronized (mPackages) {
18610                            retCode = PackageManager.INSTALL_SUCCEEDED;
18611                            pkgList.add(pkg.packageName);
18612                            // Post process args
18613                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18614                                    pkg.applicationInfo.uid);
18615                        }
18616                    } else {
18617                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18618                    }
18619                }
18620
18621            } finally {
18622                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18623                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18624                }
18625            }
18626        }
18627        // writer
18628        synchronized (mPackages) {
18629            // If the platform SDK has changed since the last time we booted,
18630            // we need to re-grant app permission to catch any new ones that
18631            // appear. This is really a hack, and means that apps can in some
18632            // cases get permissions that the user didn't initially explicitly
18633            // allow... it would be nice to have some better way to handle
18634            // this situation.
18635            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18636                    : mSettings.getInternalVersion();
18637            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18638                    : StorageManager.UUID_PRIVATE_INTERNAL;
18639
18640            int updateFlags = UPDATE_PERMISSIONS_ALL;
18641            if (ver.sdkVersion != mSdkVersion) {
18642                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18643                        + mSdkVersion + "; regranting permissions for external");
18644                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18645            }
18646            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18647
18648            // Yay, everything is now upgraded
18649            ver.forceCurrent();
18650
18651            // can downgrade to reader
18652            // Persist settings
18653            mSettings.writeLPr();
18654        }
18655        // Send a broadcast to let everyone know we are done processing
18656        if (pkgList.size() > 0) {
18657            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18658        }
18659    }
18660
18661   /*
18662     * Utility method to unload a list of specified containers
18663     */
18664    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18665        // Just unmount all valid containers.
18666        for (AsecInstallArgs arg : cidArgs) {
18667            synchronized (mInstallLock) {
18668                arg.doPostDeleteLI(false);
18669           }
18670       }
18671   }
18672
18673    /*
18674     * Unload packages mounted on external media. This involves deleting package
18675     * data from internal structures, sending broadcasts about disabled packages,
18676     * gc'ing to free up references, unmounting all secure containers
18677     * corresponding to packages on external media, and posting a
18678     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18679     * that we always have to post this message if status has been requested no
18680     * matter what.
18681     */
18682    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18683            final boolean reportStatus) {
18684        if (DEBUG_SD_INSTALL)
18685            Log.i(TAG, "unloading media packages");
18686        ArrayList<String> pkgList = new ArrayList<String>();
18687        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18688        final Set<AsecInstallArgs> keys = processCids.keySet();
18689        for (AsecInstallArgs args : keys) {
18690            String pkgName = args.getPackageName();
18691            if (DEBUG_SD_INSTALL)
18692                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18693            // Delete package internally
18694            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18695            synchronized (mInstallLock) {
18696                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18697                final boolean res;
18698                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18699                        "unloadMediaPackages")) {
18700                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18701                            null);
18702                }
18703                if (res) {
18704                    pkgList.add(pkgName);
18705                } else {
18706                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18707                    failedList.add(args);
18708                }
18709            }
18710        }
18711
18712        // reader
18713        synchronized (mPackages) {
18714            // We didn't update the settings after removing each package;
18715            // write them now for all packages.
18716            mSettings.writeLPr();
18717        }
18718
18719        // We have to absolutely send UPDATED_MEDIA_STATUS only
18720        // after confirming that all the receivers processed the ordered
18721        // broadcast when packages get disabled, force a gc to clean things up.
18722        // and unload all the containers.
18723        if (pkgList.size() > 0) {
18724            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18725                    new IIntentReceiver.Stub() {
18726                public void performReceive(Intent intent, int resultCode, String data,
18727                        Bundle extras, boolean ordered, boolean sticky,
18728                        int sendingUser) throws RemoteException {
18729                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18730                            reportStatus ? 1 : 0, 1, keys);
18731                    mHandler.sendMessage(msg);
18732                }
18733            });
18734        } else {
18735            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18736                    keys);
18737            mHandler.sendMessage(msg);
18738        }
18739    }
18740
18741    private void loadPrivatePackages(final VolumeInfo vol) {
18742        mHandler.post(new Runnable() {
18743            @Override
18744            public void run() {
18745                loadPrivatePackagesInner(vol);
18746            }
18747        });
18748    }
18749
18750    private void loadPrivatePackagesInner(VolumeInfo vol) {
18751        final String volumeUuid = vol.fsUuid;
18752        if (TextUtils.isEmpty(volumeUuid)) {
18753            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18754            return;
18755        }
18756
18757        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18758        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18759        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18760
18761        final VersionInfo ver;
18762        final List<PackageSetting> packages;
18763        synchronized (mPackages) {
18764            ver = mSettings.findOrCreateVersion(volumeUuid);
18765            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18766        }
18767
18768        for (PackageSetting ps : packages) {
18769            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18770            synchronized (mInstallLock) {
18771                final PackageParser.Package pkg;
18772                try {
18773                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18774                    loaded.add(pkg.applicationInfo);
18775
18776                } catch (PackageManagerException e) {
18777                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18778                }
18779
18780                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18781                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18782                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18783                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18784                }
18785            }
18786        }
18787
18788        // Reconcile app data for all started/unlocked users
18789        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18790        final UserManager um = mContext.getSystemService(UserManager.class);
18791        for (UserInfo user : um.getUsers()) {
18792            final int flags;
18793            if (um.isUserUnlocked(user.id)) {
18794                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18795            } else if (um.isUserRunning(user.id)) {
18796                flags = StorageManager.FLAG_STORAGE_DE;
18797            } else {
18798                continue;
18799            }
18800
18801            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18802            synchronized (mInstallLock) {
18803                reconcileAppsDataLI(volumeUuid, user.id, flags);
18804            }
18805        }
18806
18807        synchronized (mPackages) {
18808            int updateFlags = UPDATE_PERMISSIONS_ALL;
18809            if (ver.sdkVersion != mSdkVersion) {
18810                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18811                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18812                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18813            }
18814            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18815
18816            // Yay, everything is now upgraded
18817            ver.forceCurrent();
18818
18819            mSettings.writeLPr();
18820        }
18821
18822        for (PackageFreezer freezer : freezers) {
18823            freezer.close();
18824        }
18825
18826        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18827        sendResourcesChangedBroadcast(true, false, loaded, null);
18828    }
18829
18830    private void unloadPrivatePackages(final VolumeInfo vol) {
18831        mHandler.post(new Runnable() {
18832            @Override
18833            public void run() {
18834                unloadPrivatePackagesInner(vol);
18835            }
18836        });
18837    }
18838
18839    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18840        final String volumeUuid = vol.fsUuid;
18841        if (TextUtils.isEmpty(volumeUuid)) {
18842            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18843            return;
18844        }
18845
18846        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18847        synchronized (mInstallLock) {
18848        synchronized (mPackages) {
18849            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18850            for (PackageSetting ps : packages) {
18851                if (ps.pkg == null) continue;
18852
18853                final ApplicationInfo info = ps.pkg.applicationInfo;
18854                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18855                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18856
18857                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18858                        "unloadPrivatePackagesInner")) {
18859                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18860                            false, null)) {
18861                        unloaded.add(info);
18862                    } else {
18863                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18864                    }
18865                }
18866            }
18867
18868            mSettings.writeLPr();
18869        }
18870        }
18871
18872        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18873        sendResourcesChangedBroadcast(false, false, unloaded, null);
18874    }
18875
18876    /**
18877     * Prepare storage areas for given user on all mounted devices.
18878     */
18879    void prepareUserData(int userId, int userSerial, int flags) {
18880        synchronized (mInstallLock) {
18881            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18882            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18883                final String volumeUuid = vol.getFsUuid();
18884                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18885            }
18886        }
18887    }
18888
18889    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18890            boolean allowRecover) {
18891        // Prepare storage and verify that serial numbers are consistent; if
18892        // there's a mismatch we need to destroy to avoid leaking data
18893        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18894        try {
18895            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18896
18897            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18898                UserManagerService.enforceSerialNumber(
18899                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18900            }
18901            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18902                UserManagerService.enforceSerialNumber(
18903                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18904            }
18905
18906            synchronized (mInstallLock) {
18907                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18908            }
18909        } catch (Exception e) {
18910            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18911                    + " because we failed to prepare: " + e);
18912            destroyUserDataLI(volumeUuid, userId,
18913                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18914
18915            if (allowRecover) {
18916                // Try one last time; if we fail again we're really in trouble
18917                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18918            }
18919        }
18920    }
18921
18922    /**
18923     * Destroy storage areas for given user on all mounted devices.
18924     */
18925    void destroyUserData(int userId, int flags) {
18926        synchronized (mInstallLock) {
18927            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18928            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18929                final String volumeUuid = vol.getFsUuid();
18930                destroyUserDataLI(volumeUuid, userId, flags);
18931            }
18932        }
18933    }
18934
18935    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18936        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18937        try {
18938            // Clean up app data, profile data, and media data
18939            mInstaller.destroyUserData(volumeUuid, userId, flags);
18940
18941            // Clean up system data
18942            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18943                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18944                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18945                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18946                }
18947                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18948                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18949                }
18950            }
18951
18952            // Data with special labels is now gone, so finish the job
18953            storage.destroyUserStorage(volumeUuid, userId, flags);
18954
18955        } catch (Exception e) {
18956            logCriticalInfo(Log.WARN,
18957                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18958        }
18959    }
18960
18961    /**
18962     * Examine all users present on given mounted volume, and destroy data
18963     * belonging to users that are no longer valid, or whose user ID has been
18964     * recycled.
18965     */
18966    private void reconcileUsers(String volumeUuid) {
18967        final List<File> files = new ArrayList<>();
18968        Collections.addAll(files, FileUtils
18969                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18970        Collections.addAll(files, FileUtils
18971                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18972        for (File file : files) {
18973            if (!file.isDirectory()) continue;
18974
18975            final int userId;
18976            final UserInfo info;
18977            try {
18978                userId = Integer.parseInt(file.getName());
18979                info = sUserManager.getUserInfo(userId);
18980            } catch (NumberFormatException e) {
18981                Slog.w(TAG, "Invalid user directory " + file);
18982                continue;
18983            }
18984
18985            boolean destroyUser = false;
18986            if (info == null) {
18987                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18988                        + " because no matching user was found");
18989                destroyUser = true;
18990            } else if (!mOnlyCore) {
18991                try {
18992                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18993                } catch (IOException e) {
18994                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18995                            + " because we failed to enforce serial number: " + e);
18996                    destroyUser = true;
18997                }
18998            }
18999
19000            if (destroyUser) {
19001                synchronized (mInstallLock) {
19002                    destroyUserDataLI(volumeUuid, userId,
19003                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19004                }
19005            }
19006        }
19007    }
19008
19009    private void assertPackageKnown(String volumeUuid, String packageName)
19010            throws PackageManagerException {
19011        synchronized (mPackages) {
19012            final PackageSetting ps = mSettings.mPackages.get(packageName);
19013            if (ps == null) {
19014                throw new PackageManagerException("Package " + packageName + " is unknown");
19015            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19016                throw new PackageManagerException(
19017                        "Package " + packageName + " found on unknown volume " + volumeUuid
19018                                + "; expected volume " + ps.volumeUuid);
19019            }
19020        }
19021    }
19022
19023    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19024            throws PackageManagerException {
19025        synchronized (mPackages) {
19026            final PackageSetting ps = mSettings.mPackages.get(packageName);
19027            if (ps == null) {
19028                throw new PackageManagerException("Package " + packageName + " is unknown");
19029            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19030                throw new PackageManagerException(
19031                        "Package " + packageName + " found on unknown volume " + volumeUuid
19032                                + "; expected volume " + ps.volumeUuid);
19033            } else if (!ps.getInstalled(userId)) {
19034                throw new PackageManagerException(
19035                        "Package " + packageName + " not installed for user " + userId);
19036            }
19037        }
19038    }
19039
19040    /**
19041     * Examine all apps present on given mounted volume, and destroy apps that
19042     * aren't expected, either due to uninstallation or reinstallation on
19043     * another volume.
19044     */
19045    private void reconcileApps(String volumeUuid) {
19046        final File[] files = FileUtils
19047                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19048        for (File file : files) {
19049            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19050                    && !PackageInstallerService.isStageName(file.getName());
19051            if (!isPackage) {
19052                // Ignore entries which are not packages
19053                continue;
19054            }
19055
19056            try {
19057                final PackageLite pkg = PackageParser.parsePackageLite(file,
19058                        PackageParser.PARSE_MUST_BE_APK);
19059                assertPackageKnown(volumeUuid, pkg.packageName);
19060
19061            } catch (PackageParserException | PackageManagerException e) {
19062                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19063                synchronized (mInstallLock) {
19064                    removeCodePathLI(file);
19065                }
19066            }
19067        }
19068    }
19069
19070    /**
19071     * Reconcile all app data for the given user.
19072     * <p>
19073     * Verifies that directories exist and that ownership and labeling is
19074     * correct for all installed apps on all mounted volumes.
19075     */
19076    void reconcileAppsData(int userId, int flags) {
19077        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19078        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19079            final String volumeUuid = vol.getFsUuid();
19080            synchronized (mInstallLock) {
19081                reconcileAppsDataLI(volumeUuid, userId, flags);
19082            }
19083        }
19084    }
19085
19086    /**
19087     * Reconcile all app data on given mounted volume.
19088     * <p>
19089     * Destroys app data that isn't expected, either due to uninstallation or
19090     * reinstallation on another volume.
19091     * <p>
19092     * Verifies that directories exist and that ownership and labeling is
19093     * correct for all installed apps.
19094     */
19095    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19096        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19097                + Integer.toHexString(flags));
19098
19099        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19100        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19101
19102        boolean restoreconNeeded = false;
19103
19104        // First look for stale data that doesn't belong, and check if things
19105        // have changed since we did our last restorecon
19106        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19107            if (!isUserKeyUnlocked(userId)) {
19108                throw new RuntimeException(
19109                        "Yikes, someone asked us to reconcile CE storage while " + userId
19110                                + " was still locked; this would have caused massive data loss!");
19111            }
19112
19113            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19114
19115            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19116            for (File file : files) {
19117                final String packageName = file.getName();
19118                try {
19119                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19120                } catch (PackageManagerException e) {
19121                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19122                    try {
19123                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19124                                StorageManager.FLAG_STORAGE_CE, 0);
19125                    } catch (InstallerException e2) {
19126                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19127                    }
19128                }
19129            }
19130        }
19131        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19132            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19133
19134            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19135            for (File file : files) {
19136                final String packageName = file.getName();
19137                try {
19138                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19139                } catch (PackageManagerException e) {
19140                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19141                    try {
19142                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19143                                StorageManager.FLAG_STORAGE_DE, 0);
19144                    } catch (InstallerException e2) {
19145                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19146                    }
19147                }
19148            }
19149        }
19150
19151        // Ensure that data directories are ready to roll for all packages
19152        // installed for this volume and user
19153        final List<PackageSetting> packages;
19154        synchronized (mPackages) {
19155            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19156        }
19157        int preparedCount = 0;
19158        for (PackageSetting ps : packages) {
19159            final String packageName = ps.name;
19160            if (ps.pkg == null) {
19161                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19162                // TODO: might be due to legacy ASEC apps; we should circle back
19163                // and reconcile again once they're scanned
19164                continue;
19165            }
19166
19167            if (ps.getInstalled(userId)) {
19168                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19169
19170                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19171                    // We may have just shuffled around app data directories, so
19172                    // prepare them one more time
19173                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19174                }
19175
19176                preparedCount++;
19177            }
19178        }
19179
19180        if (restoreconNeeded) {
19181            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19182                SELinuxMMAC.setRestoreconDone(ceDir);
19183            }
19184            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19185                SELinuxMMAC.setRestoreconDone(deDir);
19186            }
19187        }
19188
19189        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19190                + " packages; restoreconNeeded was " + restoreconNeeded);
19191    }
19192
19193    /**
19194     * Prepare app data for the given app just after it was installed or
19195     * upgraded. This method carefully only touches users that it's installed
19196     * for, and it forces a restorecon to handle any seinfo changes.
19197     * <p>
19198     * Verifies that directories exist and that ownership and labeling is
19199     * correct for all installed apps. If there is an ownership mismatch, it
19200     * will try recovering system apps by wiping data; third-party app data is
19201     * left intact.
19202     * <p>
19203     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19204     */
19205    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19206        final PackageSetting ps;
19207        synchronized (mPackages) {
19208            ps = mSettings.mPackages.get(pkg.packageName);
19209            mSettings.writeKernelMappingLPr(ps);
19210        }
19211
19212        final UserManager um = mContext.getSystemService(UserManager.class);
19213        for (UserInfo user : um.getUsers()) {
19214            final int flags;
19215            if (um.isUserUnlocked(user.id)) {
19216                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19217            } else if (um.isUserRunning(user.id)) {
19218                flags = StorageManager.FLAG_STORAGE_DE;
19219            } else {
19220                continue;
19221            }
19222
19223            if (ps.getInstalled(user.id)) {
19224                // Whenever an app changes, force a restorecon of its data
19225                // TODO: when user data is locked, mark that we're still dirty
19226                prepareAppDataLIF(pkg, user.id, flags, true);
19227            }
19228        }
19229    }
19230
19231    /**
19232     * Prepare app data for the given app.
19233     * <p>
19234     * Verifies that directories exist and that ownership and labeling is
19235     * correct for all installed apps. If there is an ownership mismatch, this
19236     * will try recovering system apps by wiping data; third-party app data is
19237     * left intact.
19238     */
19239    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19240            boolean restoreconNeeded) {
19241        if (pkg == null) {
19242            Slog.wtf(TAG, "Package was null!", new Throwable());
19243            return;
19244        }
19245        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19246        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19247        for (int i = 0; i < childCount; i++) {
19248            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19249        }
19250    }
19251
19252    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19253            boolean restoreconNeeded) {
19254        if (DEBUG_APP_DATA) {
19255            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19256                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19257        }
19258
19259        final String volumeUuid = pkg.volumeUuid;
19260        final String packageName = pkg.packageName;
19261        final ApplicationInfo app = pkg.applicationInfo;
19262        final int appId = UserHandle.getAppId(app.uid);
19263
19264        Preconditions.checkNotNull(app.seinfo);
19265
19266        try {
19267            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19268                    appId, app.seinfo, app.targetSdkVersion);
19269        } catch (InstallerException e) {
19270            if (app.isSystemApp()) {
19271                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19272                        + ", but trying to recover: " + e);
19273                destroyAppDataLeafLIF(pkg, userId, flags);
19274                try {
19275                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19276                            appId, app.seinfo, app.targetSdkVersion);
19277                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19278                } catch (InstallerException e2) {
19279                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19280                }
19281            } else {
19282                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19283            }
19284        }
19285
19286        if (restoreconNeeded) {
19287            try {
19288                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19289                        app.seinfo);
19290            } catch (InstallerException e) {
19291                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19292            }
19293        }
19294
19295        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19296            try {
19297                // CE storage is unlocked right now, so read out the inode and
19298                // remember for use later when it's locked
19299                // TODO: mark this structure as dirty so we persist it!
19300                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19301                        StorageManager.FLAG_STORAGE_CE);
19302                synchronized (mPackages) {
19303                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19304                    if (ps != null) {
19305                        ps.setCeDataInode(ceDataInode, userId);
19306                    }
19307                }
19308            } catch (InstallerException e) {
19309                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19310            }
19311        }
19312
19313        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19314    }
19315
19316    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19317        if (pkg == null) {
19318            Slog.wtf(TAG, "Package was null!", new Throwable());
19319            return;
19320        }
19321        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19322        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19323        for (int i = 0; i < childCount; i++) {
19324            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19325        }
19326    }
19327
19328    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19329        final String volumeUuid = pkg.volumeUuid;
19330        final String packageName = pkg.packageName;
19331        final ApplicationInfo app = pkg.applicationInfo;
19332
19333        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19334            // Create a native library symlink only if we have native libraries
19335            // and if the native libraries are 32 bit libraries. We do not provide
19336            // this symlink for 64 bit libraries.
19337            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19338                final String nativeLibPath = app.nativeLibraryDir;
19339                try {
19340                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19341                            nativeLibPath, userId);
19342                } catch (InstallerException e) {
19343                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19344                }
19345            }
19346        }
19347    }
19348
19349    /**
19350     * For system apps on non-FBE devices, this method migrates any existing
19351     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19352     * requested by the app.
19353     */
19354    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19355        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19356                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19357            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19358                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19359            try {
19360                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19361                        storageTarget);
19362            } catch (InstallerException e) {
19363                logCriticalInfo(Log.WARN,
19364                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19365            }
19366            return true;
19367        } else {
19368            return false;
19369        }
19370    }
19371
19372    public PackageFreezer freezePackage(String packageName, String killReason) {
19373        return new PackageFreezer(packageName, killReason);
19374    }
19375
19376    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19377            String killReason) {
19378        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19379            return new PackageFreezer();
19380        } else {
19381            return freezePackage(packageName, killReason);
19382        }
19383    }
19384
19385    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19386            String killReason) {
19387        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19388            return new PackageFreezer();
19389        } else {
19390            return freezePackage(packageName, killReason);
19391        }
19392    }
19393
19394    /**
19395     * Class that freezes and kills the given package upon creation, and
19396     * unfreezes it upon closing. This is typically used when doing surgery on
19397     * app code/data to prevent the app from running while you're working.
19398     */
19399    private class PackageFreezer implements AutoCloseable {
19400        private final String mPackageName;
19401        private final PackageFreezer[] mChildren;
19402
19403        private final boolean mWeFroze;
19404
19405        private final AtomicBoolean mClosed = new AtomicBoolean();
19406        private final CloseGuard mCloseGuard = CloseGuard.get();
19407
19408        /**
19409         * Create and return a stub freezer that doesn't actually do anything,
19410         * typically used when someone requested
19411         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19412         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19413         */
19414        public PackageFreezer() {
19415            mPackageName = null;
19416            mChildren = null;
19417            mWeFroze = false;
19418            mCloseGuard.open("close");
19419        }
19420
19421        public PackageFreezer(String packageName, String killReason) {
19422            synchronized (mPackages) {
19423                mPackageName = packageName;
19424                mWeFroze = mFrozenPackages.add(mPackageName);
19425
19426                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19427                if (ps != null) {
19428                    killApplication(ps.name, ps.appId, killReason);
19429                }
19430
19431                final PackageParser.Package p = mPackages.get(packageName);
19432                if (p != null && p.childPackages != null) {
19433                    final int N = p.childPackages.size();
19434                    mChildren = new PackageFreezer[N];
19435                    for (int i = 0; i < N; i++) {
19436                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19437                                killReason);
19438                    }
19439                } else {
19440                    mChildren = null;
19441                }
19442            }
19443            mCloseGuard.open("close");
19444        }
19445
19446        @Override
19447        protected void finalize() throws Throwable {
19448            try {
19449                mCloseGuard.warnIfOpen();
19450                close();
19451            } finally {
19452                super.finalize();
19453            }
19454        }
19455
19456        @Override
19457        public void close() {
19458            mCloseGuard.close();
19459            if (mClosed.compareAndSet(false, true)) {
19460                synchronized (mPackages) {
19461                    if (mWeFroze) {
19462                        mFrozenPackages.remove(mPackageName);
19463                    }
19464
19465                    if (mChildren != null) {
19466                        for (PackageFreezer freezer : mChildren) {
19467                            freezer.close();
19468                        }
19469                    }
19470                }
19471            }
19472        }
19473    }
19474
19475    /**
19476     * Verify that given package is currently frozen.
19477     */
19478    private void checkPackageFrozen(String packageName) {
19479        synchronized (mPackages) {
19480            if (!mFrozenPackages.contains(packageName)) {
19481                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19482            }
19483        }
19484    }
19485
19486    @Override
19487    public int movePackage(final String packageName, final String volumeUuid) {
19488        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19489
19490        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19491        final int moveId = mNextMoveId.getAndIncrement();
19492        mHandler.post(new Runnable() {
19493            @Override
19494            public void run() {
19495                try {
19496                    movePackageInternal(packageName, volumeUuid, moveId, user);
19497                } catch (PackageManagerException e) {
19498                    Slog.w(TAG, "Failed to move " + packageName, e);
19499                    mMoveCallbacks.notifyStatusChanged(moveId,
19500                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19501                }
19502            }
19503        });
19504        return moveId;
19505    }
19506
19507    private void movePackageInternal(final String packageName, final String volumeUuid,
19508            final int moveId, UserHandle user) throws PackageManagerException {
19509        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19510        final PackageManager pm = mContext.getPackageManager();
19511
19512        final boolean currentAsec;
19513        final String currentVolumeUuid;
19514        final File codeFile;
19515        final String installerPackageName;
19516        final String packageAbiOverride;
19517        final int appId;
19518        final String seinfo;
19519        final String label;
19520        final int targetSdkVersion;
19521        final PackageFreezer freezer;
19522
19523        // reader
19524        synchronized (mPackages) {
19525            final PackageParser.Package pkg = mPackages.get(packageName);
19526            final PackageSetting ps = mSettings.mPackages.get(packageName);
19527            if (pkg == null || ps == null) {
19528                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19529            }
19530
19531            if (pkg.applicationInfo.isSystemApp()) {
19532                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19533                        "Cannot move system application");
19534            }
19535
19536            if (pkg.applicationInfo.isExternalAsec()) {
19537                currentAsec = true;
19538                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19539            } else if (pkg.applicationInfo.isForwardLocked()) {
19540                currentAsec = true;
19541                currentVolumeUuid = "forward_locked";
19542            } else {
19543                currentAsec = false;
19544                currentVolumeUuid = ps.volumeUuid;
19545
19546                final File probe = new File(pkg.codePath);
19547                final File probeOat = new File(probe, "oat");
19548                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19549                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19550                            "Move only supported for modern cluster style installs");
19551                }
19552            }
19553
19554            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19555                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19556                        "Package already moved to " + volumeUuid);
19557            }
19558            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19559                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19560                        "Device admin cannot be moved");
19561            }
19562
19563            if (mFrozenPackages.contains(packageName)) {
19564                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19565                        "Failed to move already frozen package");
19566            }
19567
19568            codeFile = new File(pkg.codePath);
19569            installerPackageName = ps.installerPackageName;
19570            packageAbiOverride = ps.cpuAbiOverrideString;
19571            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19572            seinfo = pkg.applicationInfo.seinfo;
19573            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19574            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19575            freezer = new PackageFreezer(packageName, "movePackageInternal");
19576        }
19577
19578        final Bundle extras = new Bundle();
19579        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19580        extras.putString(Intent.EXTRA_TITLE, label);
19581        mMoveCallbacks.notifyCreated(moveId, extras);
19582
19583        int installFlags;
19584        final boolean moveCompleteApp;
19585        final File measurePath;
19586
19587        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19588            installFlags = INSTALL_INTERNAL;
19589            moveCompleteApp = !currentAsec;
19590            measurePath = Environment.getDataAppDirectory(volumeUuid);
19591        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19592            installFlags = INSTALL_EXTERNAL;
19593            moveCompleteApp = false;
19594            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19595        } else {
19596            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19597            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19598                    || !volume.isMountedWritable()) {
19599                freezer.close();
19600                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19601                        "Move location not mounted private volume");
19602            }
19603
19604            Preconditions.checkState(!currentAsec);
19605
19606            installFlags = INSTALL_INTERNAL;
19607            moveCompleteApp = true;
19608            measurePath = Environment.getDataAppDirectory(volumeUuid);
19609        }
19610
19611        final PackageStats stats = new PackageStats(null, -1);
19612        synchronized (mInstaller) {
19613            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19614                freezer.close();
19615                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19616                        "Failed to measure package size");
19617            }
19618        }
19619
19620        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19621                + stats.dataSize);
19622
19623        final long startFreeBytes = measurePath.getFreeSpace();
19624        final long sizeBytes;
19625        if (moveCompleteApp) {
19626            sizeBytes = stats.codeSize + stats.dataSize;
19627        } else {
19628            sizeBytes = stats.codeSize;
19629        }
19630
19631        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19632            freezer.close();
19633            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19634                    "Not enough free space to move");
19635        }
19636
19637        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19638
19639        final CountDownLatch installedLatch = new CountDownLatch(1);
19640        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19641            @Override
19642            public void onUserActionRequired(Intent intent) throws RemoteException {
19643                throw new IllegalStateException();
19644            }
19645
19646            @Override
19647            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19648                    Bundle extras) throws RemoteException {
19649                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19650                        + PackageManager.installStatusToString(returnCode, msg));
19651
19652                installedLatch.countDown();
19653                freezer.close();
19654
19655                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19656                switch (status) {
19657                    case PackageInstaller.STATUS_SUCCESS:
19658                        mMoveCallbacks.notifyStatusChanged(moveId,
19659                                PackageManager.MOVE_SUCCEEDED);
19660                        break;
19661                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19662                        mMoveCallbacks.notifyStatusChanged(moveId,
19663                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19664                        break;
19665                    default:
19666                        mMoveCallbacks.notifyStatusChanged(moveId,
19667                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19668                        break;
19669                }
19670            }
19671        };
19672
19673        final MoveInfo move;
19674        if (moveCompleteApp) {
19675            // Kick off a thread to report progress estimates
19676            new Thread() {
19677                @Override
19678                public void run() {
19679                    while (true) {
19680                        try {
19681                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19682                                break;
19683                            }
19684                        } catch (InterruptedException ignored) {
19685                        }
19686
19687                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19688                        final int progress = 10 + (int) MathUtils.constrain(
19689                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19690                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19691                    }
19692                }
19693            }.start();
19694
19695            final String dataAppName = codeFile.getName();
19696            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19697                    dataAppName, appId, seinfo, targetSdkVersion);
19698        } else {
19699            move = null;
19700        }
19701
19702        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19703
19704        final Message msg = mHandler.obtainMessage(INIT_COPY);
19705        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19706        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19707                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19708                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19709        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19710        msg.obj = params;
19711
19712        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19713                System.identityHashCode(msg.obj));
19714        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19715                System.identityHashCode(msg.obj));
19716
19717        mHandler.sendMessage(msg);
19718    }
19719
19720    @Override
19721    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19722        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19723
19724        final int realMoveId = mNextMoveId.getAndIncrement();
19725        final Bundle extras = new Bundle();
19726        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19727        mMoveCallbacks.notifyCreated(realMoveId, extras);
19728
19729        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19730            @Override
19731            public void onCreated(int moveId, Bundle extras) {
19732                // Ignored
19733            }
19734
19735            @Override
19736            public void onStatusChanged(int moveId, int status, long estMillis) {
19737                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19738            }
19739        };
19740
19741        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19742        storage.setPrimaryStorageUuid(volumeUuid, callback);
19743        return realMoveId;
19744    }
19745
19746    @Override
19747    public int getMoveStatus(int moveId) {
19748        mContext.enforceCallingOrSelfPermission(
19749                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19750        return mMoveCallbacks.mLastStatus.get(moveId);
19751    }
19752
19753    @Override
19754    public void registerMoveCallback(IPackageMoveObserver callback) {
19755        mContext.enforceCallingOrSelfPermission(
19756                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19757        mMoveCallbacks.register(callback);
19758    }
19759
19760    @Override
19761    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19762        mContext.enforceCallingOrSelfPermission(
19763                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19764        mMoveCallbacks.unregister(callback);
19765    }
19766
19767    @Override
19768    public boolean setInstallLocation(int loc) {
19769        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19770                null);
19771        if (getInstallLocation() == loc) {
19772            return true;
19773        }
19774        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19775                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19776            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19777                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19778            return true;
19779        }
19780        return false;
19781   }
19782
19783    @Override
19784    public int getInstallLocation() {
19785        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19786                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19787                PackageHelper.APP_INSTALL_AUTO);
19788    }
19789
19790    /** Called by UserManagerService */
19791    void cleanUpUser(UserManagerService userManager, int userHandle) {
19792        synchronized (mPackages) {
19793            mDirtyUsers.remove(userHandle);
19794            mUserNeedsBadging.delete(userHandle);
19795            mSettings.removeUserLPw(userHandle);
19796            mPendingBroadcasts.remove(userHandle);
19797            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19798            removeUnusedPackagesLPw(userManager, userHandle);
19799        }
19800    }
19801
19802    /**
19803     * We're removing userHandle and would like to remove any downloaded packages
19804     * that are no longer in use by any other user.
19805     * @param userHandle the user being removed
19806     */
19807    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19808        final boolean DEBUG_CLEAN_APKS = false;
19809        int [] users = userManager.getUserIds();
19810        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19811        while (psit.hasNext()) {
19812            PackageSetting ps = psit.next();
19813            if (ps.pkg == null) {
19814                continue;
19815            }
19816            final String packageName = ps.pkg.packageName;
19817            // Skip over if system app
19818            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19819                continue;
19820            }
19821            if (DEBUG_CLEAN_APKS) {
19822                Slog.i(TAG, "Checking package " + packageName);
19823            }
19824            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19825            if (keep) {
19826                if (DEBUG_CLEAN_APKS) {
19827                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19828                }
19829            } else {
19830                for (int i = 0; i < users.length; i++) {
19831                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19832                        keep = true;
19833                        if (DEBUG_CLEAN_APKS) {
19834                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19835                                    + users[i]);
19836                        }
19837                        break;
19838                    }
19839                }
19840            }
19841            if (!keep) {
19842                if (DEBUG_CLEAN_APKS) {
19843                    Slog.i(TAG, "  Removing package " + packageName);
19844                }
19845                mHandler.post(new Runnable() {
19846                    public void run() {
19847                        deletePackageX(packageName, userHandle, 0);
19848                    } //end run
19849                });
19850            }
19851        }
19852    }
19853
19854    /** Called by UserManagerService */
19855    void createNewUser(int userHandle) {
19856        synchronized (mInstallLock) {
19857            mSettings.createNewUserLI(this, mInstaller, userHandle);
19858        }
19859        synchronized (mPackages) {
19860            applyFactoryDefaultBrowserLPw(userHandle);
19861            primeDomainVerificationsLPw(userHandle);
19862        }
19863    }
19864
19865    void newUserCreated(final int userHandle) {
19866        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19867        // If permission review for legacy apps is required, we represent
19868        // dagerous permissions for such apps as always granted runtime
19869        // permissions to keep per user flag state whether review is needed.
19870        // Hence, if a new user is added we have to propagate dangerous
19871        // permission grants for these legacy apps.
19872        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19873            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19874                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19875        }
19876    }
19877
19878    @Override
19879    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19880        mContext.enforceCallingOrSelfPermission(
19881                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19882                "Only package verification agents can read the verifier device identity");
19883
19884        synchronized (mPackages) {
19885            return mSettings.getVerifierDeviceIdentityLPw();
19886        }
19887    }
19888
19889    @Override
19890    public void setPermissionEnforced(String permission, boolean enforced) {
19891        // TODO: Now that we no longer change GID for storage, this should to away.
19892        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19893                "setPermissionEnforced");
19894        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19895            synchronized (mPackages) {
19896                if (mSettings.mReadExternalStorageEnforced == null
19897                        || mSettings.mReadExternalStorageEnforced != enforced) {
19898                    mSettings.mReadExternalStorageEnforced = enforced;
19899                    mSettings.writeLPr();
19900                }
19901            }
19902            // kill any non-foreground processes so we restart them and
19903            // grant/revoke the GID.
19904            final IActivityManager am = ActivityManagerNative.getDefault();
19905            if (am != null) {
19906                final long token = Binder.clearCallingIdentity();
19907                try {
19908                    am.killProcessesBelowForeground("setPermissionEnforcement");
19909                } catch (RemoteException e) {
19910                } finally {
19911                    Binder.restoreCallingIdentity(token);
19912                }
19913            }
19914        } else {
19915            throw new IllegalArgumentException("No selective enforcement for " + permission);
19916        }
19917    }
19918
19919    @Override
19920    @Deprecated
19921    public boolean isPermissionEnforced(String permission) {
19922        return true;
19923    }
19924
19925    @Override
19926    public boolean isStorageLow() {
19927        final long token = Binder.clearCallingIdentity();
19928        try {
19929            final DeviceStorageMonitorInternal
19930                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19931            if (dsm != null) {
19932                return dsm.isMemoryLow();
19933            } else {
19934                return false;
19935            }
19936        } finally {
19937            Binder.restoreCallingIdentity(token);
19938        }
19939    }
19940
19941    @Override
19942    public IPackageInstaller getPackageInstaller() {
19943        return mInstallerService;
19944    }
19945
19946    private boolean userNeedsBadging(int userId) {
19947        int index = mUserNeedsBadging.indexOfKey(userId);
19948        if (index < 0) {
19949            final UserInfo userInfo;
19950            final long token = Binder.clearCallingIdentity();
19951            try {
19952                userInfo = sUserManager.getUserInfo(userId);
19953            } finally {
19954                Binder.restoreCallingIdentity(token);
19955            }
19956            final boolean b;
19957            if (userInfo != null && userInfo.isManagedProfile()) {
19958                b = true;
19959            } else {
19960                b = false;
19961            }
19962            mUserNeedsBadging.put(userId, b);
19963            return b;
19964        }
19965        return mUserNeedsBadging.valueAt(index);
19966    }
19967
19968    @Override
19969    public KeySet getKeySetByAlias(String packageName, String alias) {
19970        if (packageName == null || alias == null) {
19971            return null;
19972        }
19973        synchronized(mPackages) {
19974            final PackageParser.Package pkg = mPackages.get(packageName);
19975            if (pkg == null) {
19976                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19977                throw new IllegalArgumentException("Unknown package: " + packageName);
19978            }
19979            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19980            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19981        }
19982    }
19983
19984    @Override
19985    public KeySet getSigningKeySet(String packageName) {
19986        if (packageName == null) {
19987            return null;
19988        }
19989        synchronized(mPackages) {
19990            final PackageParser.Package pkg = mPackages.get(packageName);
19991            if (pkg == null) {
19992                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19993                throw new IllegalArgumentException("Unknown package: " + packageName);
19994            }
19995            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19996                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19997                throw new SecurityException("May not access signing KeySet of other apps.");
19998            }
19999            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20000            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20001        }
20002    }
20003
20004    @Override
20005    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20006        if (packageName == null || ks == null) {
20007            return false;
20008        }
20009        synchronized(mPackages) {
20010            final PackageParser.Package pkg = mPackages.get(packageName);
20011            if (pkg == null) {
20012                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20013                throw new IllegalArgumentException("Unknown package: " + packageName);
20014            }
20015            IBinder ksh = ks.getToken();
20016            if (ksh instanceof KeySetHandle) {
20017                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20018                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20019            }
20020            return false;
20021        }
20022    }
20023
20024    @Override
20025    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20026        if (packageName == null || ks == null) {
20027            return false;
20028        }
20029        synchronized(mPackages) {
20030            final PackageParser.Package pkg = mPackages.get(packageName);
20031            if (pkg == null) {
20032                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20033                throw new IllegalArgumentException("Unknown package: " + packageName);
20034            }
20035            IBinder ksh = ks.getToken();
20036            if (ksh instanceof KeySetHandle) {
20037                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20038                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20039            }
20040            return false;
20041        }
20042    }
20043
20044    private void deletePackageIfUnusedLPr(final String packageName) {
20045        PackageSetting ps = mSettings.mPackages.get(packageName);
20046        if (ps == null) {
20047            return;
20048        }
20049        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20050            // TODO Implement atomic delete if package is unused
20051            // It is currently possible that the package will be deleted even if it is installed
20052            // after this method returns.
20053            mHandler.post(new Runnable() {
20054                public void run() {
20055                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20056                }
20057            });
20058        }
20059    }
20060
20061    /**
20062     * Check and throw if the given before/after packages would be considered a
20063     * downgrade.
20064     */
20065    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20066            throws PackageManagerException {
20067        if (after.versionCode < before.mVersionCode) {
20068            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20069                    "Update version code " + after.versionCode + " is older than current "
20070                    + before.mVersionCode);
20071        } else if (after.versionCode == before.mVersionCode) {
20072            if (after.baseRevisionCode < before.baseRevisionCode) {
20073                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20074                        "Update base revision code " + after.baseRevisionCode
20075                        + " is older than current " + before.baseRevisionCode);
20076            }
20077
20078            if (!ArrayUtils.isEmpty(after.splitNames)) {
20079                for (int i = 0; i < after.splitNames.length; i++) {
20080                    final String splitName = after.splitNames[i];
20081                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20082                    if (j != -1) {
20083                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20084                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20085                                    "Update split " + splitName + " revision code "
20086                                    + after.splitRevisionCodes[i] + " is older than current "
20087                                    + before.splitRevisionCodes[j]);
20088                        }
20089                    }
20090                }
20091            }
20092        }
20093    }
20094
20095    private static class MoveCallbacks extends Handler {
20096        private static final int MSG_CREATED = 1;
20097        private static final int MSG_STATUS_CHANGED = 2;
20098
20099        private final RemoteCallbackList<IPackageMoveObserver>
20100                mCallbacks = new RemoteCallbackList<>();
20101
20102        private final SparseIntArray mLastStatus = new SparseIntArray();
20103
20104        public MoveCallbacks(Looper looper) {
20105            super(looper);
20106        }
20107
20108        public void register(IPackageMoveObserver callback) {
20109            mCallbacks.register(callback);
20110        }
20111
20112        public void unregister(IPackageMoveObserver callback) {
20113            mCallbacks.unregister(callback);
20114        }
20115
20116        @Override
20117        public void handleMessage(Message msg) {
20118            final SomeArgs args = (SomeArgs) msg.obj;
20119            final int n = mCallbacks.beginBroadcast();
20120            for (int i = 0; i < n; i++) {
20121                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20122                try {
20123                    invokeCallback(callback, msg.what, args);
20124                } catch (RemoteException ignored) {
20125                }
20126            }
20127            mCallbacks.finishBroadcast();
20128            args.recycle();
20129        }
20130
20131        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20132                throws RemoteException {
20133            switch (what) {
20134                case MSG_CREATED: {
20135                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20136                    break;
20137                }
20138                case MSG_STATUS_CHANGED: {
20139                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20140                    break;
20141                }
20142            }
20143        }
20144
20145        private void notifyCreated(int moveId, Bundle extras) {
20146            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20147
20148            final SomeArgs args = SomeArgs.obtain();
20149            args.argi1 = moveId;
20150            args.arg2 = extras;
20151            obtainMessage(MSG_CREATED, args).sendToTarget();
20152        }
20153
20154        private void notifyStatusChanged(int moveId, int status) {
20155            notifyStatusChanged(moveId, status, -1);
20156        }
20157
20158        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20159            Slog.v(TAG, "Move " + moveId + " status " + status);
20160
20161            final SomeArgs args = SomeArgs.obtain();
20162            args.argi1 = moveId;
20163            args.argi2 = status;
20164            args.arg3 = estMillis;
20165            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20166
20167            synchronized (mLastStatus) {
20168                mLastStatus.put(moveId, status);
20169            }
20170        }
20171    }
20172
20173    private final static class OnPermissionChangeListeners extends Handler {
20174        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20175
20176        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20177                new RemoteCallbackList<>();
20178
20179        public OnPermissionChangeListeners(Looper looper) {
20180            super(looper);
20181        }
20182
20183        @Override
20184        public void handleMessage(Message msg) {
20185            switch (msg.what) {
20186                case MSG_ON_PERMISSIONS_CHANGED: {
20187                    final int uid = msg.arg1;
20188                    handleOnPermissionsChanged(uid);
20189                } break;
20190            }
20191        }
20192
20193        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20194            mPermissionListeners.register(listener);
20195
20196        }
20197
20198        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20199            mPermissionListeners.unregister(listener);
20200        }
20201
20202        public void onPermissionsChanged(int uid) {
20203            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20204                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20205            }
20206        }
20207
20208        private void handleOnPermissionsChanged(int uid) {
20209            final int count = mPermissionListeners.beginBroadcast();
20210            try {
20211                for (int i = 0; i < count; i++) {
20212                    IOnPermissionsChangeListener callback = mPermissionListeners
20213                            .getBroadcastItem(i);
20214                    try {
20215                        callback.onPermissionsChanged(uid);
20216                    } catch (RemoteException e) {
20217                        Log.e(TAG, "Permission listener is dead", e);
20218                    }
20219                }
20220            } finally {
20221                mPermissionListeners.finishBroadcast();
20222            }
20223        }
20224    }
20225
20226    private class PackageManagerInternalImpl extends PackageManagerInternal {
20227        @Override
20228        public void setLocationPackagesProvider(PackagesProvider provider) {
20229            synchronized (mPackages) {
20230                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20231            }
20232        }
20233
20234        @Override
20235        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20236            synchronized (mPackages) {
20237                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20238            }
20239        }
20240
20241        @Override
20242        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20243            synchronized (mPackages) {
20244                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20245            }
20246        }
20247
20248        @Override
20249        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20250            synchronized (mPackages) {
20251                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20252            }
20253        }
20254
20255        @Override
20256        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20257            synchronized (mPackages) {
20258                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20259            }
20260        }
20261
20262        @Override
20263        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20264            synchronized (mPackages) {
20265                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20266            }
20267        }
20268
20269        @Override
20270        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20271            synchronized (mPackages) {
20272                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20273                        packageName, userId);
20274            }
20275        }
20276
20277        @Override
20278        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20279            synchronized (mPackages) {
20280                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20281                        packageName, userId);
20282            }
20283        }
20284
20285        @Override
20286        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20287            synchronized (mPackages) {
20288                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20289                        packageName, userId);
20290            }
20291        }
20292
20293        @Override
20294        public void setKeepUninstalledPackages(final List<String> packageList) {
20295            Preconditions.checkNotNull(packageList);
20296            List<String> removedFromList = null;
20297            synchronized (mPackages) {
20298                if (mKeepUninstalledPackages != null) {
20299                    final int packagesCount = mKeepUninstalledPackages.size();
20300                    for (int i = 0; i < packagesCount; i++) {
20301                        String oldPackage = mKeepUninstalledPackages.get(i);
20302                        if (packageList != null && packageList.contains(oldPackage)) {
20303                            continue;
20304                        }
20305                        if (removedFromList == null) {
20306                            removedFromList = new ArrayList<>();
20307                        }
20308                        removedFromList.add(oldPackage);
20309                    }
20310                }
20311                mKeepUninstalledPackages = new ArrayList<>(packageList);
20312                if (removedFromList != null) {
20313                    final int removedCount = removedFromList.size();
20314                    for (int i = 0; i < removedCount; i++) {
20315                        deletePackageIfUnusedLPr(removedFromList.get(i));
20316                    }
20317                }
20318            }
20319        }
20320
20321        @Override
20322        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20323            synchronized (mPackages) {
20324                // If we do not support permission review, done.
20325                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20326                    return false;
20327                }
20328
20329                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20330                if (packageSetting == null) {
20331                    return false;
20332                }
20333
20334                // Permission review applies only to apps not supporting the new permission model.
20335                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20336                    return false;
20337                }
20338
20339                // Legacy apps have the permission and get user consent on launch.
20340                PermissionsState permissionsState = packageSetting.getPermissionsState();
20341                return permissionsState.isPermissionReviewRequired(userId);
20342            }
20343        }
20344
20345        @Override
20346        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20347            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20348        }
20349
20350        @Override
20351        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20352                int userId) {
20353            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20354        }
20355    }
20356
20357    @Override
20358    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20359        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20360        synchronized (mPackages) {
20361            final long identity = Binder.clearCallingIdentity();
20362            try {
20363                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20364                        packageNames, userId);
20365            } finally {
20366                Binder.restoreCallingIdentity(identity);
20367            }
20368        }
20369    }
20370
20371    private static void enforceSystemOrPhoneCaller(String tag) {
20372        int callingUid = Binder.getCallingUid();
20373        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20374            throw new SecurityException(
20375                    "Cannot call " + tag + " from UID " + callingUid);
20376        }
20377    }
20378
20379    boolean isHistoricalPackageUsageAvailable() {
20380        return mPackageUsage.isHistoricalPackageUsageAvailable();
20381    }
20382
20383    /**
20384     * Return a <b>copy</b> of the collection of packages known to the package manager.
20385     * @return A copy of the values of mPackages.
20386     */
20387    Collection<PackageParser.Package> getPackages() {
20388        synchronized (mPackages) {
20389            return new ArrayList<>(mPackages.values());
20390        }
20391    }
20392
20393    /**
20394     * Logs process start information (including base APK hash) to the security log.
20395     * @hide
20396     */
20397    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20398            String apkFile, int pid) {
20399        if (!SecurityLog.isLoggingEnabled()) {
20400            return;
20401        }
20402        Bundle data = new Bundle();
20403        data.putLong("startTimestamp", System.currentTimeMillis());
20404        data.putString("processName", processName);
20405        data.putInt("uid", uid);
20406        data.putString("seinfo", seinfo);
20407        data.putString("apkFile", apkFile);
20408        data.putInt("pid", pid);
20409        Message msg = mProcessLoggingHandler.obtainMessage(
20410                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20411        msg.setData(data);
20412        mProcessLoggingHandler.sendMessage(msg);
20413    }
20414}
20415