PackageManagerService.java revision b53874e71459af4461d12fa626a39d02d98cf2b3
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.app.usage.UsageStatsManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralResolveInfo;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.security.KeyStore;
200import android.security.SystemKeyStore;
201import android.system.ErrnoException;
202import android.system.Os;
203import android.text.TextUtils;
204import android.text.format.DateUtils;
205import android.util.ArrayMap;
206import android.util.ArraySet;
207import android.util.AtomicFile;
208import android.util.DisplayMetrics;
209import android.util.EventLog;
210import android.util.ExceptionUtils;
211import android.util.Log;
212import android.util.LogPrinter;
213import android.util.MathUtils;
214import android.util.PrintStreamPrinter;
215import android.util.Slog;
216import android.util.SparseArray;
217import android.util.SparseBooleanArray;
218import android.util.SparseIntArray;
219import android.util.Xml;
220import android.view.Display;
221
222import com.android.internal.R;
223import com.android.internal.annotations.GuardedBy;
224import com.android.internal.app.IMediaContainerService;
225import com.android.internal.app.ResolverActivity;
226import com.android.internal.content.NativeLibraryHelper;
227import com.android.internal.content.PackageHelper;
228import com.android.internal.os.IParcelFileDescriptorFactory;
229import com.android.internal.os.InstallerConnection.InstallerException;
230import com.android.internal.os.SomeArgs;
231import com.android.internal.os.Zygote;
232import com.android.internal.telephony.CarrierAppUtils;
233import com.android.internal.util.ArrayUtils;
234import com.android.internal.util.FastPrintWriter;
235import com.android.internal.util.FastXmlSerializer;
236import com.android.internal.util.IndentingPrintWriter;
237import com.android.internal.util.Preconditions;
238import com.android.internal.util.XmlUtils;
239import com.android.server.EventLogTags;
240import com.android.server.FgThread;
241import com.android.server.IntentResolver;
242import com.android.server.LocalServices;
243import com.android.server.ServiceThread;
244import com.android.server.SystemConfig;
245import com.android.server.Watchdog;
246import com.android.server.pm.PermissionsState.PermissionState;
247import com.android.server.pm.Settings.DatabaseVersion;
248import com.android.server.pm.Settings.VersionInfo;
249import com.android.server.storage.DeviceStorageMonitorInternal;
250
251import dalvik.system.CloseGuard;
252import dalvik.system.DexFile;
253import dalvik.system.VMRuntime;
254
255import libcore.io.IoUtils;
256import libcore.util.EmptyArray;
257
258import org.xmlpull.v1.XmlPullParser;
259import org.xmlpull.v1.XmlPullParserException;
260import org.xmlpull.v1.XmlSerializer;
261
262import java.io.BufferedInputStream;
263import java.io.BufferedOutputStream;
264import java.io.BufferedReader;
265import java.io.ByteArrayInputStream;
266import java.io.ByteArrayOutputStream;
267import java.io.File;
268import java.io.FileDescriptor;
269import java.io.FileNotFoundException;
270import java.io.FileOutputStream;
271import java.io.FileReader;
272import java.io.FilenameFilter;
273import java.io.IOException;
274import java.io.InputStream;
275import java.io.PrintWriter;
276import java.nio.charset.StandardCharsets;
277import java.security.MessageDigest;
278import java.security.NoSuchAlgorithmException;
279import java.security.PublicKey;
280import java.security.cert.Certificate;
281import java.security.cert.CertificateEncodingException;
282import java.security.cert.CertificateException;
283import java.text.SimpleDateFormat;
284import java.util.ArrayList;
285import java.util.Arrays;
286import java.util.Collection;
287import java.util.Collections;
288import java.util.Comparator;
289import java.util.Date;
290import java.util.HashSet;
291import java.util.Iterator;
292import java.util.List;
293import java.util.Map;
294import java.util.Objects;
295import java.util.Set;
296import java.util.concurrent.CountDownLatch;
297import java.util.concurrent.TimeUnit;
298import java.util.concurrent.atomic.AtomicBoolean;
299import java.util.concurrent.atomic.AtomicInteger;
300import java.util.concurrent.atomic.AtomicLong;
301
302/**
303 * Keep track of all those APKs everywhere.
304 * <p>
305 * Internally there are two important locks:
306 * <ul>
307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
308 * and other related state. It is a fine-grained lock that should only be held
309 * momentarily, as it's one of the most contended locks in the system.
310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
311 * operations typically involve heavy lifting of application data on disk. Since
312 * {@code installd} is single-threaded, and it's operations can often be slow,
313 * this lock should never be acquired while already holding {@link #mPackages}.
314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
315 * holding {@link #mInstallLock}.
316 * </ul>
317 * Many internal methods rely on the caller to hold the appropriate locks, and
318 * this contract is expressed through method name suffixes:
319 * <ul>
320 * <li>fooLI(): the caller must hold {@link #mInstallLock}
321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
322 * being modified must be frozen
323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
325 * </ul>
326 * <p>
327 * Because this class is very central to the platform's security; please run all
328 * CTS and unit tests whenever making modifications:
329 *
330 * <pre>
331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
333 * </pre>
334 */
335public class PackageManagerService extends IPackageManager.Stub {
336    static final String TAG = "PackageManager";
337    static final boolean DEBUG_SETTINGS = false;
338    static final boolean DEBUG_PREFERRED = false;
339    static final boolean DEBUG_UPGRADE = false;
340    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
341    private static final boolean DEBUG_BACKUP = false;
342    private static final boolean DEBUG_INSTALL = false;
343    private static final boolean DEBUG_REMOVE = false;
344    private static final boolean DEBUG_BROADCASTS = false;
345    private static final boolean DEBUG_SHOW_INFO = false;
346    private static final boolean DEBUG_PACKAGE_INFO = false;
347    private static final boolean DEBUG_INTENT_MATCHING = false;
348    private static final boolean DEBUG_PACKAGE_SCANNING = false;
349    private static final boolean DEBUG_VERIFY = false;
350    private static final boolean DEBUG_FILTERS = false;
351
352    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
353    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
354    // user, but by default initialize to this.
355    static final boolean DEBUG_DEXOPT = false;
356
357    private static final boolean DEBUG_ABI_SELECTION = false;
358    private static final boolean DEBUG_EPHEMERAL = false;
359    private static final boolean DEBUG_TRIAGED_MISSING = false;
360    private static final boolean DEBUG_APP_DATA = false;
361
362    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
363
364    private static final boolean DISABLE_EPHEMERAL_APPS = true;
365
366    private static final int RADIO_UID = Process.PHONE_UID;
367    private static final int LOG_UID = Process.LOG_UID;
368    private static final int NFC_UID = Process.NFC_UID;
369    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
370    private static final int SHELL_UID = Process.SHELL_UID;
371
372    // Cap the size of permission trees that 3rd party apps can define
373    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
374
375    // Suffix used during package installation when copying/moving
376    // package apks to install directory.
377    private static final String INSTALL_PACKAGE_SUFFIX = "-";
378
379    static final int SCAN_NO_DEX = 1<<1;
380    static final int SCAN_FORCE_DEX = 1<<2;
381    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
382    static final int SCAN_NEW_INSTALL = 1<<4;
383    static final int SCAN_NO_PATHS = 1<<5;
384    static final int SCAN_UPDATE_TIME = 1<<6;
385    static final int SCAN_DEFER_DEX = 1<<7;
386    static final int SCAN_BOOTING = 1<<8;
387    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
388    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
389    static final int SCAN_REPLACING = 1<<11;
390    static final int SCAN_REQUIRE_KNOWN = 1<<12;
391    static final int SCAN_MOVE = 1<<13;
392    static final int SCAN_INITIAL = 1<<14;
393    static final int SCAN_CHECK_ONLY = 1<<15;
394    static final int SCAN_DONT_KILL_APP = 1<<17;
395    static final int SCAN_IGNORE_FROZEN = 1<<18;
396
397    static final int REMOVE_CHATTY = 1<<16;
398
399    private static final int[] EMPTY_INT_ARRAY = new int[0];
400
401    /**
402     * Timeout (in milliseconds) after which the watchdog should declare that
403     * our handler thread is wedged.  The usual default for such things is one
404     * minute but we sometimes do very lengthy I/O operations on this thread,
405     * such as installing multi-gigabyte applications, so ours needs to be longer.
406     */
407    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
408
409    /**
410     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
411     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
412     * settings entry if available, otherwise we use the hardcoded default.  If it's been
413     * more than this long since the last fstrim, we force one during the boot sequence.
414     *
415     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
416     * one gets run at the next available charging+idle time.  This final mandatory
417     * no-fstrim check kicks in only of the other scheduling criteria is never met.
418     */
419    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
420
421    /**
422     * Whether verification is enabled by default.
423     */
424    private static final boolean DEFAULT_VERIFY_ENABLE = true;
425
426    /**
427     * The default maximum time to wait for the verification agent to return in
428     * milliseconds.
429     */
430    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
431
432    /**
433     * The default response for package verification timeout.
434     *
435     * This can be either PackageManager.VERIFICATION_ALLOW or
436     * PackageManager.VERIFICATION_REJECT.
437     */
438    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
439
440    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
441
442    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
443            DEFAULT_CONTAINER_PACKAGE,
444            "com.android.defcontainer.DefaultContainerService");
445
446    private static final String KILL_APP_REASON_GIDS_CHANGED =
447            "permission grant or revoke changed gids";
448
449    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
450            "permissions revoked";
451
452    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
453
454    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
455
456    /** Permission grant: not grant the permission. */
457    private static final int GRANT_DENIED = 1;
458
459    /** Permission grant: grant the permission as an install permission. */
460    private static final int GRANT_INSTALL = 2;
461
462    /** Permission grant: grant the permission as a runtime one. */
463    private static final int GRANT_RUNTIME = 3;
464
465    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
466    private static final int GRANT_UPGRADE = 4;
467
468    /** Canonical intent used to identify what counts as a "web browser" app */
469    private static final Intent sBrowserIntent;
470    static {
471        sBrowserIntent = new Intent();
472        sBrowserIntent.setAction(Intent.ACTION_VIEW);
473        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
474        sBrowserIntent.setData(Uri.parse("http:"));
475    }
476
477    /**
478     * The set of all protected actions [i.e. those actions for which a high priority
479     * intent filter is disallowed].
480     */
481    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
482    static {
483        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
484        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
486        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
487    }
488
489    // Compilation reasons.
490    public static final int REASON_FIRST_BOOT = 0;
491    public static final int REASON_BOOT = 1;
492    public static final int REASON_INSTALL = 2;
493    public static final int REASON_BACKGROUND_DEXOPT = 3;
494    public static final int REASON_AB_OTA = 4;
495    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
496    public static final int REASON_SHARED_APK = 6;
497    public static final int REASON_FORCED_DEXOPT = 7;
498
499    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
500
501    final ServiceThread mHandlerThread;
502
503    final PackageHandler mHandler;
504
505    private final ProcessLoggingHandler mProcessLoggingHandler;
506
507    /**
508     * Messages for {@link #mHandler} that need to wait for system ready before
509     * being dispatched.
510     */
511    private ArrayList<Message> mPostSystemReadyMessages;
512
513    final int mSdkVersion = Build.VERSION.SDK_INT;
514
515    final Context mContext;
516    final boolean mFactoryTest;
517    final boolean mOnlyCore;
518    final DisplayMetrics mMetrics;
519    final int mDefParseFlags;
520    final String[] mSeparateProcesses;
521    final boolean mIsUpgrade;
522    final boolean mIsPreNUpgrade;
523
524    /** The location for ASEC container files on internal storage. */
525    final String mAsecInternalPath;
526
527    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
528    // LOCK HELD.  Can be called with mInstallLock held.
529    @GuardedBy("mInstallLock")
530    final Installer mInstaller;
531
532    /** Directory where installed third-party apps stored */
533    final File mAppInstallDir;
534    final File mEphemeralInstallDir;
535
536    /**
537     * Directory to which applications installed internally have their
538     * 32 bit native libraries copied.
539     */
540    private File mAppLib32InstallDir;
541
542    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
543    // apps.
544    final File mDrmAppPrivateInstallDir;
545
546    // ----------------------------------------------------------------
547
548    // Lock for state used when installing and doing other long running
549    // operations.  Methods that must be called with this lock held have
550    // the suffix "LI".
551    final Object mInstallLock = new Object();
552
553    // ----------------------------------------------------------------
554
555    // Keys are String (package name), values are Package.  This also serves
556    // as the lock for the global state.  Methods that must be called with
557    // this lock held have the prefix "LP".
558    @GuardedBy("mPackages")
559    final ArrayMap<String, PackageParser.Package> mPackages =
560            new ArrayMap<String, PackageParser.Package>();
561
562    final ArrayMap<String, Set<String>> mKnownCodebase =
563            new ArrayMap<String, Set<String>>();
564
565    // Tracks available target package names -> overlay package paths.
566    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
567        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
568
569    /**
570     * Tracks new system packages [received in an OTA] that we expect to
571     * find updated user-installed versions. Keys are package name, values
572     * are package location.
573     */
574    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
575    /**
576     * Tracks high priority intent filters for protected actions. During boot, certain
577     * filter actions are protected and should never be allowed to have a high priority
578     * intent filter for them. However, there is one, and only one exception -- the
579     * setup wizard. It must be able to define a high priority intent filter for these
580     * actions to ensure there are no escapes from the wizard. We need to delay processing
581     * of these during boot as we need to look at all of the system packages in order
582     * to know which component is the setup wizard.
583     */
584    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
585    /**
586     * Whether or not processing protected filters should be deferred.
587     */
588    private boolean mDeferProtectedFilters = true;
589
590    /**
591     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
592     */
593    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
594    /**
595     * Whether or not system app permissions should be promoted from install to runtime.
596     */
597    boolean mPromoteSystemApps;
598
599    @GuardedBy("mPackages")
600    final Settings mSettings;
601
602    /**
603     * Set of package names that are currently "frozen", which means active
604     * surgery is being done on the code/data for that package. The platform
605     * will refuse to launch frozen packages to avoid race conditions.
606     *
607     * @see PackageFreezer
608     */
609    @GuardedBy("mPackages")
610    final ArraySet<String> mFrozenPackages = new ArraySet<>();
611
612    boolean mRestoredSettings;
613
614    // System configuration read by SystemConfig.
615    final int[] mGlobalGids;
616    final SparseArray<ArraySet<String>> mSystemPermissions;
617    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
618
619    // If mac_permissions.xml was found for seinfo labeling.
620    boolean mFoundPolicyFile;
621
622    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
623
624    public static final class SharedLibraryEntry {
625        public final String path;
626        public final String apk;
627
628        SharedLibraryEntry(String _path, String _apk) {
629            path = _path;
630            apk = _apk;
631        }
632    }
633
634    // Currently known shared libraries.
635    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
636            new ArrayMap<String, SharedLibraryEntry>();
637
638    // All available activities, for your resolving pleasure.
639    final ActivityIntentResolver mActivities =
640            new ActivityIntentResolver();
641
642    // All available receivers, for your resolving pleasure.
643    final ActivityIntentResolver mReceivers =
644            new ActivityIntentResolver();
645
646    // All available services, for your resolving pleasure.
647    final ServiceIntentResolver mServices = new ServiceIntentResolver();
648
649    // All available providers, for your resolving pleasure.
650    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
651
652    // Mapping from provider base names (first directory in content URI codePath)
653    // to the provider information.
654    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
655            new ArrayMap<String, PackageParser.Provider>();
656
657    // Mapping from instrumentation class names to info about them.
658    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
659            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
660
661    // Mapping from permission names to info about them.
662    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
663            new ArrayMap<String, PackageParser.PermissionGroup>();
664
665    // Packages whose data we have transfered into another package, thus
666    // should no longer exist.
667    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
668
669    // Broadcast actions that are only available to the system.
670    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
671
672    /** List of packages waiting for verification. */
673    final SparseArray<PackageVerificationState> mPendingVerification
674            = new SparseArray<PackageVerificationState>();
675
676    /** Set of packages associated with each app op permission. */
677    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
678
679    final PackageInstallerService mInstallerService;
680
681    private final PackageDexOptimizer mPackageDexOptimizer;
682
683    private AtomicInteger mNextMoveId = new AtomicInteger();
684    private final MoveCallbacks mMoveCallbacks;
685
686    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
687
688    // Cache of users who need badging.
689    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
690
691    /** Token for keys in mPendingVerification. */
692    private int mPendingVerificationToken = 0;
693
694    volatile boolean mSystemReady;
695    volatile boolean mSafeMode;
696    volatile boolean mHasSystemUidErrors;
697
698    ApplicationInfo mAndroidApplication;
699    final ActivityInfo mResolveActivity = new ActivityInfo();
700    final ResolveInfo mResolveInfo = new ResolveInfo();
701    ComponentName mResolveComponentName;
702    PackageParser.Package mPlatformPackage;
703    ComponentName mCustomResolverComponentName;
704
705    boolean mResolverReplaced = false;
706
707    private final @Nullable ComponentName mIntentFilterVerifierComponent;
708    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
709
710    private int mIntentFilterVerificationToken = 0;
711
712    /** Component that knows whether or not an ephemeral application exists */
713    final ComponentName mEphemeralResolverComponent;
714    /** The service connection to the ephemeral resolver */
715    final EphemeralResolverConnection mEphemeralResolverConnection;
716
717    /** Component used to install ephemeral applications */
718    final ComponentName mEphemeralInstallerComponent;
719    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
720    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
721
722    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
723            = new SparseArray<IntentFilterVerificationState>();
724
725    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
726            new DefaultPermissionGrantPolicy(this);
727
728    // List of packages names to keep cached, even if they are uninstalled for all users
729    private List<String> mKeepUninstalledPackages;
730
731    private static class IFVerificationParams {
732        PackageParser.Package pkg;
733        boolean replacing;
734        int userId;
735        int verifierUid;
736
737        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
738                int _userId, int _verifierUid) {
739            pkg = _pkg;
740            replacing = _replacing;
741            userId = _userId;
742            replacing = _replacing;
743            verifierUid = _verifierUid;
744        }
745    }
746
747    private interface IntentFilterVerifier<T extends IntentFilter> {
748        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
749                                               T filter, String packageName);
750        void startVerifications(int userId);
751        void receiveVerificationResponse(int verificationId);
752    }
753
754    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
755        private Context mContext;
756        private ComponentName mIntentFilterVerifierComponent;
757        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
758
759        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
760            mContext = context;
761            mIntentFilterVerifierComponent = verifierComponent;
762        }
763
764        private String getDefaultScheme() {
765            return IntentFilter.SCHEME_HTTPS;
766        }
767
768        @Override
769        public void startVerifications(int userId) {
770            // Launch verifications requests
771            int count = mCurrentIntentFilterVerifications.size();
772            for (int n=0; n<count; n++) {
773                int verificationId = mCurrentIntentFilterVerifications.get(n);
774                final IntentFilterVerificationState ivs =
775                        mIntentFilterVerificationStates.get(verificationId);
776
777                String packageName = ivs.getPackageName();
778
779                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
780                final int filterCount = filters.size();
781                ArraySet<String> domainsSet = new ArraySet<>();
782                for (int m=0; m<filterCount; m++) {
783                    PackageParser.ActivityIntentInfo filter = filters.get(m);
784                    domainsSet.addAll(filter.getHostsList());
785                }
786                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
787                synchronized (mPackages) {
788                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
789                            packageName, domainsList) != null) {
790                        scheduleWriteSettingsLocked();
791                    }
792                }
793                sendVerificationRequest(userId, verificationId, ivs);
794            }
795            mCurrentIntentFilterVerifications.clear();
796        }
797
798        private void sendVerificationRequest(int userId, int verificationId,
799                IntentFilterVerificationState ivs) {
800
801            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
802            verificationIntent.putExtra(
803                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
804                    verificationId);
805            verificationIntent.putExtra(
806                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
807                    getDefaultScheme());
808            verificationIntent.putExtra(
809                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
810                    ivs.getHostsString());
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
813                    ivs.getPackageName());
814            verificationIntent.setComponent(mIntentFilterVerifierComponent);
815            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
816
817            UserHandle user = new UserHandle(userId);
818            mContext.sendBroadcastAsUser(verificationIntent, user);
819            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
820                    "Sending IntentFilter verification broadcast");
821        }
822
823        public void receiveVerificationResponse(int verificationId) {
824            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
825
826            final boolean verified = ivs.isVerified();
827
828            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
829            final int count = filters.size();
830            if (DEBUG_DOMAIN_VERIFICATION) {
831                Slog.i(TAG, "Received verification response " + verificationId
832                        + " for " + count + " filters, verified=" + verified);
833            }
834            for (int n=0; n<count; n++) {
835                PackageParser.ActivityIntentInfo filter = filters.get(n);
836                filter.setVerified(verified);
837
838                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
839                        + " verified with result:" + verified + " and hosts:"
840                        + ivs.getHostsString());
841            }
842
843            mIntentFilterVerificationStates.remove(verificationId);
844
845            final String packageName = ivs.getPackageName();
846            IntentFilterVerificationInfo ivi = null;
847
848            synchronized (mPackages) {
849                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
850            }
851            if (ivi == null) {
852                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
853                        + verificationId + " packageName:" + packageName);
854                return;
855            }
856            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
857                    "Updating IntentFilterVerificationInfo for package " + packageName
858                            +" verificationId:" + verificationId);
859
860            synchronized (mPackages) {
861                if (verified) {
862                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
863                } else {
864                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
865                }
866                scheduleWriteSettingsLocked();
867
868                final int userId = ivs.getUserId();
869                if (userId != UserHandle.USER_ALL) {
870                    final int userStatus =
871                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
872
873                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
874                    boolean needUpdate = false;
875
876                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
877                    // already been set by the User thru the Disambiguation dialog
878                    switch (userStatus) {
879                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
880                            if (verified) {
881                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
882                            } else {
883                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
884                            }
885                            needUpdate = true;
886                            break;
887
888                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
889                            if (verified) {
890                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
891                                needUpdate = true;
892                            }
893                            break;
894
895                        default:
896                            // Nothing to do
897                    }
898
899                    if (needUpdate) {
900                        mSettings.updateIntentFilterVerificationStatusLPw(
901                                packageName, updatedStatus, userId);
902                        scheduleWritePackageRestrictionsLocked(userId);
903                    }
904                }
905            }
906        }
907
908        @Override
909        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
910                    ActivityIntentInfo filter, String packageName) {
911            if (!hasValidDomains(filter)) {
912                return false;
913            }
914            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
915            if (ivs == null) {
916                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
917                        packageName);
918            }
919            if (DEBUG_DOMAIN_VERIFICATION) {
920                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
921            }
922            ivs.addFilter(filter);
923            return true;
924        }
925
926        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
927                int userId, int verificationId, String packageName) {
928            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
929                    verifierUid, userId, packageName);
930            ivs.setPendingState();
931            synchronized (mPackages) {
932                mIntentFilterVerificationStates.append(verificationId, ivs);
933                mCurrentIntentFilterVerifications.add(verificationId);
934            }
935            return ivs;
936        }
937    }
938
939    private static boolean hasValidDomains(ActivityIntentInfo filter) {
940        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
941                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
942                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
943    }
944
945    // Set of pending broadcasts for aggregating enable/disable of components.
946    static class PendingPackageBroadcasts {
947        // for each user id, a map of <package name -> components within that package>
948        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
949
950        public PendingPackageBroadcasts() {
951            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
952        }
953
954        public ArrayList<String> get(int userId, String packageName) {
955            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
956            return packages.get(packageName);
957        }
958
959        public void put(int userId, String packageName, ArrayList<String> components) {
960            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
961            packages.put(packageName, components);
962        }
963
964        public void remove(int userId, String packageName) {
965            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
966            if (packages != null) {
967                packages.remove(packageName);
968            }
969        }
970
971        public void remove(int userId) {
972            mUidMap.remove(userId);
973        }
974
975        public int userIdCount() {
976            return mUidMap.size();
977        }
978
979        public int userIdAt(int n) {
980            return mUidMap.keyAt(n);
981        }
982
983        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
984            return mUidMap.get(userId);
985        }
986
987        public int size() {
988            // total number of pending broadcast entries across all userIds
989            int num = 0;
990            for (int i = 0; i< mUidMap.size(); i++) {
991                num += mUidMap.valueAt(i).size();
992            }
993            return num;
994        }
995
996        public void clear() {
997            mUidMap.clear();
998        }
999
1000        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1001            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1002            if (map == null) {
1003                map = new ArrayMap<String, ArrayList<String>>();
1004                mUidMap.put(userId, map);
1005            }
1006            return map;
1007        }
1008    }
1009    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1010
1011    // Service Connection to remote media container service to copy
1012    // package uri's from external media onto secure containers
1013    // or internal storage.
1014    private IMediaContainerService mContainerService = null;
1015
1016    static final int SEND_PENDING_BROADCAST = 1;
1017    static final int MCS_BOUND = 3;
1018    static final int END_COPY = 4;
1019    static final int INIT_COPY = 5;
1020    static final int MCS_UNBIND = 6;
1021    static final int START_CLEANING_PACKAGE = 7;
1022    static final int FIND_INSTALL_LOC = 8;
1023    static final int POST_INSTALL = 9;
1024    static final int MCS_RECONNECT = 10;
1025    static final int MCS_GIVE_UP = 11;
1026    static final int UPDATED_MEDIA_STATUS = 12;
1027    static final int WRITE_SETTINGS = 13;
1028    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1029    static final int PACKAGE_VERIFIED = 15;
1030    static final int CHECK_PENDING_VERIFICATION = 16;
1031    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1032    static final int INTENT_FILTER_VERIFIED = 18;
1033
1034    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1035
1036    // Delay time in millisecs
1037    static final int BROADCAST_DELAY = 10 * 1000;
1038
1039    static UserManagerService sUserManager;
1040
1041    // Stores a list of users whose package restrictions file needs to be updated
1042    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1043
1044    final private DefaultContainerConnection mDefContainerConn =
1045            new DefaultContainerConnection();
1046    class DefaultContainerConnection implements ServiceConnection {
1047        public void onServiceConnected(ComponentName name, IBinder service) {
1048            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1049            IMediaContainerService imcs =
1050                IMediaContainerService.Stub.asInterface(service);
1051            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1052        }
1053
1054        public void onServiceDisconnected(ComponentName name) {
1055            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1056        }
1057    }
1058
1059    // Recordkeeping of restore-after-install operations that are currently in flight
1060    // between the Package Manager and the Backup Manager
1061    static class PostInstallData {
1062        public InstallArgs args;
1063        public PackageInstalledInfo res;
1064
1065        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1066            args = _a;
1067            res = _r;
1068        }
1069    }
1070
1071    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1072    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1073
1074    // XML tags for backup/restore of various bits of state
1075    private static final String TAG_PREFERRED_BACKUP = "pa";
1076    private static final String TAG_DEFAULT_APPS = "da";
1077    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1078
1079    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1080    private static final String TAG_ALL_GRANTS = "rt-grants";
1081    private static final String TAG_GRANT = "grant";
1082    private static final String ATTR_PACKAGE_NAME = "pkg";
1083
1084    private static final String TAG_PERMISSION = "perm";
1085    private static final String ATTR_PERMISSION_NAME = "name";
1086    private static final String ATTR_IS_GRANTED = "g";
1087    private static final String ATTR_USER_SET = "set";
1088    private static final String ATTR_USER_FIXED = "fixed";
1089    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1090
1091    // System/policy permission grants are not backed up
1092    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1093            FLAG_PERMISSION_POLICY_FIXED
1094            | FLAG_PERMISSION_SYSTEM_FIXED
1095            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1096
1097    // And we back up these user-adjusted states
1098    private static final int USER_RUNTIME_GRANT_MASK =
1099            FLAG_PERMISSION_USER_SET
1100            | FLAG_PERMISSION_USER_FIXED
1101            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1102
1103    final @Nullable String mRequiredVerifierPackage;
1104    final @NonNull String mRequiredInstallerPackage;
1105    final @Nullable String mSetupWizardPackage;
1106    final @NonNull String mServicesSystemSharedLibraryPackageName;
1107
1108    private final PackageUsage mPackageUsage = new PackageUsage();
1109
1110    private class PackageUsage {
1111        private static final int WRITE_INTERVAL
1112            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1113
1114        private final Object mFileLock = new Object();
1115        private final AtomicLong mLastWritten = new AtomicLong(0);
1116        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1117
1118        private boolean mIsHistoricalPackageUsageAvailable = true;
1119
1120        boolean isHistoricalPackageUsageAvailable() {
1121            return mIsHistoricalPackageUsageAvailable;
1122        }
1123
1124        void write(boolean force) {
1125            if (force) {
1126                writeInternal();
1127                return;
1128            }
1129            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1130                && !DEBUG_DEXOPT) {
1131                return;
1132            }
1133            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1134                new Thread("PackageUsage_DiskWriter") {
1135                    @Override
1136                    public void run() {
1137                        try {
1138                            writeInternal();
1139                        } finally {
1140                            mBackgroundWriteRunning.set(false);
1141                        }
1142                    }
1143                }.start();
1144            }
1145        }
1146
1147        private void writeInternal() {
1148            synchronized (mPackages) {
1149                synchronized (mFileLock) {
1150                    AtomicFile file = getFile();
1151                    FileOutputStream f = null;
1152                    try {
1153                        f = file.startWrite();
1154                        BufferedOutputStream out = new BufferedOutputStream(f);
1155                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1156                        StringBuilder sb = new StringBuilder();
1157                        for (PackageParser.Package pkg : mPackages.values()) {
1158                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1159                                continue;
1160                            }
1161                            sb.setLength(0);
1162                            sb.append(pkg.packageName);
1163                            sb.append(' ');
1164                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1165                            sb.append('\n');
1166                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1167                        }
1168                        out.flush();
1169                        file.finishWrite(f);
1170                    } catch (IOException e) {
1171                        if (f != null) {
1172                            file.failWrite(f);
1173                        }
1174                        Log.e(TAG, "Failed to write package usage times", e);
1175                    }
1176                }
1177            }
1178            mLastWritten.set(SystemClock.elapsedRealtime());
1179        }
1180
1181        void readLP() {
1182            synchronized (mFileLock) {
1183                AtomicFile file = getFile();
1184                BufferedInputStream in = null;
1185                try {
1186                    in = new BufferedInputStream(file.openRead());
1187                    StringBuffer sb = new StringBuffer();
1188                    while (true) {
1189                        String packageName = readToken(in, sb, ' ');
1190                        if (packageName == null) {
1191                            break;
1192                        }
1193                        String timeInMillisString = readToken(in, sb, '\n');
1194                        if (timeInMillisString == null) {
1195                            throw new IOException("Failed to find last usage time for package "
1196                                                  + packageName);
1197                        }
1198                        PackageParser.Package pkg = mPackages.get(packageName);
1199                        if (pkg == null) {
1200                            continue;
1201                        }
1202                        long timeInMillis;
1203                        try {
1204                            timeInMillis = Long.parseLong(timeInMillisString);
1205                        } catch (NumberFormatException e) {
1206                            throw new IOException("Failed to parse " + timeInMillisString
1207                                                  + " as a long.", e);
1208                        }
1209                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1210                    }
1211                } catch (FileNotFoundException expected) {
1212                    mIsHistoricalPackageUsageAvailable = false;
1213                } catch (IOException e) {
1214                    Log.w(TAG, "Failed to read package usage times", e);
1215                } finally {
1216                    IoUtils.closeQuietly(in);
1217                }
1218            }
1219            mLastWritten.set(SystemClock.elapsedRealtime());
1220        }
1221
1222        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1223                throws IOException {
1224            sb.setLength(0);
1225            while (true) {
1226                int ch = in.read();
1227                if (ch == -1) {
1228                    if (sb.length() == 0) {
1229                        return null;
1230                    }
1231                    throw new IOException("Unexpected EOF");
1232                }
1233                if (ch == endOfToken) {
1234                    return sb.toString();
1235                }
1236                sb.append((char)ch);
1237            }
1238        }
1239
1240        private AtomicFile getFile() {
1241            File dataDir = Environment.getDataDirectory();
1242            File systemDir = new File(dataDir, "system");
1243            File fname = new File(systemDir, "package-usage.list");
1244            return new AtomicFile(fname);
1245        }
1246    }
1247
1248    class PackageHandler extends Handler {
1249        private boolean mBound = false;
1250        final ArrayList<HandlerParams> mPendingInstalls =
1251            new ArrayList<HandlerParams>();
1252
1253        private boolean connectToService() {
1254            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1255                    " DefaultContainerService");
1256            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1257            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1258            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1259                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1260                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1261                mBound = true;
1262                return true;
1263            }
1264            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1265            return false;
1266        }
1267
1268        private void disconnectService() {
1269            mContainerService = null;
1270            mBound = false;
1271            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1272            mContext.unbindService(mDefContainerConn);
1273            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1274        }
1275
1276        PackageHandler(Looper looper) {
1277            super(looper);
1278        }
1279
1280        public void handleMessage(Message msg) {
1281            try {
1282                doHandleMessage(msg);
1283            } finally {
1284                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1285            }
1286        }
1287
1288        void doHandleMessage(Message msg) {
1289            switch (msg.what) {
1290                case INIT_COPY: {
1291                    HandlerParams params = (HandlerParams) msg.obj;
1292                    int idx = mPendingInstalls.size();
1293                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1294                    // If a bind was already initiated we dont really
1295                    // need to do anything. The pending install
1296                    // will be processed later on.
1297                    if (!mBound) {
1298                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1299                                System.identityHashCode(mHandler));
1300                        // If this is the only one pending we might
1301                        // have to bind to the service again.
1302                        if (!connectToService()) {
1303                            Slog.e(TAG, "Failed to bind to media container service");
1304                            params.serviceError();
1305                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1306                                    System.identityHashCode(mHandler));
1307                            if (params.traceMethod != null) {
1308                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1309                                        params.traceCookie);
1310                            }
1311                            return;
1312                        } else {
1313                            // Once we bind to the service, the first
1314                            // pending request will be processed.
1315                            mPendingInstalls.add(idx, params);
1316                        }
1317                    } else {
1318                        mPendingInstalls.add(idx, params);
1319                        // Already bound to the service. Just make
1320                        // sure we trigger off processing the first request.
1321                        if (idx == 0) {
1322                            mHandler.sendEmptyMessage(MCS_BOUND);
1323                        }
1324                    }
1325                    break;
1326                }
1327                case MCS_BOUND: {
1328                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1329                    if (msg.obj != null) {
1330                        mContainerService = (IMediaContainerService) msg.obj;
1331                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1332                                System.identityHashCode(mHandler));
1333                    }
1334                    if (mContainerService == null) {
1335                        if (!mBound) {
1336                            // Something seriously wrong since we are not bound and we are not
1337                            // waiting for connection. Bail out.
1338                            Slog.e(TAG, "Cannot bind to media container service");
1339                            for (HandlerParams params : mPendingInstalls) {
1340                                // Indicate service bind error
1341                                params.serviceError();
1342                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1343                                        System.identityHashCode(params));
1344                                if (params.traceMethod != null) {
1345                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1346                                            params.traceMethod, params.traceCookie);
1347                                }
1348                                return;
1349                            }
1350                            mPendingInstalls.clear();
1351                        } else {
1352                            Slog.w(TAG, "Waiting to connect to media container service");
1353                        }
1354                    } else if (mPendingInstalls.size() > 0) {
1355                        HandlerParams params = mPendingInstalls.get(0);
1356                        if (params != null) {
1357                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1358                                    System.identityHashCode(params));
1359                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1360                            if (params.startCopy()) {
1361                                // We are done...  look for more work or to
1362                                // go idle.
1363                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1364                                        "Checking for more work or unbind...");
1365                                // Delete pending install
1366                                if (mPendingInstalls.size() > 0) {
1367                                    mPendingInstalls.remove(0);
1368                                }
1369                                if (mPendingInstalls.size() == 0) {
1370                                    if (mBound) {
1371                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1372                                                "Posting delayed MCS_UNBIND");
1373                                        removeMessages(MCS_UNBIND);
1374                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1375                                        // Unbind after a little delay, to avoid
1376                                        // continual thrashing.
1377                                        sendMessageDelayed(ubmsg, 10000);
1378                                    }
1379                                } else {
1380                                    // There are more pending requests in queue.
1381                                    // Just post MCS_BOUND message to trigger processing
1382                                    // of next pending install.
1383                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1384                                            "Posting MCS_BOUND for next work");
1385                                    mHandler.sendEmptyMessage(MCS_BOUND);
1386                                }
1387                            }
1388                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1389                        }
1390                    } else {
1391                        // Should never happen ideally.
1392                        Slog.w(TAG, "Empty queue");
1393                    }
1394                    break;
1395                }
1396                case MCS_RECONNECT: {
1397                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1398                    if (mPendingInstalls.size() > 0) {
1399                        if (mBound) {
1400                            disconnectService();
1401                        }
1402                        if (!connectToService()) {
1403                            Slog.e(TAG, "Failed to bind to media container service");
1404                            for (HandlerParams params : mPendingInstalls) {
1405                                // Indicate service bind error
1406                                params.serviceError();
1407                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1408                                        System.identityHashCode(params));
1409                            }
1410                            mPendingInstalls.clear();
1411                        }
1412                    }
1413                    break;
1414                }
1415                case MCS_UNBIND: {
1416                    // If there is no actual work left, then time to unbind.
1417                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1418
1419                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1420                        if (mBound) {
1421                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1422
1423                            disconnectService();
1424                        }
1425                    } else if (mPendingInstalls.size() > 0) {
1426                        // There are more pending requests in queue.
1427                        // Just post MCS_BOUND message to trigger processing
1428                        // of next pending install.
1429                        mHandler.sendEmptyMessage(MCS_BOUND);
1430                    }
1431
1432                    break;
1433                }
1434                case MCS_GIVE_UP: {
1435                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1436                    HandlerParams params = mPendingInstalls.remove(0);
1437                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1438                            System.identityHashCode(params));
1439                    break;
1440                }
1441                case SEND_PENDING_BROADCAST: {
1442                    String packages[];
1443                    ArrayList<String> components[];
1444                    int size = 0;
1445                    int uids[];
1446                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1447                    synchronized (mPackages) {
1448                        if (mPendingBroadcasts == null) {
1449                            return;
1450                        }
1451                        size = mPendingBroadcasts.size();
1452                        if (size <= 0) {
1453                            // Nothing to be done. Just return
1454                            return;
1455                        }
1456                        packages = new String[size];
1457                        components = new ArrayList[size];
1458                        uids = new int[size];
1459                        int i = 0;  // filling out the above arrays
1460
1461                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1462                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1463                            Iterator<Map.Entry<String, ArrayList<String>>> it
1464                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1465                                            .entrySet().iterator();
1466                            while (it.hasNext() && i < size) {
1467                                Map.Entry<String, ArrayList<String>> ent = it.next();
1468                                packages[i] = ent.getKey();
1469                                components[i] = ent.getValue();
1470                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1471                                uids[i] = (ps != null)
1472                                        ? UserHandle.getUid(packageUserId, ps.appId)
1473                                        : -1;
1474                                i++;
1475                            }
1476                        }
1477                        size = i;
1478                        mPendingBroadcasts.clear();
1479                    }
1480                    // Send broadcasts
1481                    for (int i = 0; i < size; i++) {
1482                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                    break;
1486                }
1487                case START_CLEANING_PACKAGE: {
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1489                    final String packageName = (String)msg.obj;
1490                    final int userId = msg.arg1;
1491                    final boolean andCode = msg.arg2 != 0;
1492                    synchronized (mPackages) {
1493                        if (userId == UserHandle.USER_ALL) {
1494                            int[] users = sUserManager.getUserIds();
1495                            for (int user : users) {
1496                                mSettings.addPackageToCleanLPw(
1497                                        new PackageCleanItem(user, packageName, andCode));
1498                            }
1499                        } else {
1500                            mSettings.addPackageToCleanLPw(
1501                                    new PackageCleanItem(userId, packageName, andCode));
1502                        }
1503                    }
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1505                    startCleaningPackages();
1506                } break;
1507                case POST_INSTALL: {
1508                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1509
1510                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1511                    mRunningInstalls.delete(msg.arg1);
1512
1513                    if (data != null) {
1514                        InstallArgs args = data.args;
1515                        PackageInstalledInfo parentRes = data.res;
1516
1517                        final boolean grantPermissions = (args.installFlags
1518                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1519                        final boolean killApp = (args.installFlags
1520                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1521                        final String[] grantedPermissions = args.installGrantPermissions;
1522
1523                        // Handle the parent package
1524                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1525                                grantedPermissions, args.observer);
1526
1527                        // Handle the child packages
1528                        final int childCount = (parentRes.addedChildPackages != null)
1529                                ? parentRes.addedChildPackages.size() : 0;
1530                        for (int i = 0; i < childCount; i++) {
1531                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1532                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1533                                    grantedPermissions, args.observer);
1534                        }
1535
1536                        // Log tracing if needed
1537                        if (args.traceMethod != null) {
1538                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1539                                    args.traceCookie);
1540                        }
1541                    } else {
1542                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1543                    }
1544
1545                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1546                } break;
1547                case UPDATED_MEDIA_STATUS: {
1548                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1549                    boolean reportStatus = msg.arg1 == 1;
1550                    boolean doGc = msg.arg2 == 1;
1551                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1552                    if (doGc) {
1553                        // Force a gc to clear up stale containers.
1554                        Runtime.getRuntime().gc();
1555                    }
1556                    if (msg.obj != null) {
1557                        @SuppressWarnings("unchecked")
1558                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1559                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1560                        // Unload containers
1561                        unloadAllContainers(args);
1562                    }
1563                    if (reportStatus) {
1564                        try {
1565                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1566                            PackageHelper.getMountService().finishMediaUpdate();
1567                        } catch (RemoteException e) {
1568                            Log.e(TAG, "MountService not running?");
1569                        }
1570                    }
1571                } break;
1572                case WRITE_SETTINGS: {
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1574                    synchronized (mPackages) {
1575                        removeMessages(WRITE_SETTINGS);
1576                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1577                        mSettings.writeLPr();
1578                        mDirtyUsers.clear();
1579                    }
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1581                } break;
1582                case WRITE_PACKAGE_RESTRICTIONS: {
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1584                    synchronized (mPackages) {
1585                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1586                        for (int userId : mDirtyUsers) {
1587                            mSettings.writePackageRestrictionsLPr(userId);
1588                        }
1589                        mDirtyUsers.clear();
1590                    }
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1592                } break;
1593                case CHECK_PENDING_VERIFICATION: {
1594                    final int verificationId = msg.arg1;
1595                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1596
1597                    if ((state != null) && !state.timeoutExtended()) {
1598                        final InstallArgs args = state.getInstallArgs();
1599                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1600
1601                        Slog.i(TAG, "Verification timed out for " + originUri);
1602                        mPendingVerification.remove(verificationId);
1603
1604                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1605
1606                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1607                            Slog.i(TAG, "Continuing with installation of " + originUri);
1608                            state.setVerifierResponse(Binder.getCallingUid(),
1609                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1610                            broadcastPackageVerified(verificationId, originUri,
1611                                    PackageManager.VERIFICATION_ALLOW,
1612                                    state.getInstallArgs().getUser());
1613                            try {
1614                                ret = args.copyApk(mContainerService, true);
1615                            } catch (RemoteException e) {
1616                                Slog.e(TAG, "Could not contact the ContainerService");
1617                            }
1618                        } else {
1619                            broadcastPackageVerified(verificationId, originUri,
1620                                    PackageManager.VERIFICATION_REJECT,
1621                                    state.getInstallArgs().getUser());
1622                        }
1623
1624                        Trace.asyncTraceEnd(
1625                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1626
1627                        processPendingInstall(args, ret);
1628                        mHandler.sendEmptyMessage(MCS_UNBIND);
1629                    }
1630                    break;
1631                }
1632                case PACKAGE_VERIFIED: {
1633                    final int verificationId = msg.arg1;
1634
1635                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1636                    if (state == null) {
1637                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1638                        break;
1639                    }
1640
1641                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1642
1643                    state.setVerifierResponse(response.callerUid, response.code);
1644
1645                    if (state.isVerificationComplete()) {
1646                        mPendingVerification.remove(verificationId);
1647
1648                        final InstallArgs args = state.getInstallArgs();
1649                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1650
1651                        int ret;
1652                        if (state.isInstallAllowed()) {
1653                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1654                            broadcastPackageVerified(verificationId, originUri,
1655                                    response.code, state.getInstallArgs().getUser());
1656                            try {
1657                                ret = args.copyApk(mContainerService, true);
1658                            } catch (RemoteException e) {
1659                                Slog.e(TAG, "Could not contact the ContainerService");
1660                            }
1661                        } else {
1662                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1663                        }
1664
1665                        Trace.asyncTraceEnd(
1666                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1667
1668                        processPendingInstall(args, ret);
1669                        mHandler.sendEmptyMessage(MCS_UNBIND);
1670                    }
1671
1672                    break;
1673                }
1674                case START_INTENT_FILTER_VERIFICATIONS: {
1675                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1676                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1677                            params.replacing, params.pkg);
1678                    break;
1679                }
1680                case INTENT_FILTER_VERIFIED: {
1681                    final int verificationId = msg.arg1;
1682
1683                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1684                            verificationId);
1685                    if (state == null) {
1686                        Slog.w(TAG, "Invalid IntentFilter verification token "
1687                                + verificationId + " received");
1688                        break;
1689                    }
1690
1691                    final int userId = state.getUserId();
1692
1693                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1694                            "Processing IntentFilter verification with token:"
1695                            + verificationId + " and userId:" + userId);
1696
1697                    final IntentFilterVerificationResponse response =
1698                            (IntentFilterVerificationResponse) msg.obj;
1699
1700                    state.setVerifierResponse(response.callerUid, response.code);
1701
1702                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1703                            "IntentFilter verification with token:" + verificationId
1704                            + " and userId:" + userId
1705                            + " is settings verifier response with response code:"
1706                            + response.code);
1707
1708                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1709                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1710                                + response.getFailedDomainsString());
1711                    }
1712
1713                    if (state.isVerificationComplete()) {
1714                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1715                    } else {
1716                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1717                                "IntentFilter verification with token:" + verificationId
1718                                + " was not said to be complete");
1719                    }
1720
1721                    break;
1722                }
1723            }
1724        }
1725    }
1726
1727    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1728            boolean killApp, String[] grantedPermissions,
1729            IPackageInstallObserver2 installObserver) {
1730        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1731            // Send the removed broadcasts
1732            if (res.removedInfo != null) {
1733                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1734            }
1735
1736            // Now that we successfully installed the package, grant runtime
1737            // permissions if requested before broadcasting the install.
1738            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1739                    >= Build.VERSION_CODES.M) {
1740                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1741            }
1742
1743            final boolean update = res.removedInfo != null
1744                    && res.removedInfo.removedPackage != null;
1745
1746            // If this is the first time we have child packages for a disabled privileged
1747            // app that had no children, we grant requested runtime permissions to the new
1748            // children if the parent on the system image had them already granted.
1749            if (res.pkg.parentPackage != null) {
1750                synchronized (mPackages) {
1751                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1752                }
1753            }
1754
1755            synchronized (mPackages) {
1756                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1757            }
1758
1759            final String packageName = res.pkg.applicationInfo.packageName;
1760            Bundle extras = new Bundle(1);
1761            extras.putInt(Intent.EXTRA_UID, res.uid);
1762
1763            // Determine the set of users who are adding this package for
1764            // the first time vs. those who are seeing an update.
1765            int[] firstUsers = EMPTY_INT_ARRAY;
1766            int[] updateUsers = EMPTY_INT_ARRAY;
1767            if (res.origUsers == null || res.origUsers.length == 0) {
1768                firstUsers = res.newUsers;
1769            } else {
1770                for (int newUser : res.newUsers) {
1771                    boolean isNew = true;
1772                    for (int origUser : res.origUsers) {
1773                        if (origUser == newUser) {
1774                            isNew = false;
1775                            break;
1776                        }
1777                    }
1778                    if (isNew) {
1779                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1780                    } else {
1781                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1782                    }
1783                }
1784            }
1785
1786            // Send installed broadcasts if the install/update is not ephemeral
1787            if (!isEphemeral(res.pkg)) {
1788                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1789
1790                // Send added for users that see the package for the first time
1791                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1792                        extras, 0 /*flags*/, null /*targetPackage*/,
1793                        null /*finishedReceiver*/, firstUsers);
1794
1795                // Send added for users that don't see the package for the first time
1796                if (update) {
1797                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1798                }
1799                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1800                        extras, 0 /*flags*/, null /*targetPackage*/,
1801                        null /*finishedReceiver*/, updateUsers);
1802
1803                // Send replaced for users that don't see the package for the first time
1804                if (update) {
1805                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1806                            packageName, extras, 0 /*flags*/,
1807                            null /*targetPackage*/, null /*finishedReceiver*/,
1808                            updateUsers);
1809                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1810                            null /*package*/, null /*extras*/, 0 /*flags*/,
1811                            packageName /*targetPackage*/,
1812                            null /*finishedReceiver*/, updateUsers);
1813                }
1814
1815                // Send broadcast package appeared if forward locked/external for all users
1816                // treat asec-hosted packages like removable media on upgrade
1817                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1818                    if (DEBUG_INSTALL) {
1819                        Slog.i(TAG, "upgrading pkg " + res.pkg
1820                                + " is ASEC-hosted -> AVAILABLE");
1821                    }
1822                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1823                    ArrayList<String> pkgList = new ArrayList<>(1);
1824                    pkgList.add(packageName);
1825                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1826                }
1827            }
1828
1829            // Work that needs to happen on first install within each user
1830            if (firstUsers != null && firstUsers.length > 0) {
1831                synchronized (mPackages) {
1832                    for (int userId : firstUsers) {
1833                        // If this app is a browser and it's newly-installed for some
1834                        // users, clear any default-browser state in those users. The
1835                        // app's nature doesn't depend on the user, so we can just check
1836                        // its browser nature in any user and generalize.
1837                        if (packageIsBrowser(packageName, userId)) {
1838                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1839                        }
1840
1841                        // We may also need to apply pending (restored) runtime
1842                        // permission grants within these users.
1843                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1844                    }
1845                }
1846            }
1847
1848            // Log current value of "unknown sources" setting
1849            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1850                    getUnknownSourcesSettings());
1851
1852            // Force a gc to clear up things
1853            Runtime.getRuntime().gc();
1854
1855            // Remove the replaced package's older resources safely now
1856            // We delete after a gc for applications  on sdcard.
1857            if (res.removedInfo != null && res.removedInfo.args != null) {
1858                synchronized (mInstallLock) {
1859                    res.removedInfo.args.doPostDeleteLI(true);
1860                }
1861            }
1862        }
1863
1864        // If someone is watching installs - notify them
1865        if (installObserver != null) {
1866            try {
1867                Bundle extras = extrasForInstallResult(res);
1868                installObserver.onPackageInstalled(res.name, res.returnCode,
1869                        res.returnMsg, extras);
1870            } catch (RemoteException e) {
1871                Slog.i(TAG, "Observer no longer exists.");
1872            }
1873        }
1874    }
1875
1876    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1877            PackageParser.Package pkg) {
1878        if (pkg.parentPackage == null) {
1879            return;
1880        }
1881        if (pkg.requestedPermissions == null) {
1882            return;
1883        }
1884        final PackageSetting disabledSysParentPs = mSettings
1885                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1886        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1887                || !disabledSysParentPs.isPrivileged()
1888                || (disabledSysParentPs.childPackageNames != null
1889                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1890            return;
1891        }
1892        final int[] allUserIds = sUserManager.getUserIds();
1893        final int permCount = pkg.requestedPermissions.size();
1894        for (int i = 0; i < permCount; i++) {
1895            String permission = pkg.requestedPermissions.get(i);
1896            BasePermission bp = mSettings.mPermissions.get(permission);
1897            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1898                continue;
1899            }
1900            for (int userId : allUserIds) {
1901                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1902                        permission, userId)) {
1903                    grantRuntimePermission(pkg.packageName, permission, userId);
1904                }
1905            }
1906        }
1907    }
1908
1909    private StorageEventListener mStorageListener = new StorageEventListener() {
1910        @Override
1911        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1912            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1913                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1914                    final String volumeUuid = vol.getFsUuid();
1915
1916                    // Clean up any users or apps that were removed or recreated
1917                    // while this volume was missing
1918                    reconcileUsers(volumeUuid);
1919                    reconcileApps(volumeUuid);
1920
1921                    // Clean up any install sessions that expired or were
1922                    // cancelled while this volume was missing
1923                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1924
1925                    loadPrivatePackages(vol);
1926
1927                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1928                    unloadPrivatePackages(vol);
1929                }
1930            }
1931
1932            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1933                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1934                    updateExternalMediaStatus(true, false);
1935                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1936                    updateExternalMediaStatus(false, false);
1937                }
1938            }
1939        }
1940
1941        @Override
1942        public void onVolumeForgotten(String fsUuid) {
1943            if (TextUtils.isEmpty(fsUuid)) {
1944                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1945                return;
1946            }
1947
1948            // Remove any apps installed on the forgotten volume
1949            synchronized (mPackages) {
1950                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1951                for (PackageSetting ps : packages) {
1952                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1953                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1954                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1955                }
1956
1957                mSettings.onVolumeForgotten(fsUuid);
1958                mSettings.writeLPr();
1959            }
1960        }
1961    };
1962
1963    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1964            String[] grantedPermissions) {
1965        for (int userId : userIds) {
1966            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1967        }
1968
1969        // We could have touched GID membership, so flush out packages.list
1970        synchronized (mPackages) {
1971            mSettings.writePackageListLPr();
1972        }
1973    }
1974
1975    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1976            String[] grantedPermissions) {
1977        SettingBase sb = (SettingBase) pkg.mExtras;
1978        if (sb == null) {
1979            return;
1980        }
1981
1982        PermissionsState permissionsState = sb.getPermissionsState();
1983
1984        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1985                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1986
1987        synchronized (mPackages) {
1988            for (String permission : pkg.requestedPermissions) {
1989                BasePermission bp = mSettings.mPermissions.get(permission);
1990                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1991                        && (grantedPermissions == null
1992                               || ArrayUtils.contains(grantedPermissions, permission))) {
1993                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1994                    // Installer cannot change immutable permissions.
1995                    if ((flags & immutableFlags) == 0) {
1996                        grantRuntimePermission(pkg.packageName, permission, userId);
1997                    }
1998                }
1999            }
2000        }
2001    }
2002
2003    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2004        Bundle extras = null;
2005        switch (res.returnCode) {
2006            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2007                extras = new Bundle();
2008                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2009                        res.origPermission);
2010                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2011                        res.origPackage);
2012                break;
2013            }
2014            case PackageManager.INSTALL_SUCCEEDED: {
2015                extras = new Bundle();
2016                extras.putBoolean(Intent.EXTRA_REPLACING,
2017                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2018                break;
2019            }
2020        }
2021        return extras;
2022    }
2023
2024    void scheduleWriteSettingsLocked() {
2025        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2026            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2027        }
2028    }
2029
2030    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2031        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2032        scheduleWritePackageRestrictionsLocked(userId);
2033    }
2034
2035    void scheduleWritePackageRestrictionsLocked(int userId) {
2036        final int[] userIds = (userId == UserHandle.USER_ALL)
2037                ? sUserManager.getUserIds() : new int[]{userId};
2038        for (int nextUserId : userIds) {
2039            if (!sUserManager.exists(nextUserId)) return;
2040            mDirtyUsers.add(nextUserId);
2041            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2042                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2043            }
2044        }
2045    }
2046
2047    public static PackageManagerService main(Context context, Installer installer,
2048            boolean factoryTest, boolean onlyCore) {
2049        // Self-check for initial settings.
2050        PackageManagerServiceCompilerMapping.checkProperties();
2051
2052        PackageManagerService m = new PackageManagerService(context, installer,
2053                factoryTest, onlyCore);
2054        m.enableSystemUserPackages();
2055        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2056        // disabled after already being started.
2057        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2058                UserHandle.USER_SYSTEM);
2059        ServiceManager.addService("package", m);
2060        return m;
2061    }
2062
2063    private void enableSystemUserPackages() {
2064        if (!UserManager.isSplitSystemUser()) {
2065            return;
2066        }
2067        // For system user, enable apps based on the following conditions:
2068        // - app is whitelisted or belong to one of these groups:
2069        //   -- system app which has no launcher icons
2070        //   -- system app which has INTERACT_ACROSS_USERS permission
2071        //   -- system IME app
2072        // - app is not in the blacklist
2073        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2074        Set<String> enableApps = new ArraySet<>();
2075        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2076                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2077                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2078        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2079        enableApps.addAll(wlApps);
2080        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2081                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2082        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2083        enableApps.removeAll(blApps);
2084        Log.i(TAG, "Applications installed for system user: " + enableApps);
2085        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2086                UserHandle.SYSTEM);
2087        final int allAppsSize = allAps.size();
2088        synchronized (mPackages) {
2089            for (int i = 0; i < allAppsSize; i++) {
2090                String pName = allAps.get(i);
2091                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2092                // Should not happen, but we shouldn't be failing if it does
2093                if (pkgSetting == null) {
2094                    continue;
2095                }
2096                boolean install = enableApps.contains(pName);
2097                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2098                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2099                            + " for system user");
2100                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2101                }
2102            }
2103        }
2104    }
2105
2106    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2107        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2108                Context.DISPLAY_SERVICE);
2109        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2110    }
2111
2112    public PackageManagerService(Context context, Installer installer,
2113            boolean factoryTest, boolean onlyCore) {
2114        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2115                SystemClock.uptimeMillis());
2116
2117        if (mSdkVersion <= 0) {
2118            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2119        }
2120
2121        mContext = context;
2122        mFactoryTest = factoryTest;
2123        mOnlyCore = onlyCore;
2124        mMetrics = new DisplayMetrics();
2125        mSettings = new Settings(mPackages);
2126        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2127                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2128        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2129                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2130        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2131                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2132        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2133                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2134        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2135                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2136        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2137                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2138
2139        String separateProcesses = SystemProperties.get("debug.separate_processes");
2140        if (separateProcesses != null && separateProcesses.length() > 0) {
2141            if ("*".equals(separateProcesses)) {
2142                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2143                mSeparateProcesses = null;
2144                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2145            } else {
2146                mDefParseFlags = 0;
2147                mSeparateProcesses = separateProcesses.split(",");
2148                Slog.w(TAG, "Running with debug.separate_processes: "
2149                        + separateProcesses);
2150            }
2151        } else {
2152            mDefParseFlags = 0;
2153            mSeparateProcesses = null;
2154        }
2155
2156        mInstaller = installer;
2157        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2158                "*dexopt*");
2159        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2160
2161        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2162                FgThread.get().getLooper());
2163
2164        getDefaultDisplayMetrics(context, mMetrics);
2165
2166        SystemConfig systemConfig = SystemConfig.getInstance();
2167        mGlobalGids = systemConfig.getGlobalGids();
2168        mSystemPermissions = systemConfig.getSystemPermissions();
2169        mAvailableFeatures = systemConfig.getAvailableFeatures();
2170
2171        synchronized (mInstallLock) {
2172        // writer
2173        synchronized (mPackages) {
2174            mHandlerThread = new ServiceThread(TAG,
2175                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2176            mHandlerThread.start();
2177            mHandler = new PackageHandler(mHandlerThread.getLooper());
2178            mProcessLoggingHandler = new ProcessLoggingHandler();
2179            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2180
2181            File dataDir = Environment.getDataDirectory();
2182            mAppInstallDir = new File(dataDir, "app");
2183            mAppLib32InstallDir = new File(dataDir, "app-lib");
2184            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2185            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2186            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2187
2188            sUserManager = new UserManagerService(context, this, mPackages);
2189
2190            // Propagate permission configuration in to package manager.
2191            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2192                    = systemConfig.getPermissions();
2193            for (int i=0; i<permConfig.size(); i++) {
2194                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2195                BasePermission bp = mSettings.mPermissions.get(perm.name);
2196                if (bp == null) {
2197                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2198                    mSettings.mPermissions.put(perm.name, bp);
2199                }
2200                if (perm.gids != null) {
2201                    bp.setGids(perm.gids, perm.perUser);
2202                }
2203            }
2204
2205            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2206            for (int i=0; i<libConfig.size(); i++) {
2207                mSharedLibraries.put(libConfig.keyAt(i),
2208                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2209            }
2210
2211            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2212
2213            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2214
2215            String customResolverActivity = Resources.getSystem().getString(
2216                    R.string.config_customResolverActivity);
2217            if (TextUtils.isEmpty(customResolverActivity)) {
2218                customResolverActivity = null;
2219            } else {
2220                mCustomResolverComponentName = ComponentName.unflattenFromString(
2221                        customResolverActivity);
2222            }
2223
2224            long startTime = SystemClock.uptimeMillis();
2225
2226            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2227                    startTime);
2228
2229            // Set flag to monitor and not change apk file paths when
2230            // scanning install directories.
2231            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2232
2233            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2234            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2235
2236            if (bootClassPath == null) {
2237                Slog.w(TAG, "No BOOTCLASSPATH found!");
2238            }
2239
2240            if (systemServerClassPath == null) {
2241                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2242            }
2243
2244            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2245            final String[] dexCodeInstructionSets =
2246                    getDexCodeInstructionSets(
2247                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2248
2249            /**
2250             * Ensure all external libraries have had dexopt run on them.
2251             */
2252            if (mSharedLibraries.size() > 0) {
2253                // NOTE: For now, we're compiling these system "shared libraries"
2254                // (and framework jars) into all available architectures. It's possible
2255                // to compile them only when we come across an app that uses them (there's
2256                // already logic for that in scanPackageLI) but that adds some complexity.
2257                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2258                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2259                        final String lib = libEntry.path;
2260                        if (lib == null) {
2261                            continue;
2262                        }
2263
2264                        try {
2265                            // Shared libraries do not have profiles so we perform a full
2266                            // AOT compilation (if needed).
2267                            int dexoptNeeded = DexFile.getDexOptNeeded(
2268                                    lib, dexCodeInstructionSet,
2269                                    getCompilerFilterForReason(REASON_SHARED_APK),
2270                                    false /* newProfile */);
2271                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2272                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2273                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2274                                        getCompilerFilterForReason(REASON_SHARED_APK),
2275                                        StorageManager.UUID_PRIVATE_INTERNAL);
2276                            }
2277                        } catch (FileNotFoundException e) {
2278                            Slog.w(TAG, "Library not found: " + lib);
2279                        } catch (IOException | InstallerException e) {
2280                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2281                                    + e.getMessage());
2282                        }
2283                    }
2284                }
2285            }
2286
2287            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2288
2289            final VersionInfo ver = mSettings.getInternalVersion();
2290            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2291
2292            // when upgrading from pre-M, promote system app permissions from install to runtime
2293            mPromoteSystemApps =
2294                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2295
2296            // save off the names of pre-existing system packages prior to scanning; we don't
2297            // want to automatically grant runtime permissions for new system apps
2298            if (mPromoteSystemApps) {
2299                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2300                while (pkgSettingIter.hasNext()) {
2301                    PackageSetting ps = pkgSettingIter.next();
2302                    if (isSystemApp(ps)) {
2303                        mExistingSystemPackages.add(ps.name);
2304                    }
2305                }
2306            }
2307
2308            // When upgrading from pre-N, we need to handle package extraction like first boot,
2309            // as there is no profiling data available.
2310            mIsPreNUpgrade = !mSettings.isNWorkDone();
2311            mSettings.setNWorkDone();
2312
2313            // Collect vendor overlay packages.
2314            // (Do this before scanning any apps.)
2315            // For security and version matching reason, only consider
2316            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2317            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2318            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2319                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2320
2321            // Find base frameworks (resource packages without code).
2322            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2323                    | PackageParser.PARSE_IS_SYSTEM_DIR
2324                    | PackageParser.PARSE_IS_PRIVILEGED,
2325                    scanFlags | SCAN_NO_DEX, 0);
2326
2327            // Collected privileged system packages.
2328            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2329            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2330                    | PackageParser.PARSE_IS_SYSTEM_DIR
2331                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2332
2333            // Collect ordinary system packages.
2334            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2335            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2336                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2337
2338            // Collect all vendor packages.
2339            File vendorAppDir = new File("/vendor/app");
2340            try {
2341                vendorAppDir = vendorAppDir.getCanonicalFile();
2342            } catch (IOException e) {
2343                // failed to look up canonical path, continue with original one
2344            }
2345            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2346                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2347
2348            // Collect all OEM packages.
2349            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2350            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2351                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2352
2353            // Prune any system packages that no longer exist.
2354            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2355            if (!mOnlyCore) {
2356                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2357                while (psit.hasNext()) {
2358                    PackageSetting ps = psit.next();
2359
2360                    /*
2361                     * If this is not a system app, it can't be a
2362                     * disable system app.
2363                     */
2364                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2365                        continue;
2366                    }
2367
2368                    /*
2369                     * If the package is scanned, it's not erased.
2370                     */
2371                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2372                    if (scannedPkg != null) {
2373                        /*
2374                         * If the system app is both scanned and in the
2375                         * disabled packages list, then it must have been
2376                         * added via OTA. Remove it from the currently
2377                         * scanned package so the previously user-installed
2378                         * application can be scanned.
2379                         */
2380                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2381                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2382                                    + ps.name + "; removing system app.  Last known codePath="
2383                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2384                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2385                                    + scannedPkg.mVersionCode);
2386                            removePackageLI(scannedPkg, true);
2387                            mExpectingBetter.put(ps.name, ps.codePath);
2388                        }
2389
2390                        continue;
2391                    }
2392
2393                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2394                        psit.remove();
2395                        logCriticalInfo(Log.WARN, "System package " + ps.name
2396                                + " no longer exists; it's data will be wiped");
2397                        // Actual deletion of code and data will be handled by later
2398                        // reconciliation step
2399                    } else {
2400                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2401                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2402                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2403                        }
2404                    }
2405                }
2406            }
2407
2408            //look for any incomplete package installations
2409            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2410            for (int i = 0; i < deletePkgsList.size(); i++) {
2411                // Actual deletion of code and data will be handled by later
2412                // reconciliation step
2413                final String packageName = deletePkgsList.get(i).name;
2414                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2415                synchronized (mPackages) {
2416                    mSettings.removePackageLPw(packageName);
2417                }
2418            }
2419
2420            //delete tmp files
2421            deleteTempPackageFiles();
2422
2423            // Remove any shared userIDs that have no associated packages
2424            mSettings.pruneSharedUsersLPw();
2425
2426            if (!mOnlyCore) {
2427                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2428                        SystemClock.uptimeMillis());
2429                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2430
2431                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2432                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2433
2434                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2435                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2436
2437                /**
2438                 * Remove disable package settings for any updated system
2439                 * apps that were removed via an OTA. If they're not a
2440                 * previously-updated app, remove them completely.
2441                 * Otherwise, just revoke their system-level permissions.
2442                 */
2443                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2444                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2445                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2446
2447                    String msg;
2448                    if (deletedPkg == null) {
2449                        msg = "Updated system package " + deletedAppName
2450                                + " no longer exists; it's data will be wiped";
2451                        // Actual deletion of code and data will be handled by later
2452                        // reconciliation step
2453                    } else {
2454                        msg = "Updated system app + " + deletedAppName
2455                                + " no longer present; removing system privileges for "
2456                                + deletedAppName;
2457
2458                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2459
2460                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2461                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2462                    }
2463                    logCriticalInfo(Log.WARN, msg);
2464                }
2465
2466                /**
2467                 * Make sure all system apps that we expected to appear on
2468                 * the userdata partition actually showed up. If they never
2469                 * appeared, crawl back and revive the system version.
2470                 */
2471                for (int i = 0; i < mExpectingBetter.size(); i++) {
2472                    final String packageName = mExpectingBetter.keyAt(i);
2473                    if (!mPackages.containsKey(packageName)) {
2474                        final File scanFile = mExpectingBetter.valueAt(i);
2475
2476                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2477                                + " but never showed up; reverting to system");
2478
2479                        final int reparseFlags;
2480                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2481                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2482                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2483                                    | PackageParser.PARSE_IS_PRIVILEGED;
2484                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2485                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2486                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2487                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2488                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2489                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2490                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2491                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2492                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2493                        } else {
2494                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2495                            continue;
2496                        }
2497
2498                        mSettings.enableSystemPackageLPw(packageName);
2499
2500                        try {
2501                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2502                        } catch (PackageManagerException e) {
2503                            Slog.e(TAG, "Failed to parse original system package: "
2504                                    + e.getMessage());
2505                        }
2506                    }
2507                }
2508            }
2509            mExpectingBetter.clear();
2510
2511            // Resolve protected action filters. Only the setup wizard is allowed to
2512            // have a high priority filter for these actions.
2513            mSetupWizardPackage = getSetupWizardPackageName();
2514            if (mProtectedFilters.size() > 0) {
2515                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2516                    Slog.i(TAG, "No setup wizard;"
2517                        + " All protected intents capped to priority 0");
2518                }
2519                for (ActivityIntentInfo filter : mProtectedFilters) {
2520                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2521                        if (DEBUG_FILTERS) {
2522                            Slog.i(TAG, "Found setup wizard;"
2523                                + " allow priority " + filter.getPriority() + ";"
2524                                + " package: " + filter.activity.info.packageName
2525                                + " activity: " + filter.activity.className
2526                                + " priority: " + filter.getPriority());
2527                        }
2528                        // skip setup wizard; allow it to keep the high priority filter
2529                        continue;
2530                    }
2531                    Slog.w(TAG, "Protected action; cap priority to 0;"
2532                            + " package: " + filter.activity.info.packageName
2533                            + " activity: " + filter.activity.className
2534                            + " origPrio: " + filter.getPriority());
2535                    filter.setPriority(0);
2536                }
2537            }
2538            mDeferProtectedFilters = false;
2539            mProtectedFilters.clear();
2540
2541            // Now that we know all of the shared libraries, update all clients to have
2542            // the correct library paths.
2543            updateAllSharedLibrariesLPw();
2544
2545            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2546                // NOTE: We ignore potential failures here during a system scan (like
2547                // the rest of the commands above) because there's precious little we
2548                // can do about it. A settings error is reported, though.
2549                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2550                        false /* boot complete */);
2551            }
2552
2553            // Now that we know all the packages we are keeping,
2554            // read and update their last usage times.
2555            mPackageUsage.readLP();
2556
2557            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2558                    SystemClock.uptimeMillis());
2559            Slog.i(TAG, "Time to scan packages: "
2560                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2561                    + " seconds");
2562
2563            // If the platform SDK has changed since the last time we booted,
2564            // we need to re-grant app permission to catch any new ones that
2565            // appear.  This is really a hack, and means that apps can in some
2566            // cases get permissions that the user didn't initially explicitly
2567            // allow...  it would be nice to have some better way to handle
2568            // this situation.
2569            int updateFlags = UPDATE_PERMISSIONS_ALL;
2570            if (ver.sdkVersion != mSdkVersion) {
2571                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2572                        + mSdkVersion + "; regranting permissions for internal storage");
2573                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2574            }
2575            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2576            ver.sdkVersion = mSdkVersion;
2577
2578            // If this is the first boot or an update from pre-M, and it is a normal
2579            // boot, then we need to initialize the default preferred apps across
2580            // all defined users.
2581            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2582                for (UserInfo user : sUserManager.getUsers(true)) {
2583                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2584                    applyFactoryDefaultBrowserLPw(user.id);
2585                    primeDomainVerificationsLPw(user.id);
2586                }
2587            }
2588
2589            // Prepare storage for system user really early during boot,
2590            // since core system apps like SettingsProvider and SystemUI
2591            // can't wait for user to start
2592            final int storageFlags;
2593            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2594                storageFlags = StorageManager.FLAG_STORAGE_DE;
2595            } else {
2596                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2597            }
2598            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2599                    storageFlags);
2600
2601            // If this is first boot after an OTA, and a normal boot, then
2602            // we need to clear code cache directories.
2603            if (mIsUpgrade && !onlyCore) {
2604                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2605                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2606                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2607                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2608                        // No apps are running this early, so no need to freeze
2609                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2610                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2611                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2612                    }
2613                    clearAppProfilesLIF(ps.pkg);
2614                }
2615                ver.fingerprint = Build.FINGERPRINT;
2616            }
2617
2618            checkDefaultBrowser();
2619
2620            // clear only after permissions and other defaults have been updated
2621            mExistingSystemPackages.clear();
2622            mPromoteSystemApps = false;
2623
2624            // All the changes are done during package scanning.
2625            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2626
2627            // can downgrade to reader
2628            mSettings.writeLPr();
2629
2630            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2631                    SystemClock.uptimeMillis());
2632
2633            if (!mOnlyCore) {
2634                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2635                mRequiredInstallerPackage = getRequiredInstallerLPr();
2636                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2637                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2638                        mIntentFilterVerifierComponent);
2639                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2640                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2641                getRequiredSharedLibraryLPr(
2642                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2643            } else {
2644                mRequiredVerifierPackage = null;
2645                mRequiredInstallerPackage = null;
2646                mIntentFilterVerifierComponent = null;
2647                mIntentFilterVerifier = null;
2648                mServicesSystemSharedLibraryPackageName = null;
2649            }
2650
2651            mInstallerService = new PackageInstallerService(context, this);
2652
2653            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2654            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2655            // both the installer and resolver must be present to enable ephemeral
2656            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2657                if (DEBUG_EPHEMERAL) {
2658                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2659                            + " installer:" + ephemeralInstallerComponent);
2660                }
2661                mEphemeralResolverComponent = ephemeralResolverComponent;
2662                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2663                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2664                mEphemeralResolverConnection =
2665                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2666            } else {
2667                if (DEBUG_EPHEMERAL) {
2668                    final String missingComponent =
2669                            (ephemeralResolverComponent == null)
2670                            ? (ephemeralInstallerComponent == null)
2671                                    ? "resolver and installer"
2672                                    : "resolver"
2673                            : "installer";
2674                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2675                }
2676                mEphemeralResolverComponent = null;
2677                mEphemeralInstallerComponent = null;
2678                mEphemeralResolverConnection = null;
2679            }
2680
2681            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2682        } // synchronized (mPackages)
2683        } // synchronized (mInstallLock)
2684
2685        // Now after opening every single application zip, make sure they
2686        // are all flushed.  Not really needed, but keeps things nice and
2687        // tidy.
2688        Runtime.getRuntime().gc();
2689
2690        // The initial scanning above does many calls into installd while
2691        // holding the mPackages lock, but we're mostly interested in yelling
2692        // once we have a booted system.
2693        mInstaller.setWarnIfHeld(mPackages);
2694
2695        // Expose private service for system components to use.
2696        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2697    }
2698
2699    @Override
2700    public boolean isFirstBoot() {
2701        return !mRestoredSettings;
2702    }
2703
2704    @Override
2705    public boolean isOnlyCoreApps() {
2706        return mOnlyCore;
2707    }
2708
2709    @Override
2710    public boolean isUpgrade() {
2711        return mIsUpgrade;
2712    }
2713
2714    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2715        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2716
2717        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2718                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2719                UserHandle.USER_SYSTEM);
2720        if (matches.size() == 1) {
2721            return matches.get(0).getComponentInfo().packageName;
2722        } else {
2723            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2724            return null;
2725        }
2726    }
2727
2728    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2729        synchronized (mPackages) {
2730            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2731            if (libraryEntry == null) {
2732                throw new IllegalStateException("Missing required shared library:" + libraryName);
2733            }
2734            return libraryEntry.apk;
2735        }
2736    }
2737
2738    private @NonNull String getRequiredInstallerLPr() {
2739        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2740        intent.addCategory(Intent.CATEGORY_DEFAULT);
2741        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2742
2743        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2744                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2745                UserHandle.USER_SYSTEM);
2746        if (matches.size() == 1) {
2747            ResolveInfo resolveInfo = matches.get(0);
2748            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2749                throw new RuntimeException("The installer must be a privileged app");
2750            }
2751            return matches.get(0).getComponentInfo().packageName;
2752        } else {
2753            throw new RuntimeException("There must be exactly one installer; found " + matches);
2754        }
2755    }
2756
2757    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2758        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2759
2760        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2761                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2762                UserHandle.USER_SYSTEM);
2763        ResolveInfo best = null;
2764        final int N = matches.size();
2765        for (int i = 0; i < N; i++) {
2766            final ResolveInfo cur = matches.get(i);
2767            final String packageName = cur.getComponentInfo().packageName;
2768            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2769                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2770                continue;
2771            }
2772
2773            if (best == null || cur.priority > best.priority) {
2774                best = cur;
2775            }
2776        }
2777
2778        if (best != null) {
2779            return best.getComponentInfo().getComponentName();
2780        } else {
2781            throw new RuntimeException("There must be at least one intent filter verifier");
2782        }
2783    }
2784
2785    private @Nullable ComponentName getEphemeralResolverLPr() {
2786        final String[] packageArray =
2787                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2788        if (packageArray.length == 0) {
2789            if (DEBUG_EPHEMERAL) {
2790                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2791            }
2792            return null;
2793        }
2794
2795        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2796        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2797                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2798                UserHandle.USER_SYSTEM);
2799
2800        final int N = resolvers.size();
2801        if (N == 0) {
2802            if (DEBUG_EPHEMERAL) {
2803                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2804            }
2805            return null;
2806        }
2807
2808        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2809        for (int i = 0; i < N; i++) {
2810            final ResolveInfo info = resolvers.get(i);
2811
2812            if (info.serviceInfo == null) {
2813                continue;
2814            }
2815
2816            final String packageName = info.serviceInfo.packageName;
2817            if (!possiblePackages.contains(packageName)) {
2818                if (DEBUG_EPHEMERAL) {
2819                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2820                            + " pkg: " + packageName + ", info:" + info);
2821                }
2822                continue;
2823            }
2824
2825            if (DEBUG_EPHEMERAL) {
2826                Slog.v(TAG, "Ephemeral resolver found;"
2827                        + " pkg: " + packageName + ", info:" + info);
2828            }
2829            return new ComponentName(packageName, info.serviceInfo.name);
2830        }
2831        if (DEBUG_EPHEMERAL) {
2832            Slog.v(TAG, "Ephemeral resolver NOT found");
2833        }
2834        return null;
2835    }
2836
2837    private @Nullable ComponentName getEphemeralInstallerLPr() {
2838        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2839        intent.addCategory(Intent.CATEGORY_DEFAULT);
2840        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2841
2842        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2843                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2844                UserHandle.USER_SYSTEM);
2845        if (matches.size() == 0) {
2846            return null;
2847        } else if (matches.size() == 1) {
2848            return matches.get(0).getComponentInfo().getComponentName();
2849        } else {
2850            throw new RuntimeException(
2851                    "There must be at most one ephemeral installer; found " + matches);
2852        }
2853    }
2854
2855    private void primeDomainVerificationsLPw(int userId) {
2856        if (DEBUG_DOMAIN_VERIFICATION) {
2857            Slog.d(TAG, "Priming domain verifications in user " + userId);
2858        }
2859
2860        SystemConfig systemConfig = SystemConfig.getInstance();
2861        ArraySet<String> packages = systemConfig.getLinkedApps();
2862        ArraySet<String> domains = new ArraySet<String>();
2863
2864        for (String packageName : packages) {
2865            PackageParser.Package pkg = mPackages.get(packageName);
2866            if (pkg != null) {
2867                if (!pkg.isSystemApp()) {
2868                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2869                    continue;
2870                }
2871
2872                domains.clear();
2873                for (PackageParser.Activity a : pkg.activities) {
2874                    for (ActivityIntentInfo filter : a.intents) {
2875                        if (hasValidDomains(filter)) {
2876                            domains.addAll(filter.getHostsList());
2877                        }
2878                    }
2879                }
2880
2881                if (domains.size() > 0) {
2882                    if (DEBUG_DOMAIN_VERIFICATION) {
2883                        Slog.v(TAG, "      + " + packageName);
2884                    }
2885                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2886                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2887                    // and then 'always' in the per-user state actually used for intent resolution.
2888                    final IntentFilterVerificationInfo ivi;
2889                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2890                            new ArrayList<String>(domains));
2891                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2892                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2893                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2894                } else {
2895                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2896                            + "' does not handle web links");
2897                }
2898            } else {
2899                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2900            }
2901        }
2902
2903        scheduleWritePackageRestrictionsLocked(userId);
2904        scheduleWriteSettingsLocked();
2905    }
2906
2907    private void applyFactoryDefaultBrowserLPw(int userId) {
2908        // The default browser app's package name is stored in a string resource,
2909        // with a product-specific overlay used for vendor customization.
2910        String browserPkg = mContext.getResources().getString(
2911                com.android.internal.R.string.default_browser);
2912        if (!TextUtils.isEmpty(browserPkg)) {
2913            // non-empty string => required to be a known package
2914            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2915            if (ps == null) {
2916                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2917                browserPkg = null;
2918            } else {
2919                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2920            }
2921        }
2922
2923        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2924        // default.  If there's more than one, just leave everything alone.
2925        if (browserPkg == null) {
2926            calculateDefaultBrowserLPw(userId);
2927        }
2928    }
2929
2930    private void calculateDefaultBrowserLPw(int userId) {
2931        List<String> allBrowsers = resolveAllBrowserApps(userId);
2932        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2933        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2934    }
2935
2936    private List<String> resolveAllBrowserApps(int userId) {
2937        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2938        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2939                PackageManager.MATCH_ALL, userId);
2940
2941        final int count = list.size();
2942        List<String> result = new ArrayList<String>(count);
2943        for (int i=0; i<count; i++) {
2944            ResolveInfo info = list.get(i);
2945            if (info.activityInfo == null
2946                    || !info.handleAllWebDataURI
2947                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2948                    || result.contains(info.activityInfo.packageName)) {
2949                continue;
2950            }
2951            result.add(info.activityInfo.packageName);
2952        }
2953
2954        return result;
2955    }
2956
2957    private boolean packageIsBrowser(String packageName, int userId) {
2958        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2959                PackageManager.MATCH_ALL, userId);
2960        final int N = list.size();
2961        for (int i = 0; i < N; i++) {
2962            ResolveInfo info = list.get(i);
2963            if (packageName.equals(info.activityInfo.packageName)) {
2964                return true;
2965            }
2966        }
2967        return false;
2968    }
2969
2970    private void checkDefaultBrowser() {
2971        final int myUserId = UserHandle.myUserId();
2972        final String packageName = getDefaultBrowserPackageName(myUserId);
2973        if (packageName != null) {
2974            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2975            if (info == null) {
2976                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2977                synchronized (mPackages) {
2978                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2979                }
2980            }
2981        }
2982    }
2983
2984    @Override
2985    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2986            throws RemoteException {
2987        try {
2988            return super.onTransact(code, data, reply, flags);
2989        } catch (RuntimeException e) {
2990            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2991                Slog.wtf(TAG, "Package Manager Crash", e);
2992            }
2993            throw e;
2994        }
2995    }
2996
2997    static int[] appendInts(int[] cur, int[] add) {
2998        if (add == null) return cur;
2999        if (cur == null) return add;
3000        final int N = add.length;
3001        for (int i=0; i<N; i++) {
3002            cur = appendInt(cur, add[i]);
3003        }
3004        return cur;
3005    }
3006
3007    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        if (ps == null) {
3010            return null;
3011        }
3012        final PackageParser.Package p = ps.pkg;
3013        if (p == null) {
3014            return null;
3015        }
3016
3017        final PermissionsState permissionsState = ps.getPermissionsState();
3018
3019        final int[] gids = permissionsState.computeGids(userId);
3020        final Set<String> permissions = permissionsState.getPermissions(userId);
3021        final PackageUserState state = ps.readUserState(userId);
3022
3023        return PackageParser.generatePackageInfo(p, gids, flags,
3024                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3025    }
3026
3027    @Override
3028    public void checkPackageStartable(String packageName, int userId) {
3029        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3030
3031        synchronized (mPackages) {
3032            final PackageSetting ps = mSettings.mPackages.get(packageName);
3033            if (ps == null) {
3034                throw new SecurityException("Package " + packageName + " was not found!");
3035            }
3036
3037            if (!ps.getInstalled(userId)) {
3038                throw new SecurityException(
3039                        "Package " + packageName + " was not installed for user " + userId + "!");
3040            }
3041
3042            if (mSafeMode && !ps.isSystem()) {
3043                throw new SecurityException("Package " + packageName + " not a system app!");
3044            }
3045
3046            if (mFrozenPackages.contains(packageName)) {
3047                throw new SecurityException("Package " + packageName + " is currently frozen!");
3048            }
3049
3050            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3051                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3052                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3053            }
3054        }
3055    }
3056
3057    @Override
3058    public boolean isPackageAvailable(String packageName, int userId) {
3059        if (!sUserManager.exists(userId)) return false;
3060        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3061                false /* requireFullPermission */, false /* checkShell */, "is package available");
3062        synchronized (mPackages) {
3063            PackageParser.Package p = mPackages.get(packageName);
3064            if (p != null) {
3065                final PackageSetting ps = (PackageSetting) p.mExtras;
3066                if (ps != null) {
3067                    final PackageUserState state = ps.readUserState(userId);
3068                    if (state != null) {
3069                        return PackageParser.isAvailable(state);
3070                    }
3071                }
3072            }
3073        }
3074        return false;
3075    }
3076
3077    @Override
3078    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3079        if (!sUserManager.exists(userId)) return null;
3080        flags = updateFlagsForPackage(flags, userId, packageName);
3081        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3082                false /* requireFullPermission */, false /* checkShell */, "get package info");
3083        // reader
3084        synchronized (mPackages) {
3085            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3086            PackageParser.Package p = null;
3087            if (matchFactoryOnly) {
3088                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3089                if (ps != null) {
3090                    return generatePackageInfo(ps, flags, userId);
3091                }
3092            }
3093            if (p == null) {
3094                p = mPackages.get(packageName);
3095                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3096                    return null;
3097                }
3098            }
3099            if (DEBUG_PACKAGE_INFO)
3100                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3101            if (p != null) {
3102                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3103            }
3104            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3105                final PackageSetting ps = mSettings.mPackages.get(packageName);
3106                return generatePackageInfo(ps, flags, userId);
3107            }
3108        }
3109        return null;
3110    }
3111
3112    @Override
3113    public String[] currentToCanonicalPackageNames(String[] names) {
3114        String[] out = new String[names.length];
3115        // reader
3116        synchronized (mPackages) {
3117            for (int i=names.length-1; i>=0; i--) {
3118                PackageSetting ps = mSettings.mPackages.get(names[i]);
3119                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3120            }
3121        }
3122        return out;
3123    }
3124
3125    @Override
3126    public String[] canonicalToCurrentPackageNames(String[] names) {
3127        String[] out = new String[names.length];
3128        // reader
3129        synchronized (mPackages) {
3130            for (int i=names.length-1; i>=0; i--) {
3131                String cur = mSettings.mRenamedPackages.get(names[i]);
3132                out[i] = cur != null ? cur : names[i];
3133            }
3134        }
3135        return out;
3136    }
3137
3138    @Override
3139    public int getPackageUid(String packageName, int flags, int userId) {
3140        if (!sUserManager.exists(userId)) return -1;
3141        flags = updateFlagsForPackage(flags, userId, packageName);
3142        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3143                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3144
3145        // reader
3146        synchronized (mPackages) {
3147            final PackageParser.Package p = mPackages.get(packageName);
3148            if (p != null && p.isMatch(flags)) {
3149                return UserHandle.getUid(userId, p.applicationInfo.uid);
3150            }
3151            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3152                final PackageSetting ps = mSettings.mPackages.get(packageName);
3153                if (ps != null && ps.isMatch(flags)) {
3154                    return UserHandle.getUid(userId, ps.appId);
3155                }
3156            }
3157        }
3158
3159        return -1;
3160    }
3161
3162    @Override
3163    public int[] getPackageGids(String packageName, int flags, int userId) {
3164        if (!sUserManager.exists(userId)) return null;
3165        flags = updateFlagsForPackage(flags, userId, packageName);
3166        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3167                false /* requireFullPermission */, false /* checkShell */,
3168                "getPackageGids");
3169
3170        // reader
3171        synchronized (mPackages) {
3172            final PackageParser.Package p = mPackages.get(packageName);
3173            if (p != null && p.isMatch(flags)) {
3174                PackageSetting ps = (PackageSetting) p.mExtras;
3175                return ps.getPermissionsState().computeGids(userId);
3176            }
3177            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3178                final PackageSetting ps = mSettings.mPackages.get(packageName);
3179                if (ps != null && ps.isMatch(flags)) {
3180                    return ps.getPermissionsState().computeGids(userId);
3181                }
3182            }
3183        }
3184
3185        return null;
3186    }
3187
3188    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3189        if (bp.perm != null) {
3190            return PackageParser.generatePermissionInfo(bp.perm, flags);
3191        }
3192        PermissionInfo pi = new PermissionInfo();
3193        pi.name = bp.name;
3194        pi.packageName = bp.sourcePackage;
3195        pi.nonLocalizedLabel = bp.name;
3196        pi.protectionLevel = bp.protectionLevel;
3197        return pi;
3198    }
3199
3200    @Override
3201    public PermissionInfo getPermissionInfo(String name, int flags) {
3202        // reader
3203        synchronized (mPackages) {
3204            final BasePermission p = mSettings.mPermissions.get(name);
3205            if (p != null) {
3206                return generatePermissionInfo(p, flags);
3207            }
3208            return null;
3209        }
3210    }
3211
3212    @Override
3213    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3214            int flags) {
3215        // reader
3216        synchronized (mPackages) {
3217            if (group != null && !mPermissionGroups.containsKey(group)) {
3218                // This is thrown as NameNotFoundException
3219                return null;
3220            }
3221
3222            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3223            for (BasePermission p : mSettings.mPermissions.values()) {
3224                if (group == null) {
3225                    if (p.perm == null || p.perm.info.group == null) {
3226                        out.add(generatePermissionInfo(p, flags));
3227                    }
3228                } else {
3229                    if (p.perm != null && group.equals(p.perm.info.group)) {
3230                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3231                    }
3232                }
3233            }
3234            return new ParceledListSlice<>(out);
3235        }
3236    }
3237
3238    @Override
3239    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3240        // reader
3241        synchronized (mPackages) {
3242            return PackageParser.generatePermissionGroupInfo(
3243                    mPermissionGroups.get(name), flags);
3244        }
3245    }
3246
3247    @Override
3248    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3249        // reader
3250        synchronized (mPackages) {
3251            final int N = mPermissionGroups.size();
3252            ArrayList<PermissionGroupInfo> out
3253                    = new ArrayList<PermissionGroupInfo>(N);
3254            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3255                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3256            }
3257            return new ParceledListSlice<>(out);
3258        }
3259    }
3260
3261    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3262            int userId) {
3263        if (!sUserManager.exists(userId)) return null;
3264        PackageSetting ps = mSettings.mPackages.get(packageName);
3265        if (ps != null) {
3266            if (ps.pkg == null) {
3267                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3268                if (pInfo != null) {
3269                    return pInfo.applicationInfo;
3270                }
3271                return null;
3272            }
3273            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3274                    ps.readUserState(userId), userId);
3275        }
3276        return null;
3277    }
3278
3279    @Override
3280    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3281        if (!sUserManager.exists(userId)) return null;
3282        flags = updateFlagsForApplication(flags, userId, packageName);
3283        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3284                false /* requireFullPermission */, false /* checkShell */, "get application info");
3285        // writer
3286        synchronized (mPackages) {
3287            PackageParser.Package p = mPackages.get(packageName);
3288            if (DEBUG_PACKAGE_INFO) Log.v(
3289                    TAG, "getApplicationInfo " + packageName
3290                    + ": " + p);
3291            if (p != null) {
3292                PackageSetting ps = mSettings.mPackages.get(packageName);
3293                if (ps == null) return null;
3294                // Note: isEnabledLP() does not apply here - always return info
3295                return PackageParser.generateApplicationInfo(
3296                        p, flags, ps.readUserState(userId), userId);
3297            }
3298            if ("android".equals(packageName)||"system".equals(packageName)) {
3299                return mAndroidApplication;
3300            }
3301            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3302                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3303            }
3304        }
3305        return null;
3306    }
3307
3308    @Override
3309    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3310            final IPackageDataObserver observer) {
3311        mContext.enforceCallingOrSelfPermission(
3312                android.Manifest.permission.CLEAR_APP_CACHE, null);
3313        // Queue up an async operation since clearing cache may take a little while.
3314        mHandler.post(new Runnable() {
3315            public void run() {
3316                mHandler.removeCallbacks(this);
3317                boolean success = true;
3318                synchronized (mInstallLock) {
3319                    try {
3320                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3321                    } catch (InstallerException e) {
3322                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3323                        success = false;
3324                    }
3325                }
3326                if (observer != null) {
3327                    try {
3328                        observer.onRemoveCompleted(null, success);
3329                    } catch (RemoteException e) {
3330                        Slog.w(TAG, "RemoveException when invoking call back");
3331                    }
3332                }
3333            }
3334        });
3335    }
3336
3337    @Override
3338    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3339            final IntentSender pi) {
3340        mContext.enforceCallingOrSelfPermission(
3341                android.Manifest.permission.CLEAR_APP_CACHE, null);
3342        // Queue up an async operation since clearing cache may take a little while.
3343        mHandler.post(new Runnable() {
3344            public void run() {
3345                mHandler.removeCallbacks(this);
3346                boolean success = true;
3347                synchronized (mInstallLock) {
3348                    try {
3349                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3350                    } catch (InstallerException e) {
3351                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3352                        success = false;
3353                    }
3354                }
3355                if(pi != null) {
3356                    try {
3357                        // Callback via pending intent
3358                        int code = success ? 1 : 0;
3359                        pi.sendIntent(null, code, null,
3360                                null, null);
3361                    } catch (SendIntentException e1) {
3362                        Slog.i(TAG, "Failed to send pending intent");
3363                    }
3364                }
3365            }
3366        });
3367    }
3368
3369    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3370        synchronized (mInstallLock) {
3371            try {
3372                mInstaller.freeCache(volumeUuid, freeStorageSize);
3373            } catch (InstallerException e) {
3374                throw new IOException("Failed to free enough space", e);
3375            }
3376        }
3377    }
3378
3379    /**
3380     * Return if the user key is currently unlocked.
3381     */
3382    private boolean isUserKeyUnlocked(int userId) {
3383        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3384            final IMountService mount = IMountService.Stub
3385                    .asInterface(ServiceManager.getService("mount"));
3386            if (mount == null) {
3387                Slog.w(TAG, "Early during boot, assuming locked");
3388                return false;
3389            }
3390            final long token = Binder.clearCallingIdentity();
3391            try {
3392                return mount.isUserKeyUnlocked(userId);
3393            } catch (RemoteException e) {
3394                throw e.rethrowAsRuntimeException();
3395            } finally {
3396                Binder.restoreCallingIdentity(token);
3397            }
3398        } else {
3399            return true;
3400        }
3401    }
3402
3403    /**
3404     * Update given flags based on encryption status of current user.
3405     */
3406    private int updateFlags(int flags, int userId) {
3407        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3408                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3409            // Caller expressed an explicit opinion about what encryption
3410            // aware/unaware components they want to see, so fall through and
3411            // give them what they want
3412        } else {
3413            // Caller expressed no opinion, so match based on user state
3414            if (isUserKeyUnlocked(userId)) {
3415                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3416            } else {
3417                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3418            }
3419        }
3420        return flags;
3421    }
3422
3423    /**
3424     * Update given flags when being used to request {@link PackageInfo}.
3425     */
3426    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3427        boolean triaged = true;
3428        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3429                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3430            // Caller is asking for component details, so they'd better be
3431            // asking for specific encryption matching behavior, or be triaged
3432            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3433                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3434                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3435                triaged = false;
3436            }
3437        }
3438        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3439                | PackageManager.MATCH_SYSTEM_ONLY
3440                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3441            triaged = false;
3442        }
3443        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3444            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3445                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3446        }
3447        return updateFlags(flags, userId);
3448    }
3449
3450    /**
3451     * Update given flags when being used to request {@link ApplicationInfo}.
3452     */
3453    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3454        return updateFlagsForPackage(flags, userId, cookie);
3455    }
3456
3457    /**
3458     * Update given flags when being used to request {@link ComponentInfo}.
3459     */
3460    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3461        if (cookie instanceof Intent) {
3462            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3463                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3464            }
3465        }
3466
3467        boolean triaged = true;
3468        // Caller is asking for component details, so they'd better be
3469        // asking for specific encryption matching behavior, or be triaged
3470        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3471                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3472                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3473            triaged = false;
3474        }
3475        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3476            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3477                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3478        }
3479
3480        return updateFlags(flags, userId);
3481    }
3482
3483    /**
3484     * Update given flags when being used to request {@link ResolveInfo}.
3485     */
3486    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3487        // Safe mode means we shouldn't match any third-party components
3488        if (mSafeMode) {
3489            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3490        }
3491
3492        return updateFlagsForComponent(flags, userId, cookie);
3493    }
3494
3495    @Override
3496    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3497        if (!sUserManager.exists(userId)) return null;
3498        flags = updateFlagsForComponent(flags, userId, component);
3499        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3500                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3501        synchronized (mPackages) {
3502            PackageParser.Activity a = mActivities.mActivities.get(component);
3503
3504            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3505            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3506                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3507                if (ps == null) return null;
3508                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3509                        userId);
3510            }
3511            if (mResolveComponentName.equals(component)) {
3512                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3513                        new PackageUserState(), userId);
3514            }
3515        }
3516        return null;
3517    }
3518
3519    @Override
3520    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3521            String resolvedType) {
3522        synchronized (mPackages) {
3523            if (component.equals(mResolveComponentName)) {
3524                // The resolver supports EVERYTHING!
3525                return true;
3526            }
3527            PackageParser.Activity a = mActivities.mActivities.get(component);
3528            if (a == null) {
3529                return false;
3530            }
3531            for (int i=0; i<a.intents.size(); i++) {
3532                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3533                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3534                    return true;
3535                }
3536            }
3537            return false;
3538        }
3539    }
3540
3541    @Override
3542    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3543        if (!sUserManager.exists(userId)) return null;
3544        flags = updateFlagsForComponent(flags, userId, component);
3545        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3546                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3547        synchronized (mPackages) {
3548            PackageParser.Activity a = mReceivers.mActivities.get(component);
3549            if (DEBUG_PACKAGE_INFO) Log.v(
3550                TAG, "getReceiverInfo " + component + ": " + a);
3551            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3552                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3553                if (ps == null) return null;
3554                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3555                        userId);
3556            }
3557        }
3558        return null;
3559    }
3560
3561    @Override
3562    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3563        if (!sUserManager.exists(userId)) return null;
3564        flags = updateFlagsForComponent(flags, userId, component);
3565        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3566                false /* requireFullPermission */, false /* checkShell */, "get service info");
3567        synchronized (mPackages) {
3568            PackageParser.Service s = mServices.mServices.get(component);
3569            if (DEBUG_PACKAGE_INFO) Log.v(
3570                TAG, "getServiceInfo " + component + ": " + s);
3571            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3572                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3573                if (ps == null) return null;
3574                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3575                        userId);
3576            }
3577        }
3578        return null;
3579    }
3580
3581    @Override
3582    public ProviderInfo getProviderInfo(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 provider info");
3587        synchronized (mPackages) {
3588            PackageParser.Provider p = mProviders.mProviders.get(component);
3589            if (DEBUG_PACKAGE_INFO) Log.v(
3590                TAG, "getProviderInfo " + component + ": " + p);
3591            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3592                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3593                if (ps == null) return null;
3594                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3595                        userId);
3596            }
3597        }
3598        return null;
3599    }
3600
3601    @Override
3602    public String[] getSystemSharedLibraryNames() {
3603        Set<String> libSet;
3604        synchronized (mPackages) {
3605            libSet = mSharedLibraries.keySet();
3606            int size = libSet.size();
3607            if (size > 0) {
3608                String[] libs = new String[size];
3609                libSet.toArray(libs);
3610                return libs;
3611            }
3612        }
3613        return null;
3614    }
3615
3616    @Override
3617    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3618        synchronized (mPackages) {
3619            return mServicesSystemSharedLibraryPackageName;
3620        }
3621    }
3622
3623    @Override
3624    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3625        synchronized (mPackages) {
3626            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3627
3628            final FeatureInfo fi = new FeatureInfo();
3629            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3630                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3631            res.add(fi);
3632
3633            return new ParceledListSlice<>(res);
3634        }
3635    }
3636
3637    @Override
3638    public boolean hasSystemFeature(String name, int version) {
3639        synchronized (mPackages) {
3640            final FeatureInfo feat = mAvailableFeatures.get(name);
3641            if (feat == null) {
3642                return false;
3643            } else {
3644                return feat.version >= version;
3645            }
3646        }
3647    }
3648
3649    @Override
3650    public int checkPermission(String permName, String pkgName, int userId) {
3651        if (!sUserManager.exists(userId)) {
3652            return PackageManager.PERMISSION_DENIED;
3653        }
3654
3655        synchronized (mPackages) {
3656            final PackageParser.Package p = mPackages.get(pkgName);
3657            if (p != null && p.mExtras != null) {
3658                final PackageSetting ps = (PackageSetting) p.mExtras;
3659                final PermissionsState permissionsState = ps.getPermissionsState();
3660                if (permissionsState.hasPermission(permName, userId)) {
3661                    return PackageManager.PERMISSION_GRANTED;
3662                }
3663                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3664                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3665                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3666                    return PackageManager.PERMISSION_GRANTED;
3667                }
3668            }
3669        }
3670
3671        return PackageManager.PERMISSION_DENIED;
3672    }
3673
3674    @Override
3675    public int checkUidPermission(String permName, int uid) {
3676        final int userId = UserHandle.getUserId(uid);
3677
3678        if (!sUserManager.exists(userId)) {
3679            return PackageManager.PERMISSION_DENIED;
3680        }
3681
3682        synchronized (mPackages) {
3683            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3684            if (obj != null) {
3685                final SettingBase ps = (SettingBase) obj;
3686                final PermissionsState permissionsState = ps.getPermissionsState();
3687                if (permissionsState.hasPermission(permName, userId)) {
3688                    return PackageManager.PERMISSION_GRANTED;
3689                }
3690                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3691                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3692                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3693                    return PackageManager.PERMISSION_GRANTED;
3694                }
3695            } else {
3696                ArraySet<String> perms = mSystemPermissions.get(uid);
3697                if (perms != null) {
3698                    if (perms.contains(permName)) {
3699                        return PackageManager.PERMISSION_GRANTED;
3700                    }
3701                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3702                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3703                        return PackageManager.PERMISSION_GRANTED;
3704                    }
3705                }
3706            }
3707        }
3708
3709        return PackageManager.PERMISSION_DENIED;
3710    }
3711
3712    @Override
3713    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3714        if (UserHandle.getCallingUserId() != userId) {
3715            mContext.enforceCallingPermission(
3716                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3717                    "isPermissionRevokedByPolicy for user " + userId);
3718        }
3719
3720        if (checkPermission(permission, packageName, userId)
3721                == PackageManager.PERMISSION_GRANTED) {
3722            return false;
3723        }
3724
3725        final long identity = Binder.clearCallingIdentity();
3726        try {
3727            final int flags = getPermissionFlags(permission, packageName, userId);
3728            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3729        } finally {
3730            Binder.restoreCallingIdentity(identity);
3731        }
3732    }
3733
3734    @Override
3735    public String getPermissionControllerPackageName() {
3736        synchronized (mPackages) {
3737            return mRequiredInstallerPackage;
3738        }
3739    }
3740
3741    /**
3742     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3743     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3744     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3745     * @param message the message to log on security exception
3746     */
3747    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3748            boolean checkShell, String message) {
3749        if (userId < 0) {
3750            throw new IllegalArgumentException("Invalid userId " + userId);
3751        }
3752        if (checkShell) {
3753            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3754        }
3755        if (userId == UserHandle.getUserId(callingUid)) return;
3756        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3757            if (requireFullPermission) {
3758                mContext.enforceCallingOrSelfPermission(
3759                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3760            } else {
3761                try {
3762                    mContext.enforceCallingOrSelfPermission(
3763                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3764                } catch (SecurityException se) {
3765                    mContext.enforceCallingOrSelfPermission(
3766                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3767                }
3768            }
3769        }
3770    }
3771
3772    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3773        if (callingUid == Process.SHELL_UID) {
3774            if (userHandle >= 0
3775                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3776                throw new SecurityException("Shell does not have permission to access user "
3777                        + userHandle);
3778            } else if (userHandle < 0) {
3779                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3780                        + Debug.getCallers(3));
3781            }
3782        }
3783    }
3784
3785    private BasePermission findPermissionTreeLP(String permName) {
3786        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3787            if (permName.startsWith(bp.name) &&
3788                    permName.length() > bp.name.length() &&
3789                    permName.charAt(bp.name.length()) == '.') {
3790                return bp;
3791            }
3792        }
3793        return null;
3794    }
3795
3796    private BasePermission checkPermissionTreeLP(String permName) {
3797        if (permName != null) {
3798            BasePermission bp = findPermissionTreeLP(permName);
3799            if (bp != null) {
3800                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3801                    return bp;
3802                }
3803                throw new SecurityException("Calling uid "
3804                        + Binder.getCallingUid()
3805                        + " is not allowed to add to permission tree "
3806                        + bp.name + " owned by uid " + bp.uid);
3807            }
3808        }
3809        throw new SecurityException("No permission tree found for " + permName);
3810    }
3811
3812    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3813        if (s1 == null) {
3814            return s2 == null;
3815        }
3816        if (s2 == null) {
3817            return false;
3818        }
3819        if (s1.getClass() != s2.getClass()) {
3820            return false;
3821        }
3822        return s1.equals(s2);
3823    }
3824
3825    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3826        if (pi1.icon != pi2.icon) return false;
3827        if (pi1.logo != pi2.logo) return false;
3828        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3829        if (!compareStrings(pi1.name, pi2.name)) return false;
3830        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3831        // We'll take care of setting this one.
3832        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3833        // These are not currently stored in settings.
3834        //if (!compareStrings(pi1.group, pi2.group)) return false;
3835        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3836        //if (pi1.labelRes != pi2.labelRes) return false;
3837        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3838        return true;
3839    }
3840
3841    int permissionInfoFootprint(PermissionInfo info) {
3842        int size = info.name.length();
3843        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3844        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3845        return size;
3846    }
3847
3848    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3849        int size = 0;
3850        for (BasePermission perm : mSettings.mPermissions.values()) {
3851            if (perm.uid == tree.uid) {
3852                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3853            }
3854        }
3855        return size;
3856    }
3857
3858    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3859        // We calculate the max size of permissions defined by this uid and throw
3860        // if that plus the size of 'info' would exceed our stated maximum.
3861        if (tree.uid != Process.SYSTEM_UID) {
3862            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3863            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3864                throw new SecurityException("Permission tree size cap exceeded");
3865            }
3866        }
3867    }
3868
3869    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3870        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3871            throw new SecurityException("Label must be specified in permission");
3872        }
3873        BasePermission tree = checkPermissionTreeLP(info.name);
3874        BasePermission bp = mSettings.mPermissions.get(info.name);
3875        boolean added = bp == null;
3876        boolean changed = true;
3877        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3878        if (added) {
3879            enforcePermissionCapLocked(info, tree);
3880            bp = new BasePermission(info.name, tree.sourcePackage,
3881                    BasePermission.TYPE_DYNAMIC);
3882        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3883            throw new SecurityException(
3884                    "Not allowed to modify non-dynamic permission "
3885                    + info.name);
3886        } else {
3887            if (bp.protectionLevel == fixedLevel
3888                    && bp.perm.owner.equals(tree.perm.owner)
3889                    && bp.uid == tree.uid
3890                    && comparePermissionInfos(bp.perm.info, info)) {
3891                changed = false;
3892            }
3893        }
3894        bp.protectionLevel = fixedLevel;
3895        info = new PermissionInfo(info);
3896        info.protectionLevel = fixedLevel;
3897        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3898        bp.perm.info.packageName = tree.perm.info.packageName;
3899        bp.uid = tree.uid;
3900        if (added) {
3901            mSettings.mPermissions.put(info.name, bp);
3902        }
3903        if (changed) {
3904            if (!async) {
3905                mSettings.writeLPr();
3906            } else {
3907                scheduleWriteSettingsLocked();
3908            }
3909        }
3910        return added;
3911    }
3912
3913    @Override
3914    public boolean addPermission(PermissionInfo info) {
3915        synchronized (mPackages) {
3916            return addPermissionLocked(info, false);
3917        }
3918    }
3919
3920    @Override
3921    public boolean addPermissionAsync(PermissionInfo info) {
3922        synchronized (mPackages) {
3923            return addPermissionLocked(info, true);
3924        }
3925    }
3926
3927    @Override
3928    public void removePermission(String name) {
3929        synchronized (mPackages) {
3930            checkPermissionTreeLP(name);
3931            BasePermission bp = mSettings.mPermissions.get(name);
3932            if (bp != null) {
3933                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3934                    throw new SecurityException(
3935                            "Not allowed to modify non-dynamic permission "
3936                            + name);
3937                }
3938                mSettings.mPermissions.remove(name);
3939                mSettings.writeLPr();
3940            }
3941        }
3942    }
3943
3944    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3945            BasePermission bp) {
3946        int index = pkg.requestedPermissions.indexOf(bp.name);
3947        if (index == -1) {
3948            throw new SecurityException("Package " + pkg.packageName
3949                    + " has not requested permission " + bp.name);
3950        }
3951        if (!bp.isRuntime() && !bp.isDevelopment()) {
3952            throw new SecurityException("Permission " + bp.name
3953                    + " is not a changeable permission type");
3954        }
3955    }
3956
3957    @Override
3958    public void grantRuntimePermission(String packageName, String name, final int userId) {
3959        if (!sUserManager.exists(userId)) {
3960            Log.e(TAG, "No such user:" + userId);
3961            return;
3962        }
3963
3964        mContext.enforceCallingOrSelfPermission(
3965                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3966                "grantRuntimePermission");
3967
3968        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3969                true /* requireFullPermission */, true /* checkShell */,
3970                "grantRuntimePermission");
3971
3972        final int uid;
3973        final SettingBase sb;
3974
3975        synchronized (mPackages) {
3976            final PackageParser.Package pkg = mPackages.get(packageName);
3977            if (pkg == null) {
3978                throw new IllegalArgumentException("Unknown package: " + packageName);
3979            }
3980
3981            final BasePermission bp = mSettings.mPermissions.get(name);
3982            if (bp == null) {
3983                throw new IllegalArgumentException("Unknown permission: " + name);
3984            }
3985
3986            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3987
3988            // If a permission review is required for legacy apps we represent
3989            // their permissions as always granted runtime ones since we need
3990            // to keep the review required permission flag per user while an
3991            // install permission's state is shared across all users.
3992            if (Build.PERMISSIONS_REVIEW_REQUIRED
3993                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3994                    && bp.isRuntime()) {
3995                return;
3996            }
3997
3998            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3999            sb = (SettingBase) pkg.mExtras;
4000            if (sb == null) {
4001                throw new IllegalArgumentException("Unknown package: " + packageName);
4002            }
4003
4004            final PermissionsState permissionsState = sb.getPermissionsState();
4005
4006            final int flags = permissionsState.getPermissionFlags(name, userId);
4007            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4008                throw new SecurityException("Cannot grant system fixed permission "
4009                        + name + " for package " + packageName);
4010            }
4011
4012            if (bp.isDevelopment()) {
4013                // Development permissions must be handled specially, since they are not
4014                // normal runtime permissions.  For now they apply to all users.
4015                if (permissionsState.grantInstallPermission(bp) !=
4016                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4017                    scheduleWriteSettingsLocked();
4018                }
4019                return;
4020            }
4021
4022            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4023                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4024                return;
4025            }
4026
4027            final int result = permissionsState.grantRuntimePermission(bp, userId);
4028            switch (result) {
4029                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4030                    return;
4031                }
4032
4033                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4034                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4035                    mHandler.post(new Runnable() {
4036                        @Override
4037                        public void run() {
4038                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4039                        }
4040                    });
4041                }
4042                break;
4043            }
4044
4045            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4046
4047            // Not critical if that is lost - app has to request again.
4048            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4049        }
4050
4051        // Only need to do this if user is initialized. Otherwise it's a new user
4052        // and there are no processes running as the user yet and there's no need
4053        // to make an expensive call to remount processes for the changed permissions.
4054        if (READ_EXTERNAL_STORAGE.equals(name)
4055                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4056            final long token = Binder.clearCallingIdentity();
4057            try {
4058                if (sUserManager.isInitialized(userId)) {
4059                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4060                            MountServiceInternal.class);
4061                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4062                }
4063            } finally {
4064                Binder.restoreCallingIdentity(token);
4065            }
4066        }
4067    }
4068
4069    @Override
4070    public void revokeRuntimePermission(String packageName, String name, int userId) {
4071        if (!sUserManager.exists(userId)) {
4072            Log.e(TAG, "No such user:" + userId);
4073            return;
4074        }
4075
4076        mContext.enforceCallingOrSelfPermission(
4077                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4078                "revokeRuntimePermission");
4079
4080        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4081                true /* requireFullPermission */, true /* checkShell */,
4082                "revokeRuntimePermission");
4083
4084        final int appId;
4085
4086        synchronized (mPackages) {
4087            final PackageParser.Package pkg = mPackages.get(packageName);
4088            if (pkg == null) {
4089                throw new IllegalArgumentException("Unknown package: " + packageName);
4090            }
4091
4092            final BasePermission bp = mSettings.mPermissions.get(name);
4093            if (bp == null) {
4094                throw new IllegalArgumentException("Unknown permission: " + name);
4095            }
4096
4097            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4098
4099            // If a permission review is required for legacy apps we represent
4100            // their permissions as always granted runtime ones since we need
4101            // to keep the review required permission flag per user while an
4102            // install permission's state is shared across all users.
4103            if (Build.PERMISSIONS_REVIEW_REQUIRED
4104                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4105                    && bp.isRuntime()) {
4106                return;
4107            }
4108
4109            SettingBase sb = (SettingBase) pkg.mExtras;
4110            if (sb == null) {
4111                throw new IllegalArgumentException("Unknown package: " + packageName);
4112            }
4113
4114            final PermissionsState permissionsState = sb.getPermissionsState();
4115
4116            final int flags = permissionsState.getPermissionFlags(name, userId);
4117            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4118                throw new SecurityException("Cannot revoke system fixed permission "
4119                        + name + " for package " + packageName);
4120            }
4121
4122            if (bp.isDevelopment()) {
4123                // Development permissions must be handled specially, since they are not
4124                // normal runtime permissions.  For now they apply to all users.
4125                if (permissionsState.revokeInstallPermission(bp) !=
4126                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4127                    scheduleWriteSettingsLocked();
4128                }
4129                return;
4130            }
4131
4132            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4133                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4134                return;
4135            }
4136
4137            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4138
4139            // Critical, after this call app should never have the permission.
4140            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4141
4142            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4143        }
4144
4145        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4146    }
4147
4148    @Override
4149    public void resetRuntimePermissions() {
4150        mContext.enforceCallingOrSelfPermission(
4151                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4152                "revokeRuntimePermission");
4153
4154        int callingUid = Binder.getCallingUid();
4155        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4156            mContext.enforceCallingOrSelfPermission(
4157                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4158                    "resetRuntimePermissions");
4159        }
4160
4161        synchronized (mPackages) {
4162            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4163            for (int userId : UserManagerService.getInstance().getUserIds()) {
4164                final int packageCount = mPackages.size();
4165                for (int i = 0; i < packageCount; i++) {
4166                    PackageParser.Package pkg = mPackages.valueAt(i);
4167                    if (!(pkg.mExtras instanceof PackageSetting)) {
4168                        continue;
4169                    }
4170                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4171                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4172                }
4173            }
4174        }
4175    }
4176
4177    @Override
4178    public int getPermissionFlags(String name, String packageName, int userId) {
4179        if (!sUserManager.exists(userId)) {
4180            return 0;
4181        }
4182
4183        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4184
4185        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4186                true /* requireFullPermission */, false /* checkShell */,
4187                "getPermissionFlags");
4188
4189        synchronized (mPackages) {
4190            final PackageParser.Package pkg = mPackages.get(packageName);
4191            if (pkg == null) {
4192                throw new IllegalArgumentException("Unknown package: " + packageName);
4193            }
4194
4195            final BasePermission bp = mSettings.mPermissions.get(name);
4196            if (bp == null) {
4197                throw new IllegalArgumentException("Unknown permission: " + name);
4198            }
4199
4200            SettingBase sb = (SettingBase) pkg.mExtras;
4201            if (sb == null) {
4202                throw new IllegalArgumentException("Unknown package: " + packageName);
4203            }
4204
4205            PermissionsState permissionsState = sb.getPermissionsState();
4206            return permissionsState.getPermissionFlags(name, userId);
4207        }
4208    }
4209
4210    @Override
4211    public void updatePermissionFlags(String name, String packageName, int flagMask,
4212            int flagValues, int userId) {
4213        if (!sUserManager.exists(userId)) {
4214            return;
4215        }
4216
4217        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4218
4219        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4220                true /* requireFullPermission */, true /* checkShell */,
4221                "updatePermissionFlags");
4222
4223        // Only the system can change these flags and nothing else.
4224        if (getCallingUid() != Process.SYSTEM_UID) {
4225            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4226            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4227            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4228            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4229            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4230        }
4231
4232        synchronized (mPackages) {
4233            final PackageParser.Package pkg = mPackages.get(packageName);
4234            if (pkg == null) {
4235                throw new IllegalArgumentException("Unknown package: " + packageName);
4236            }
4237
4238            final BasePermission bp = mSettings.mPermissions.get(name);
4239            if (bp == null) {
4240                throw new IllegalArgumentException("Unknown permission: " + name);
4241            }
4242
4243            SettingBase sb = (SettingBase) pkg.mExtras;
4244            if (sb == null) {
4245                throw new IllegalArgumentException("Unknown package: " + packageName);
4246            }
4247
4248            PermissionsState permissionsState = sb.getPermissionsState();
4249
4250            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4251
4252            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4253                // Install and runtime permissions are stored in different places,
4254                // so figure out what permission changed and persist the change.
4255                if (permissionsState.getInstallPermissionState(name) != null) {
4256                    scheduleWriteSettingsLocked();
4257                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4258                        || hadState) {
4259                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4260                }
4261            }
4262        }
4263    }
4264
4265    /**
4266     * Update the permission flags for all packages and runtime permissions of a user in order
4267     * to allow device or profile owner to remove POLICY_FIXED.
4268     */
4269    @Override
4270    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4271        if (!sUserManager.exists(userId)) {
4272            return;
4273        }
4274
4275        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4276
4277        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4278                true /* requireFullPermission */, true /* checkShell */,
4279                "updatePermissionFlagsForAllApps");
4280
4281        // Only the system can change system fixed flags.
4282        if (getCallingUid() != Process.SYSTEM_UID) {
4283            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4284            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4285        }
4286
4287        synchronized (mPackages) {
4288            boolean changed = false;
4289            final int packageCount = mPackages.size();
4290            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4291                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4292                SettingBase sb = (SettingBase) pkg.mExtras;
4293                if (sb == null) {
4294                    continue;
4295                }
4296                PermissionsState permissionsState = sb.getPermissionsState();
4297                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4298                        userId, flagMask, flagValues);
4299            }
4300            if (changed) {
4301                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4302            }
4303        }
4304    }
4305
4306    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4307        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4308                != PackageManager.PERMISSION_GRANTED
4309            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4310                != PackageManager.PERMISSION_GRANTED) {
4311            throw new SecurityException(message + " requires "
4312                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4313                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4314        }
4315    }
4316
4317    @Override
4318    public boolean shouldShowRequestPermissionRationale(String permissionName,
4319            String packageName, int userId) {
4320        if (UserHandle.getCallingUserId() != userId) {
4321            mContext.enforceCallingPermission(
4322                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4323                    "canShowRequestPermissionRationale for user " + userId);
4324        }
4325
4326        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4327        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4328            return false;
4329        }
4330
4331        if (checkPermission(permissionName, packageName, userId)
4332                == PackageManager.PERMISSION_GRANTED) {
4333            return false;
4334        }
4335
4336        final int flags;
4337
4338        final long identity = Binder.clearCallingIdentity();
4339        try {
4340            flags = getPermissionFlags(permissionName,
4341                    packageName, userId);
4342        } finally {
4343            Binder.restoreCallingIdentity(identity);
4344        }
4345
4346        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4347                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4348                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4349
4350        if ((flags & fixedFlags) != 0) {
4351            return false;
4352        }
4353
4354        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4355    }
4356
4357    @Override
4358    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4359        mContext.enforceCallingOrSelfPermission(
4360                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4361                "addOnPermissionsChangeListener");
4362
4363        synchronized (mPackages) {
4364            mOnPermissionChangeListeners.addListenerLocked(listener);
4365        }
4366    }
4367
4368    @Override
4369    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4370        synchronized (mPackages) {
4371            mOnPermissionChangeListeners.removeListenerLocked(listener);
4372        }
4373    }
4374
4375    @Override
4376    public boolean isProtectedBroadcast(String actionName) {
4377        synchronized (mPackages) {
4378            if (mProtectedBroadcasts.contains(actionName)) {
4379                return true;
4380            } else if (actionName != null) {
4381                // TODO: remove these terrible hacks
4382                if (actionName.startsWith("android.net.netmon.lingerExpired")
4383                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4384                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4385                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4386                    return true;
4387                }
4388            }
4389        }
4390        return false;
4391    }
4392
4393    @Override
4394    public int checkSignatures(String pkg1, String pkg2) {
4395        synchronized (mPackages) {
4396            final PackageParser.Package p1 = mPackages.get(pkg1);
4397            final PackageParser.Package p2 = mPackages.get(pkg2);
4398            if (p1 == null || p1.mExtras == null
4399                    || p2 == null || p2.mExtras == null) {
4400                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4401            }
4402            return compareSignatures(p1.mSignatures, p2.mSignatures);
4403        }
4404    }
4405
4406    @Override
4407    public int checkUidSignatures(int uid1, int uid2) {
4408        // Map to base uids.
4409        uid1 = UserHandle.getAppId(uid1);
4410        uid2 = UserHandle.getAppId(uid2);
4411        // reader
4412        synchronized (mPackages) {
4413            Signature[] s1;
4414            Signature[] s2;
4415            Object obj = mSettings.getUserIdLPr(uid1);
4416            if (obj != null) {
4417                if (obj instanceof SharedUserSetting) {
4418                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4419                } else if (obj instanceof PackageSetting) {
4420                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4421                } else {
4422                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4423                }
4424            } else {
4425                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4426            }
4427            obj = mSettings.getUserIdLPr(uid2);
4428            if (obj != null) {
4429                if (obj instanceof SharedUserSetting) {
4430                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4431                } else if (obj instanceof PackageSetting) {
4432                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4433                } else {
4434                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4435                }
4436            } else {
4437                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4438            }
4439            return compareSignatures(s1, s2);
4440        }
4441    }
4442
4443    /**
4444     * This method should typically only be used when granting or revoking
4445     * permissions, since the app may immediately restart after this call.
4446     * <p>
4447     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4448     * guard your work against the app being relaunched.
4449     */
4450    private void killUid(int appId, int userId, String reason) {
4451        final long identity = Binder.clearCallingIdentity();
4452        try {
4453            IActivityManager am = ActivityManagerNative.getDefault();
4454            if (am != null) {
4455                try {
4456                    am.killUid(appId, userId, reason);
4457                } catch (RemoteException e) {
4458                    /* ignore - same process */
4459                }
4460            }
4461        } finally {
4462            Binder.restoreCallingIdentity(identity);
4463        }
4464    }
4465
4466    /**
4467     * Compares two sets of signatures. Returns:
4468     * <br />
4469     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4470     * <br />
4471     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4472     * <br />
4473     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4474     * <br />
4475     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4476     * <br />
4477     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4478     */
4479    static int compareSignatures(Signature[] s1, Signature[] s2) {
4480        if (s1 == null) {
4481            return s2 == null
4482                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4483                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4484        }
4485
4486        if (s2 == null) {
4487            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4488        }
4489
4490        if (s1.length != s2.length) {
4491            return PackageManager.SIGNATURE_NO_MATCH;
4492        }
4493
4494        // Since both signature sets are of size 1, we can compare without HashSets.
4495        if (s1.length == 1) {
4496            return s1[0].equals(s2[0]) ?
4497                    PackageManager.SIGNATURE_MATCH :
4498                    PackageManager.SIGNATURE_NO_MATCH;
4499        }
4500
4501        ArraySet<Signature> set1 = new ArraySet<Signature>();
4502        for (Signature sig : s1) {
4503            set1.add(sig);
4504        }
4505        ArraySet<Signature> set2 = new ArraySet<Signature>();
4506        for (Signature sig : s2) {
4507            set2.add(sig);
4508        }
4509        // Make sure s2 contains all signatures in s1.
4510        if (set1.equals(set2)) {
4511            return PackageManager.SIGNATURE_MATCH;
4512        }
4513        return PackageManager.SIGNATURE_NO_MATCH;
4514    }
4515
4516    /**
4517     * If the database version for this type of package (internal storage or
4518     * external storage) is less than the version where package signatures
4519     * were updated, return true.
4520     */
4521    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4522        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4523        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4524    }
4525
4526    /**
4527     * Used for backward compatibility to make sure any packages with
4528     * certificate chains get upgraded to the new style. {@code existingSigs}
4529     * will be in the old format (since they were stored on disk from before the
4530     * system upgrade) and {@code scannedSigs} will be in the newer format.
4531     */
4532    private int compareSignaturesCompat(PackageSignatures existingSigs,
4533            PackageParser.Package scannedPkg) {
4534        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4535            return PackageManager.SIGNATURE_NO_MATCH;
4536        }
4537
4538        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4539        for (Signature sig : existingSigs.mSignatures) {
4540            existingSet.add(sig);
4541        }
4542        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4543        for (Signature sig : scannedPkg.mSignatures) {
4544            try {
4545                Signature[] chainSignatures = sig.getChainSignatures();
4546                for (Signature chainSig : chainSignatures) {
4547                    scannedCompatSet.add(chainSig);
4548                }
4549            } catch (CertificateEncodingException e) {
4550                scannedCompatSet.add(sig);
4551            }
4552        }
4553        /*
4554         * Make sure the expanded scanned set contains all signatures in the
4555         * existing one.
4556         */
4557        if (scannedCompatSet.equals(existingSet)) {
4558            // Migrate the old signatures to the new scheme.
4559            existingSigs.assignSignatures(scannedPkg.mSignatures);
4560            // The new KeySets will be re-added later in the scanning process.
4561            synchronized (mPackages) {
4562                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4563            }
4564            return PackageManager.SIGNATURE_MATCH;
4565        }
4566        return PackageManager.SIGNATURE_NO_MATCH;
4567    }
4568
4569    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4570        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4571        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4572    }
4573
4574    private int compareSignaturesRecover(PackageSignatures existingSigs,
4575            PackageParser.Package scannedPkg) {
4576        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4577            return PackageManager.SIGNATURE_NO_MATCH;
4578        }
4579
4580        String msg = null;
4581        try {
4582            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4583                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4584                        + scannedPkg.packageName);
4585                return PackageManager.SIGNATURE_MATCH;
4586            }
4587        } catch (CertificateException e) {
4588            msg = e.getMessage();
4589        }
4590
4591        logCriticalInfo(Log.INFO,
4592                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4593        return PackageManager.SIGNATURE_NO_MATCH;
4594    }
4595
4596    @Override
4597    public List<String> getAllPackages() {
4598        synchronized (mPackages) {
4599            return new ArrayList<String>(mPackages.keySet());
4600        }
4601    }
4602
4603    @Override
4604    public String[] getPackagesForUid(int uid) {
4605        uid = UserHandle.getAppId(uid);
4606        // reader
4607        synchronized (mPackages) {
4608            Object obj = mSettings.getUserIdLPr(uid);
4609            if (obj instanceof SharedUserSetting) {
4610                final SharedUserSetting sus = (SharedUserSetting) obj;
4611                final int N = sus.packages.size();
4612                final String[] res = new String[N];
4613                final Iterator<PackageSetting> it = sus.packages.iterator();
4614                int i = 0;
4615                while (it.hasNext()) {
4616                    res[i++] = it.next().name;
4617                }
4618                return res;
4619            } else if (obj instanceof PackageSetting) {
4620                final PackageSetting ps = (PackageSetting) obj;
4621                return new String[] { ps.name };
4622            }
4623        }
4624        return null;
4625    }
4626
4627    @Override
4628    public String getNameForUid(int uid) {
4629        // reader
4630        synchronized (mPackages) {
4631            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4632            if (obj instanceof SharedUserSetting) {
4633                final SharedUserSetting sus = (SharedUserSetting) obj;
4634                return sus.name + ":" + sus.userId;
4635            } else if (obj instanceof PackageSetting) {
4636                final PackageSetting ps = (PackageSetting) obj;
4637                return ps.name;
4638            }
4639        }
4640        return null;
4641    }
4642
4643    @Override
4644    public int getUidForSharedUser(String sharedUserName) {
4645        if(sharedUserName == null) {
4646            return -1;
4647        }
4648        // reader
4649        synchronized (mPackages) {
4650            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4651            if (suid == null) {
4652                return -1;
4653            }
4654            return suid.userId;
4655        }
4656    }
4657
4658    @Override
4659    public int getFlagsForUid(int uid) {
4660        synchronized (mPackages) {
4661            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4662            if (obj instanceof SharedUserSetting) {
4663                final SharedUserSetting sus = (SharedUserSetting) obj;
4664                return sus.pkgFlags;
4665            } else if (obj instanceof PackageSetting) {
4666                final PackageSetting ps = (PackageSetting) obj;
4667                return ps.pkgFlags;
4668            }
4669        }
4670        return 0;
4671    }
4672
4673    @Override
4674    public int getPrivateFlagsForUid(int uid) {
4675        synchronized (mPackages) {
4676            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4677            if (obj instanceof SharedUserSetting) {
4678                final SharedUserSetting sus = (SharedUserSetting) obj;
4679                return sus.pkgPrivateFlags;
4680            } else if (obj instanceof PackageSetting) {
4681                final PackageSetting ps = (PackageSetting) obj;
4682                return ps.pkgPrivateFlags;
4683            }
4684        }
4685        return 0;
4686    }
4687
4688    @Override
4689    public boolean isUidPrivileged(int uid) {
4690        uid = UserHandle.getAppId(uid);
4691        // reader
4692        synchronized (mPackages) {
4693            Object obj = mSettings.getUserIdLPr(uid);
4694            if (obj instanceof SharedUserSetting) {
4695                final SharedUserSetting sus = (SharedUserSetting) obj;
4696                final Iterator<PackageSetting> it = sus.packages.iterator();
4697                while (it.hasNext()) {
4698                    if (it.next().isPrivileged()) {
4699                        return true;
4700                    }
4701                }
4702            } else if (obj instanceof PackageSetting) {
4703                final PackageSetting ps = (PackageSetting) obj;
4704                return ps.isPrivileged();
4705            }
4706        }
4707        return false;
4708    }
4709
4710    @Override
4711    public String[] getAppOpPermissionPackages(String permissionName) {
4712        synchronized (mPackages) {
4713            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4714            if (pkgs == null) {
4715                return null;
4716            }
4717            return pkgs.toArray(new String[pkgs.size()]);
4718        }
4719    }
4720
4721    @Override
4722    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4723            int flags, int userId) {
4724        try {
4725            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4726
4727            if (!sUserManager.exists(userId)) return null;
4728            flags = updateFlagsForResolve(flags, userId, intent);
4729            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4730                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4731
4732            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4733            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4734                    flags, userId);
4735            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4736
4737            final ResolveInfo bestChoice =
4738                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4739
4740            if (isEphemeralAllowed(intent, query, userId)) {
4741                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4742                final EphemeralResolveInfo ai =
4743                        getEphemeralResolveInfo(intent, resolvedType, userId);
4744                if (ai != null) {
4745                    if (DEBUG_EPHEMERAL) {
4746                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4747                    }
4748                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4749                    bestChoice.ephemeralResolveInfo = ai;
4750                }
4751                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4752            }
4753            return bestChoice;
4754        } finally {
4755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4756        }
4757    }
4758
4759    @Override
4760    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4761            IntentFilter filter, int match, ComponentName activity) {
4762        final int userId = UserHandle.getCallingUserId();
4763        if (DEBUG_PREFERRED) {
4764            Log.v(TAG, "setLastChosenActivity intent=" + intent
4765                + " resolvedType=" + resolvedType
4766                + " flags=" + flags
4767                + " filter=" + filter
4768                + " match=" + match
4769                + " activity=" + activity);
4770            filter.dump(new PrintStreamPrinter(System.out), "    ");
4771        }
4772        intent.setComponent(null);
4773        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4774                userId);
4775        // Find any earlier preferred or last chosen entries and nuke them
4776        findPreferredActivity(intent, resolvedType,
4777                flags, query, 0, false, true, false, userId);
4778        // Add the new activity as the last chosen for this filter
4779        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4780                "Setting last chosen");
4781    }
4782
4783    @Override
4784    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4785        final int userId = UserHandle.getCallingUserId();
4786        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4787        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4788                userId);
4789        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4790                false, false, false, userId);
4791    }
4792
4793
4794    private boolean isEphemeralAllowed(
4795            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4796        // Short circuit and return early if possible.
4797        if (DISABLE_EPHEMERAL_APPS) {
4798            return false;
4799        }
4800        final int callingUser = UserHandle.getCallingUserId();
4801        if (callingUser != UserHandle.USER_SYSTEM) {
4802            return false;
4803        }
4804        if (mEphemeralResolverConnection == null) {
4805            return false;
4806        }
4807        if (intent.getComponent() != null) {
4808            return false;
4809        }
4810        if (intent.getPackage() != null) {
4811            return false;
4812        }
4813        final boolean isWebUri = hasWebURI(intent);
4814        if (!isWebUri) {
4815            return false;
4816        }
4817        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4818        synchronized (mPackages) {
4819            final int count = resolvedActivites.size();
4820            for (int n = 0; n < count; n++) {
4821                ResolveInfo info = resolvedActivites.get(n);
4822                String packageName = info.activityInfo.packageName;
4823                PackageSetting ps = mSettings.mPackages.get(packageName);
4824                if (ps != null) {
4825                    // Try to get the status from User settings first
4826                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4827                    int status = (int) (packedStatus >> 32);
4828                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4829                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4830                        if (DEBUG_EPHEMERAL) {
4831                            Slog.v(TAG, "DENY ephemeral apps;"
4832                                + " pkg: " + packageName + ", status: " + status);
4833                        }
4834                        return false;
4835                    }
4836                }
4837            }
4838        }
4839        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4840        return true;
4841    }
4842
4843    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4844            int userId) {
4845        MessageDigest digest = null;
4846        try {
4847            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4848        } catch (NoSuchAlgorithmException e) {
4849            // If we can't create a digest, ignore ephemeral apps.
4850            return null;
4851        }
4852
4853        final byte[] hostBytes = intent.getData().getHost().getBytes();
4854        final byte[] digestBytes = digest.digest(hostBytes);
4855        int shaPrefix =
4856                digestBytes[0] << 24
4857                | digestBytes[1] << 16
4858                | digestBytes[2] << 8
4859                | digestBytes[3] << 0;
4860        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4861                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4862        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4863            // No hash prefix match; there are no ephemeral apps for this domain.
4864            return null;
4865        }
4866        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4867            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4868            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4869                continue;
4870            }
4871            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4872            // No filters; this should never happen.
4873            if (filters.isEmpty()) {
4874                continue;
4875            }
4876            // We have a domain match; resolve the filters to see if anything matches.
4877            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4878            for (int j = filters.size() - 1; j >= 0; --j) {
4879                final EphemeralResolveIntentInfo intentInfo =
4880                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4881                ephemeralResolver.addFilter(intentInfo);
4882            }
4883            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4884                    intent, resolvedType, false /*defaultOnly*/, userId);
4885            if (!matchedResolveInfoList.isEmpty()) {
4886                return matchedResolveInfoList.get(0);
4887            }
4888        }
4889        // Hash or filter mis-match; no ephemeral apps for this domain.
4890        return null;
4891    }
4892
4893    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4894            int flags, List<ResolveInfo> query, int userId) {
4895        if (query != null) {
4896            final int N = query.size();
4897            if (N == 1) {
4898                return query.get(0);
4899            } else if (N > 1) {
4900                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4901                // If there is more than one activity with the same priority,
4902                // then let the user decide between them.
4903                ResolveInfo r0 = query.get(0);
4904                ResolveInfo r1 = query.get(1);
4905                if (DEBUG_INTENT_MATCHING || debug) {
4906                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4907                            + r1.activityInfo.name + "=" + r1.priority);
4908                }
4909                // If the first activity has a higher priority, or a different
4910                // default, then it is always desirable to pick it.
4911                if (r0.priority != r1.priority
4912                        || r0.preferredOrder != r1.preferredOrder
4913                        || r0.isDefault != r1.isDefault) {
4914                    return query.get(0);
4915                }
4916                // If we have saved a preference for a preferred activity for
4917                // this Intent, use that.
4918                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4919                        flags, query, r0.priority, true, false, debug, userId);
4920                if (ri != null) {
4921                    return ri;
4922                }
4923                ri = new ResolveInfo(mResolveInfo);
4924                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4925                ri.activityInfo.applicationInfo = new ApplicationInfo(
4926                        ri.activityInfo.applicationInfo);
4927                if (userId != 0) {
4928                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4929                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4930                }
4931                // Make sure that the resolver is displayable in car mode
4932                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4933                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4934                return ri;
4935            }
4936        }
4937        return null;
4938    }
4939
4940    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4941            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4942        final int N = query.size();
4943        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4944                .get(userId);
4945        // Get the list of persistent preferred activities that handle the intent
4946        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4947        List<PersistentPreferredActivity> pprefs = ppir != null
4948                ? ppir.queryIntent(intent, resolvedType,
4949                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4950                : null;
4951        if (pprefs != null && pprefs.size() > 0) {
4952            final int M = pprefs.size();
4953            for (int i=0; i<M; i++) {
4954                final PersistentPreferredActivity ppa = pprefs.get(i);
4955                if (DEBUG_PREFERRED || debug) {
4956                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4957                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4958                            + "\n  component=" + ppa.mComponent);
4959                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4960                }
4961                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4962                        flags | MATCH_DISABLED_COMPONENTS, userId);
4963                if (DEBUG_PREFERRED || debug) {
4964                    Slog.v(TAG, "Found persistent preferred activity:");
4965                    if (ai != null) {
4966                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4967                    } else {
4968                        Slog.v(TAG, "  null");
4969                    }
4970                }
4971                if (ai == null) {
4972                    // This previously registered persistent preferred activity
4973                    // component is no longer known. Ignore it and do NOT remove it.
4974                    continue;
4975                }
4976                for (int j=0; j<N; j++) {
4977                    final ResolveInfo ri = query.get(j);
4978                    if (!ri.activityInfo.applicationInfo.packageName
4979                            .equals(ai.applicationInfo.packageName)) {
4980                        continue;
4981                    }
4982                    if (!ri.activityInfo.name.equals(ai.name)) {
4983                        continue;
4984                    }
4985                    //  Found a persistent preference that can handle the intent.
4986                    if (DEBUG_PREFERRED || debug) {
4987                        Slog.v(TAG, "Returning persistent preferred activity: " +
4988                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4989                    }
4990                    return ri;
4991                }
4992            }
4993        }
4994        return null;
4995    }
4996
4997    // TODO: handle preferred activities missing while user has amnesia
4998    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4999            List<ResolveInfo> query, int priority, boolean always,
5000            boolean removeMatches, boolean debug, int userId) {
5001        if (!sUserManager.exists(userId)) return null;
5002        flags = updateFlagsForResolve(flags, userId, intent);
5003        // writer
5004        synchronized (mPackages) {
5005            if (intent.getSelector() != null) {
5006                intent = intent.getSelector();
5007            }
5008            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5009
5010            // Try to find a matching persistent preferred activity.
5011            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5012                    debug, userId);
5013
5014            // If a persistent preferred activity matched, use it.
5015            if (pri != null) {
5016                return pri;
5017            }
5018
5019            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5020            // Get the list of preferred activities that handle the intent
5021            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5022            List<PreferredActivity> prefs = pir != null
5023                    ? pir.queryIntent(intent, resolvedType,
5024                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5025                    : null;
5026            if (prefs != null && prefs.size() > 0) {
5027                boolean changed = false;
5028                try {
5029                    // First figure out how good the original match set is.
5030                    // We will only allow preferred activities that came
5031                    // from the same match quality.
5032                    int match = 0;
5033
5034                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5035
5036                    final int N = query.size();
5037                    for (int j=0; j<N; j++) {
5038                        final ResolveInfo ri = query.get(j);
5039                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5040                                + ": 0x" + Integer.toHexString(match));
5041                        if (ri.match > match) {
5042                            match = ri.match;
5043                        }
5044                    }
5045
5046                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5047                            + Integer.toHexString(match));
5048
5049                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5050                    final int M = prefs.size();
5051                    for (int i=0; i<M; i++) {
5052                        final PreferredActivity pa = prefs.get(i);
5053                        if (DEBUG_PREFERRED || debug) {
5054                            Slog.v(TAG, "Checking PreferredActivity ds="
5055                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5056                                    + "\n  component=" + pa.mPref.mComponent);
5057                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5058                        }
5059                        if (pa.mPref.mMatch != match) {
5060                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5061                                    + Integer.toHexString(pa.mPref.mMatch));
5062                            continue;
5063                        }
5064                        // If it's not an "always" type preferred activity and that's what we're
5065                        // looking for, skip it.
5066                        if (always && !pa.mPref.mAlways) {
5067                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5068                            continue;
5069                        }
5070                        final ActivityInfo ai = getActivityInfo(
5071                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5072                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5073                                userId);
5074                        if (DEBUG_PREFERRED || debug) {
5075                            Slog.v(TAG, "Found preferred activity:");
5076                            if (ai != null) {
5077                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5078                            } else {
5079                                Slog.v(TAG, "  null");
5080                            }
5081                        }
5082                        if (ai == null) {
5083                            // This previously registered preferred activity
5084                            // component is no longer known.  Most likely an update
5085                            // to the app was installed and in the new version this
5086                            // component no longer exists.  Clean it up by removing
5087                            // it from the preferred activities list, and skip it.
5088                            Slog.w(TAG, "Removing dangling preferred activity: "
5089                                    + pa.mPref.mComponent);
5090                            pir.removeFilter(pa);
5091                            changed = true;
5092                            continue;
5093                        }
5094                        for (int j=0; j<N; j++) {
5095                            final ResolveInfo ri = query.get(j);
5096                            if (!ri.activityInfo.applicationInfo.packageName
5097                                    .equals(ai.applicationInfo.packageName)) {
5098                                continue;
5099                            }
5100                            if (!ri.activityInfo.name.equals(ai.name)) {
5101                                continue;
5102                            }
5103
5104                            if (removeMatches) {
5105                                pir.removeFilter(pa);
5106                                changed = true;
5107                                if (DEBUG_PREFERRED) {
5108                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5109                                }
5110                                break;
5111                            }
5112
5113                            // Okay we found a previously set preferred or last chosen app.
5114                            // If the result set is different from when this
5115                            // was created, we need to clear it and re-ask the
5116                            // user their preference, if we're looking for an "always" type entry.
5117                            if (always && !pa.mPref.sameSet(query)) {
5118                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5119                                        + intent + " type " + resolvedType);
5120                                if (DEBUG_PREFERRED) {
5121                                    Slog.v(TAG, "Removing preferred activity since set changed "
5122                                            + pa.mPref.mComponent);
5123                                }
5124                                pir.removeFilter(pa);
5125                                // Re-add the filter as a "last chosen" entry (!always)
5126                                PreferredActivity lastChosen = new PreferredActivity(
5127                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5128                                pir.addFilter(lastChosen);
5129                                changed = true;
5130                                return null;
5131                            }
5132
5133                            // Yay! Either the set matched or we're looking for the last chosen
5134                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5135                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5136                            return ri;
5137                        }
5138                    }
5139                } finally {
5140                    if (changed) {
5141                        if (DEBUG_PREFERRED) {
5142                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5143                        }
5144                        scheduleWritePackageRestrictionsLocked(userId);
5145                    }
5146                }
5147            }
5148        }
5149        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5150        return null;
5151    }
5152
5153    /*
5154     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5155     */
5156    @Override
5157    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5158            int targetUserId) {
5159        mContext.enforceCallingOrSelfPermission(
5160                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5161        List<CrossProfileIntentFilter> matches =
5162                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5163        if (matches != null) {
5164            int size = matches.size();
5165            for (int i = 0; i < size; i++) {
5166                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5167            }
5168        }
5169        if (hasWebURI(intent)) {
5170            // cross-profile app linking works only towards the parent.
5171            final UserInfo parent = getProfileParent(sourceUserId);
5172            synchronized(mPackages) {
5173                int flags = updateFlagsForResolve(0, parent.id, intent);
5174                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5175                        intent, resolvedType, flags, sourceUserId, parent.id);
5176                return xpDomainInfo != null;
5177            }
5178        }
5179        return false;
5180    }
5181
5182    private UserInfo getProfileParent(int userId) {
5183        final long identity = Binder.clearCallingIdentity();
5184        try {
5185            return sUserManager.getProfileParent(userId);
5186        } finally {
5187            Binder.restoreCallingIdentity(identity);
5188        }
5189    }
5190
5191    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5192            String resolvedType, int userId) {
5193        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5194        if (resolver != null) {
5195            return resolver.queryIntent(intent, resolvedType, false, userId);
5196        }
5197        return null;
5198    }
5199
5200    @Override
5201    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5202            String resolvedType, int flags, int userId) {
5203        try {
5204            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5205
5206            return new ParceledListSlice<>(
5207                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5208        } finally {
5209            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5210        }
5211    }
5212
5213    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5214            String resolvedType, int flags, int userId) {
5215        if (!sUserManager.exists(userId)) return Collections.emptyList();
5216        flags = updateFlagsForResolve(flags, userId, intent);
5217        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5218                false /* requireFullPermission */, false /* checkShell */,
5219                "query intent activities");
5220        ComponentName comp = intent.getComponent();
5221        if (comp == null) {
5222            if (intent.getSelector() != null) {
5223                intent = intent.getSelector();
5224                comp = intent.getComponent();
5225            }
5226        }
5227
5228        if (comp != null) {
5229            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5230            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5231            if (ai != null) {
5232                final ResolveInfo ri = new ResolveInfo();
5233                ri.activityInfo = ai;
5234                list.add(ri);
5235            }
5236            return list;
5237        }
5238
5239        // reader
5240        synchronized (mPackages) {
5241            final String pkgName = intent.getPackage();
5242            if (pkgName == null) {
5243                List<CrossProfileIntentFilter> matchingFilters =
5244                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5245                // Check for results that need to skip the current profile.
5246                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5247                        resolvedType, flags, userId);
5248                if (xpResolveInfo != null) {
5249                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5250                    result.add(xpResolveInfo);
5251                    return filterIfNotSystemUser(result, userId);
5252                }
5253
5254                // Check for results in the current profile.
5255                List<ResolveInfo> result = mActivities.queryIntent(
5256                        intent, resolvedType, flags, userId);
5257                result = filterIfNotSystemUser(result, userId);
5258
5259                // Check for cross profile results.
5260                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5261                xpResolveInfo = queryCrossProfileIntents(
5262                        matchingFilters, intent, resolvedType, flags, userId,
5263                        hasNonNegativePriorityResult);
5264                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5265                    boolean isVisibleToUser = filterIfNotSystemUser(
5266                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5267                    if (isVisibleToUser) {
5268                        result.add(xpResolveInfo);
5269                        Collections.sort(result, mResolvePrioritySorter);
5270                    }
5271                }
5272                if (hasWebURI(intent)) {
5273                    CrossProfileDomainInfo xpDomainInfo = null;
5274                    final UserInfo parent = getProfileParent(userId);
5275                    if (parent != null) {
5276                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5277                                flags, userId, parent.id);
5278                    }
5279                    if (xpDomainInfo != null) {
5280                        if (xpResolveInfo != null) {
5281                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5282                            // in the result.
5283                            result.remove(xpResolveInfo);
5284                        }
5285                        if (result.size() == 0) {
5286                            result.add(xpDomainInfo.resolveInfo);
5287                            return result;
5288                        }
5289                    } else if (result.size() <= 1) {
5290                        return result;
5291                    }
5292                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5293                            xpDomainInfo, userId);
5294                    Collections.sort(result, mResolvePrioritySorter);
5295                }
5296                return result;
5297            }
5298            final PackageParser.Package pkg = mPackages.get(pkgName);
5299            if (pkg != null) {
5300                return filterIfNotSystemUser(
5301                        mActivities.queryIntentForPackage(
5302                                intent, resolvedType, flags, pkg.activities, userId),
5303                        userId);
5304            }
5305            return new ArrayList<ResolveInfo>();
5306        }
5307    }
5308
5309    private static class CrossProfileDomainInfo {
5310        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5311        ResolveInfo resolveInfo;
5312        /* Best domain verification status of the activities found in the other profile */
5313        int bestDomainVerificationStatus;
5314    }
5315
5316    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5317            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5318        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5319                sourceUserId)) {
5320            return null;
5321        }
5322        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5323                resolvedType, flags, parentUserId);
5324
5325        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5326            return null;
5327        }
5328        CrossProfileDomainInfo result = null;
5329        int size = resultTargetUser.size();
5330        for (int i = 0; i < size; i++) {
5331            ResolveInfo riTargetUser = resultTargetUser.get(i);
5332            // Intent filter verification is only for filters that specify a host. So don't return
5333            // those that handle all web uris.
5334            if (riTargetUser.handleAllWebDataURI) {
5335                continue;
5336            }
5337            String packageName = riTargetUser.activityInfo.packageName;
5338            PackageSetting ps = mSettings.mPackages.get(packageName);
5339            if (ps == null) {
5340                continue;
5341            }
5342            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5343            int status = (int)(verificationState >> 32);
5344            if (result == null) {
5345                result = new CrossProfileDomainInfo();
5346                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5347                        sourceUserId, parentUserId);
5348                result.bestDomainVerificationStatus = status;
5349            } else {
5350                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5351                        result.bestDomainVerificationStatus);
5352            }
5353        }
5354        // Don't consider matches with status NEVER across profiles.
5355        if (result != null && result.bestDomainVerificationStatus
5356                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5357            return null;
5358        }
5359        return result;
5360    }
5361
5362    /**
5363     * Verification statuses are ordered from the worse to the best, except for
5364     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5365     */
5366    private int bestDomainVerificationStatus(int status1, int status2) {
5367        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5368            return status2;
5369        }
5370        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5371            return status1;
5372        }
5373        return (int) MathUtils.max(status1, status2);
5374    }
5375
5376    private boolean isUserEnabled(int userId) {
5377        long callingId = Binder.clearCallingIdentity();
5378        try {
5379            UserInfo userInfo = sUserManager.getUserInfo(userId);
5380            return userInfo != null && userInfo.isEnabled();
5381        } finally {
5382            Binder.restoreCallingIdentity(callingId);
5383        }
5384    }
5385
5386    /**
5387     * Filter out activities with systemUserOnly flag set, when current user is not System.
5388     *
5389     * @return filtered list
5390     */
5391    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5392        if (userId == UserHandle.USER_SYSTEM) {
5393            return resolveInfos;
5394        }
5395        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5396            ResolveInfo info = resolveInfos.get(i);
5397            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5398                resolveInfos.remove(i);
5399            }
5400        }
5401        return resolveInfos;
5402    }
5403
5404    /**
5405     * @param resolveInfos list of resolve infos in descending priority order
5406     * @return if the list contains a resolve info with non-negative priority
5407     */
5408    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5409        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5410    }
5411
5412    private static boolean hasWebURI(Intent intent) {
5413        if (intent.getData() == null) {
5414            return false;
5415        }
5416        final String scheme = intent.getScheme();
5417        if (TextUtils.isEmpty(scheme)) {
5418            return false;
5419        }
5420        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5421    }
5422
5423    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5424            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5425            int userId) {
5426        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5427
5428        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5429            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5430                    candidates.size());
5431        }
5432
5433        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5434        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5435        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5436        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5437        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5438        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5439
5440        synchronized (mPackages) {
5441            final int count = candidates.size();
5442            // First, try to use linked apps. Partition the candidates into four lists:
5443            // one for the final results, one for the "do not use ever", one for "undefined status"
5444            // and finally one for "browser app type".
5445            for (int n=0; n<count; n++) {
5446                ResolveInfo info = candidates.get(n);
5447                String packageName = info.activityInfo.packageName;
5448                PackageSetting ps = mSettings.mPackages.get(packageName);
5449                if (ps != null) {
5450                    // Add to the special match all list (Browser use case)
5451                    if (info.handleAllWebDataURI) {
5452                        matchAllList.add(info);
5453                        continue;
5454                    }
5455                    // Try to get the status from User settings first
5456                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5457                    int status = (int)(packedStatus >> 32);
5458                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5459                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5460                        if (DEBUG_DOMAIN_VERIFICATION) {
5461                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5462                                    + " : linkgen=" + linkGeneration);
5463                        }
5464                        // Use link-enabled generation as preferredOrder, i.e.
5465                        // prefer newly-enabled over earlier-enabled.
5466                        info.preferredOrder = linkGeneration;
5467                        alwaysList.add(info);
5468                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5469                        if (DEBUG_DOMAIN_VERIFICATION) {
5470                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5471                        }
5472                        neverList.add(info);
5473                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5474                        if (DEBUG_DOMAIN_VERIFICATION) {
5475                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5476                        }
5477                        alwaysAskList.add(info);
5478                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5479                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5480                        if (DEBUG_DOMAIN_VERIFICATION) {
5481                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5482                        }
5483                        undefinedList.add(info);
5484                    }
5485                }
5486            }
5487
5488            // We'll want to include browser possibilities in a few cases
5489            boolean includeBrowser = false;
5490
5491            // First try to add the "always" resolution(s) for the current user, if any
5492            if (alwaysList.size() > 0) {
5493                result.addAll(alwaysList);
5494            } else {
5495                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5496                result.addAll(undefinedList);
5497                // Maybe add one for the other profile.
5498                if (xpDomainInfo != null && (
5499                        xpDomainInfo.bestDomainVerificationStatus
5500                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5501                    result.add(xpDomainInfo.resolveInfo);
5502                }
5503                includeBrowser = true;
5504            }
5505
5506            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5507            // If there were 'always' entries their preferred order has been set, so we also
5508            // back that off to make the alternatives equivalent
5509            if (alwaysAskList.size() > 0) {
5510                for (ResolveInfo i : result) {
5511                    i.preferredOrder = 0;
5512                }
5513                result.addAll(alwaysAskList);
5514                includeBrowser = true;
5515            }
5516
5517            if (includeBrowser) {
5518                // Also add browsers (all of them or only the default one)
5519                if (DEBUG_DOMAIN_VERIFICATION) {
5520                    Slog.v(TAG, "   ...including browsers in candidate set");
5521                }
5522                if ((matchFlags & MATCH_ALL) != 0) {
5523                    result.addAll(matchAllList);
5524                } else {
5525                    // Browser/generic handling case.  If there's a default browser, go straight
5526                    // to that (but only if there is no other higher-priority match).
5527                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5528                    int maxMatchPrio = 0;
5529                    ResolveInfo defaultBrowserMatch = null;
5530                    final int numCandidates = matchAllList.size();
5531                    for (int n = 0; n < numCandidates; n++) {
5532                        ResolveInfo info = matchAllList.get(n);
5533                        // track the highest overall match priority...
5534                        if (info.priority > maxMatchPrio) {
5535                            maxMatchPrio = info.priority;
5536                        }
5537                        // ...and the highest-priority default browser match
5538                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5539                            if (defaultBrowserMatch == null
5540                                    || (defaultBrowserMatch.priority < info.priority)) {
5541                                if (debug) {
5542                                    Slog.v(TAG, "Considering default browser match " + info);
5543                                }
5544                                defaultBrowserMatch = info;
5545                            }
5546                        }
5547                    }
5548                    if (defaultBrowserMatch != null
5549                            && defaultBrowserMatch.priority >= maxMatchPrio
5550                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5551                    {
5552                        if (debug) {
5553                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5554                        }
5555                        result.add(defaultBrowserMatch);
5556                    } else {
5557                        result.addAll(matchAllList);
5558                    }
5559                }
5560
5561                // If there is nothing selected, add all candidates and remove the ones that the user
5562                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5563                if (result.size() == 0) {
5564                    result.addAll(candidates);
5565                    result.removeAll(neverList);
5566                }
5567            }
5568        }
5569        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5570            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5571                    result.size());
5572            for (ResolveInfo info : result) {
5573                Slog.v(TAG, "  + " + info.activityInfo);
5574            }
5575        }
5576        return result;
5577    }
5578
5579    // Returns a packed value as a long:
5580    //
5581    // high 'int'-sized word: link status: undefined/ask/never/always.
5582    // low 'int'-sized word: relative priority among 'always' results.
5583    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5584        long result = ps.getDomainVerificationStatusForUser(userId);
5585        // if none available, get the master status
5586        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5587            if (ps.getIntentFilterVerificationInfo() != null) {
5588                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5589            }
5590        }
5591        return result;
5592    }
5593
5594    private ResolveInfo querySkipCurrentProfileIntents(
5595            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5596            int flags, int sourceUserId) {
5597        if (matchingFilters != null) {
5598            int size = matchingFilters.size();
5599            for (int i = 0; i < size; i ++) {
5600                CrossProfileIntentFilter filter = matchingFilters.get(i);
5601                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5602                    // Checking if there are activities in the target user that can handle the
5603                    // intent.
5604                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5605                            resolvedType, flags, sourceUserId);
5606                    if (resolveInfo != null) {
5607                        return resolveInfo;
5608                    }
5609                }
5610            }
5611        }
5612        return null;
5613    }
5614
5615    // Return matching ResolveInfo in target user if any.
5616    private ResolveInfo queryCrossProfileIntents(
5617            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5618            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5619        if (matchingFilters != null) {
5620            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5621            // match the same intent. For performance reasons, it is better not to
5622            // run queryIntent twice for the same userId
5623            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5624            int size = matchingFilters.size();
5625            for (int i = 0; i < size; i++) {
5626                CrossProfileIntentFilter filter = matchingFilters.get(i);
5627                int targetUserId = filter.getTargetUserId();
5628                boolean skipCurrentProfile =
5629                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5630                boolean skipCurrentProfileIfNoMatchFound =
5631                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5632                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5633                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5634                    // Checking if there are activities in the target user that can handle the
5635                    // intent.
5636                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5637                            resolvedType, flags, sourceUserId);
5638                    if (resolveInfo != null) return resolveInfo;
5639                    alreadyTriedUserIds.put(targetUserId, true);
5640                }
5641            }
5642        }
5643        return null;
5644    }
5645
5646    /**
5647     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5648     * will forward the intent to the filter's target user.
5649     * Otherwise, returns null.
5650     */
5651    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5652            String resolvedType, int flags, int sourceUserId) {
5653        int targetUserId = filter.getTargetUserId();
5654        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5655                resolvedType, flags, targetUserId);
5656        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5657            // If all the matches in the target profile are suspended, return null.
5658            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5659                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5660                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5661                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5662                            targetUserId);
5663                }
5664            }
5665        }
5666        return null;
5667    }
5668
5669    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5670            int sourceUserId, int targetUserId) {
5671        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5672        long ident = Binder.clearCallingIdentity();
5673        boolean targetIsProfile;
5674        try {
5675            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5676        } finally {
5677            Binder.restoreCallingIdentity(ident);
5678        }
5679        String className;
5680        if (targetIsProfile) {
5681            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5682        } else {
5683            className = FORWARD_INTENT_TO_PARENT;
5684        }
5685        ComponentName forwardingActivityComponentName = new ComponentName(
5686                mAndroidApplication.packageName, className);
5687        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5688                sourceUserId);
5689        if (!targetIsProfile) {
5690            forwardingActivityInfo.showUserIcon = targetUserId;
5691            forwardingResolveInfo.noResourceId = true;
5692        }
5693        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5694        forwardingResolveInfo.priority = 0;
5695        forwardingResolveInfo.preferredOrder = 0;
5696        forwardingResolveInfo.match = 0;
5697        forwardingResolveInfo.isDefault = true;
5698        forwardingResolveInfo.filter = filter;
5699        forwardingResolveInfo.targetUserId = targetUserId;
5700        return forwardingResolveInfo;
5701    }
5702
5703    @Override
5704    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5705            Intent[] specifics, String[] specificTypes, Intent intent,
5706            String resolvedType, int flags, int userId) {
5707        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5708                specificTypes, intent, resolvedType, flags, userId));
5709    }
5710
5711    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5712            Intent[] specifics, String[] specificTypes, Intent intent,
5713            String resolvedType, int flags, int userId) {
5714        if (!sUserManager.exists(userId)) return Collections.emptyList();
5715        flags = updateFlagsForResolve(flags, userId, intent);
5716        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5717                false /* requireFullPermission */, false /* checkShell */,
5718                "query intent activity options");
5719        final String resultsAction = intent.getAction();
5720
5721        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5722                | PackageManager.GET_RESOLVED_FILTER, userId);
5723
5724        if (DEBUG_INTENT_MATCHING) {
5725            Log.v(TAG, "Query " + intent + ": " + results);
5726        }
5727
5728        int specificsPos = 0;
5729        int N;
5730
5731        // todo: note that the algorithm used here is O(N^2).  This
5732        // isn't a problem in our current environment, but if we start running
5733        // into situations where we have more than 5 or 10 matches then this
5734        // should probably be changed to something smarter...
5735
5736        // First we go through and resolve each of the specific items
5737        // that were supplied, taking care of removing any corresponding
5738        // duplicate items in the generic resolve list.
5739        if (specifics != null) {
5740            for (int i=0; i<specifics.length; i++) {
5741                final Intent sintent = specifics[i];
5742                if (sintent == null) {
5743                    continue;
5744                }
5745
5746                if (DEBUG_INTENT_MATCHING) {
5747                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5748                }
5749
5750                String action = sintent.getAction();
5751                if (resultsAction != null && resultsAction.equals(action)) {
5752                    // If this action was explicitly requested, then don't
5753                    // remove things that have it.
5754                    action = null;
5755                }
5756
5757                ResolveInfo ri = null;
5758                ActivityInfo ai = null;
5759
5760                ComponentName comp = sintent.getComponent();
5761                if (comp == null) {
5762                    ri = resolveIntent(
5763                        sintent,
5764                        specificTypes != null ? specificTypes[i] : null,
5765                            flags, userId);
5766                    if (ri == null) {
5767                        continue;
5768                    }
5769                    if (ri == mResolveInfo) {
5770                        // ACK!  Must do something better with this.
5771                    }
5772                    ai = ri.activityInfo;
5773                    comp = new ComponentName(ai.applicationInfo.packageName,
5774                            ai.name);
5775                } else {
5776                    ai = getActivityInfo(comp, flags, userId);
5777                    if (ai == null) {
5778                        continue;
5779                    }
5780                }
5781
5782                // Look for any generic query activities that are duplicates
5783                // of this specific one, and remove them from the results.
5784                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5785                N = results.size();
5786                int j;
5787                for (j=specificsPos; j<N; j++) {
5788                    ResolveInfo sri = results.get(j);
5789                    if ((sri.activityInfo.name.equals(comp.getClassName())
5790                            && sri.activityInfo.applicationInfo.packageName.equals(
5791                                    comp.getPackageName()))
5792                        || (action != null && sri.filter.matchAction(action))) {
5793                        results.remove(j);
5794                        if (DEBUG_INTENT_MATCHING) Log.v(
5795                            TAG, "Removing duplicate item from " + j
5796                            + " due to specific " + specificsPos);
5797                        if (ri == null) {
5798                            ri = sri;
5799                        }
5800                        j--;
5801                        N--;
5802                    }
5803                }
5804
5805                // Add this specific item to its proper place.
5806                if (ri == null) {
5807                    ri = new ResolveInfo();
5808                    ri.activityInfo = ai;
5809                }
5810                results.add(specificsPos, ri);
5811                ri.specificIndex = i;
5812                specificsPos++;
5813            }
5814        }
5815
5816        // Now we go through the remaining generic results and remove any
5817        // duplicate actions that are found here.
5818        N = results.size();
5819        for (int i=specificsPos; i<N-1; i++) {
5820            final ResolveInfo rii = results.get(i);
5821            if (rii.filter == null) {
5822                continue;
5823            }
5824
5825            // Iterate over all of the actions of this result's intent
5826            // filter...  typically this should be just one.
5827            final Iterator<String> it = rii.filter.actionsIterator();
5828            if (it == null) {
5829                continue;
5830            }
5831            while (it.hasNext()) {
5832                final String action = it.next();
5833                if (resultsAction != null && resultsAction.equals(action)) {
5834                    // If this action was explicitly requested, then don't
5835                    // remove things that have it.
5836                    continue;
5837                }
5838                for (int j=i+1; j<N; j++) {
5839                    final ResolveInfo rij = results.get(j);
5840                    if (rij.filter != null && rij.filter.hasAction(action)) {
5841                        results.remove(j);
5842                        if (DEBUG_INTENT_MATCHING) Log.v(
5843                            TAG, "Removing duplicate item from " + j
5844                            + " due to action " + action + " at " + i);
5845                        j--;
5846                        N--;
5847                    }
5848                }
5849            }
5850
5851            // If the caller didn't request filter information, drop it now
5852            // so we don't have to marshall/unmarshall it.
5853            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5854                rii.filter = null;
5855            }
5856        }
5857
5858        // Filter out the caller activity if so requested.
5859        if (caller != null) {
5860            N = results.size();
5861            for (int i=0; i<N; i++) {
5862                ActivityInfo ainfo = results.get(i).activityInfo;
5863                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5864                        && caller.getClassName().equals(ainfo.name)) {
5865                    results.remove(i);
5866                    break;
5867                }
5868            }
5869        }
5870
5871        // If the caller didn't request filter information,
5872        // drop them now so we don't have to
5873        // marshall/unmarshall it.
5874        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5875            N = results.size();
5876            for (int i=0; i<N; i++) {
5877                results.get(i).filter = null;
5878            }
5879        }
5880
5881        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5882        return results;
5883    }
5884
5885    @Override
5886    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5887            String resolvedType, int flags, int userId) {
5888        return new ParceledListSlice<>(
5889                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5890    }
5891
5892    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5893            String resolvedType, int flags, int userId) {
5894        if (!sUserManager.exists(userId)) return Collections.emptyList();
5895        flags = updateFlagsForResolve(flags, userId, intent);
5896        ComponentName comp = intent.getComponent();
5897        if (comp == null) {
5898            if (intent.getSelector() != null) {
5899                intent = intent.getSelector();
5900                comp = intent.getComponent();
5901            }
5902        }
5903        if (comp != null) {
5904            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5905            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5906            if (ai != null) {
5907                ResolveInfo ri = new ResolveInfo();
5908                ri.activityInfo = ai;
5909                list.add(ri);
5910            }
5911            return list;
5912        }
5913
5914        // reader
5915        synchronized (mPackages) {
5916            String pkgName = intent.getPackage();
5917            if (pkgName == null) {
5918                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5919            }
5920            final PackageParser.Package pkg = mPackages.get(pkgName);
5921            if (pkg != null) {
5922                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5923                        userId);
5924            }
5925            return Collections.emptyList();
5926        }
5927    }
5928
5929    @Override
5930    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5931        if (!sUserManager.exists(userId)) return null;
5932        flags = updateFlagsForResolve(flags, userId, intent);
5933        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5934        if (query != null) {
5935            if (query.size() >= 1) {
5936                // If there is more than one service with the same priority,
5937                // just arbitrarily pick the first one.
5938                return query.get(0);
5939            }
5940        }
5941        return null;
5942    }
5943
5944    @Override
5945    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5946            String resolvedType, int flags, int userId) {
5947        return new ParceledListSlice<>(
5948                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5949    }
5950
5951    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5952            String resolvedType, int flags, int userId) {
5953        if (!sUserManager.exists(userId)) return Collections.emptyList();
5954        flags = updateFlagsForResolve(flags, userId, intent);
5955        ComponentName comp = intent.getComponent();
5956        if (comp == null) {
5957            if (intent.getSelector() != null) {
5958                intent = intent.getSelector();
5959                comp = intent.getComponent();
5960            }
5961        }
5962        if (comp != null) {
5963            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5964            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5965            if (si != null) {
5966                final ResolveInfo ri = new ResolveInfo();
5967                ri.serviceInfo = si;
5968                list.add(ri);
5969            }
5970            return list;
5971        }
5972
5973        // reader
5974        synchronized (mPackages) {
5975            String pkgName = intent.getPackage();
5976            if (pkgName == null) {
5977                return mServices.queryIntent(intent, resolvedType, flags, userId);
5978            }
5979            final PackageParser.Package pkg = mPackages.get(pkgName);
5980            if (pkg != null) {
5981                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5982                        userId);
5983            }
5984            return Collections.emptyList();
5985        }
5986    }
5987
5988    @Override
5989    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5990            String resolvedType, int flags, int userId) {
5991        return new ParceledListSlice<>(
5992                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5993    }
5994
5995    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5996            Intent intent, String resolvedType, int flags, int userId) {
5997        if (!sUserManager.exists(userId)) return Collections.emptyList();
5998        flags = updateFlagsForResolve(flags, userId, intent);
5999        ComponentName comp = intent.getComponent();
6000        if (comp == null) {
6001            if (intent.getSelector() != null) {
6002                intent = intent.getSelector();
6003                comp = intent.getComponent();
6004            }
6005        }
6006        if (comp != null) {
6007            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6008            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6009            if (pi != null) {
6010                final ResolveInfo ri = new ResolveInfo();
6011                ri.providerInfo = pi;
6012                list.add(ri);
6013            }
6014            return list;
6015        }
6016
6017        // reader
6018        synchronized (mPackages) {
6019            String pkgName = intent.getPackage();
6020            if (pkgName == null) {
6021                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6022            }
6023            final PackageParser.Package pkg = mPackages.get(pkgName);
6024            if (pkg != null) {
6025                return mProviders.queryIntentForPackage(
6026                        intent, resolvedType, flags, pkg.providers, userId);
6027            }
6028            return Collections.emptyList();
6029        }
6030    }
6031
6032    @Override
6033    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6034        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6035        flags = updateFlagsForPackage(flags, userId, null);
6036        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6037        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6038                true /* requireFullPermission */, false /* checkShell */,
6039                "get installed packages");
6040
6041        // writer
6042        synchronized (mPackages) {
6043            ArrayList<PackageInfo> list;
6044            if (listUninstalled) {
6045                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6046                for (PackageSetting ps : mSettings.mPackages.values()) {
6047                    final PackageInfo pi;
6048                    if (ps.pkg != null) {
6049                        pi = generatePackageInfo(ps, flags, userId);
6050                    } else {
6051                        pi = generatePackageInfo(ps, flags, userId);
6052                    }
6053                    if (pi != null) {
6054                        list.add(pi);
6055                    }
6056                }
6057            } else {
6058                list = new ArrayList<PackageInfo>(mPackages.size());
6059                for (PackageParser.Package p : mPackages.values()) {
6060                    final PackageInfo pi =
6061                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6062                    if (pi != null) {
6063                        list.add(pi);
6064                    }
6065                }
6066            }
6067
6068            return new ParceledListSlice<PackageInfo>(list);
6069        }
6070    }
6071
6072    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6073            String[] permissions, boolean[] tmp, int flags, int userId) {
6074        int numMatch = 0;
6075        final PermissionsState permissionsState = ps.getPermissionsState();
6076        for (int i=0; i<permissions.length; i++) {
6077            final String permission = permissions[i];
6078            if (permissionsState.hasPermission(permission, userId)) {
6079                tmp[i] = true;
6080                numMatch++;
6081            } else {
6082                tmp[i] = false;
6083            }
6084        }
6085        if (numMatch == 0) {
6086            return;
6087        }
6088        final PackageInfo pi;
6089        if (ps.pkg != null) {
6090            pi = generatePackageInfo(ps, flags, userId);
6091        } else {
6092            pi = generatePackageInfo(ps, flags, userId);
6093        }
6094        // The above might return null in cases of uninstalled apps or install-state
6095        // skew across users/profiles.
6096        if (pi != null) {
6097            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6098                if (numMatch == permissions.length) {
6099                    pi.requestedPermissions = permissions;
6100                } else {
6101                    pi.requestedPermissions = new String[numMatch];
6102                    numMatch = 0;
6103                    for (int i=0; i<permissions.length; i++) {
6104                        if (tmp[i]) {
6105                            pi.requestedPermissions[numMatch] = permissions[i];
6106                            numMatch++;
6107                        }
6108                    }
6109                }
6110            }
6111            list.add(pi);
6112        }
6113    }
6114
6115    @Override
6116    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6117            String[] permissions, int flags, int userId) {
6118        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6119        flags = updateFlagsForPackage(flags, userId, permissions);
6120        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6121
6122        // writer
6123        synchronized (mPackages) {
6124            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6125            boolean[] tmpBools = new boolean[permissions.length];
6126            if (listUninstalled) {
6127                for (PackageSetting ps : mSettings.mPackages.values()) {
6128                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6129                }
6130            } else {
6131                for (PackageParser.Package pkg : mPackages.values()) {
6132                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6133                    if (ps != null) {
6134                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6135                                userId);
6136                    }
6137                }
6138            }
6139
6140            return new ParceledListSlice<PackageInfo>(list);
6141        }
6142    }
6143
6144    @Override
6145    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6146        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6147        flags = updateFlagsForApplication(flags, userId, null);
6148        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6149
6150        // writer
6151        synchronized (mPackages) {
6152            ArrayList<ApplicationInfo> list;
6153            if (listUninstalled) {
6154                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6155                for (PackageSetting ps : mSettings.mPackages.values()) {
6156                    ApplicationInfo ai;
6157                    if (ps.pkg != null) {
6158                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6159                                ps.readUserState(userId), userId);
6160                    } else {
6161                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6162                    }
6163                    if (ai != null) {
6164                        list.add(ai);
6165                    }
6166                }
6167            } else {
6168                list = new ArrayList<ApplicationInfo>(mPackages.size());
6169                for (PackageParser.Package p : mPackages.values()) {
6170                    if (p.mExtras != null) {
6171                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6172                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6173                        if (ai != null) {
6174                            list.add(ai);
6175                        }
6176                    }
6177                }
6178            }
6179
6180            return new ParceledListSlice<ApplicationInfo>(list);
6181        }
6182    }
6183
6184    @Override
6185    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6186        if (DISABLE_EPHEMERAL_APPS) {
6187            return null;
6188        }
6189
6190        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6191                "getEphemeralApplications");
6192        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6193                true /* requireFullPermission */, false /* checkShell */,
6194                "getEphemeralApplications");
6195        synchronized (mPackages) {
6196            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6197                    .getEphemeralApplicationsLPw(userId);
6198            if (ephemeralApps != null) {
6199                return new ParceledListSlice<>(ephemeralApps);
6200            }
6201        }
6202        return null;
6203    }
6204
6205    @Override
6206    public boolean isEphemeralApplication(String packageName, int userId) {
6207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6208                true /* requireFullPermission */, false /* checkShell */,
6209                "isEphemeral");
6210        if (DISABLE_EPHEMERAL_APPS) {
6211            return false;
6212        }
6213
6214        if (!isCallerSameApp(packageName)) {
6215            return false;
6216        }
6217        synchronized (mPackages) {
6218            PackageParser.Package pkg = mPackages.get(packageName);
6219            if (pkg != null) {
6220                return pkg.applicationInfo.isEphemeralApp();
6221            }
6222        }
6223        return false;
6224    }
6225
6226    @Override
6227    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6228        if (DISABLE_EPHEMERAL_APPS) {
6229            return null;
6230        }
6231
6232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6233                true /* requireFullPermission */, false /* checkShell */,
6234                "getCookie");
6235        if (!isCallerSameApp(packageName)) {
6236            return null;
6237        }
6238        synchronized (mPackages) {
6239            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6240                    packageName, userId);
6241        }
6242    }
6243
6244    @Override
6245    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6246        if (DISABLE_EPHEMERAL_APPS) {
6247            return true;
6248        }
6249
6250        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6251                true /* requireFullPermission */, true /* checkShell */,
6252                "setCookie");
6253        if (!isCallerSameApp(packageName)) {
6254            return false;
6255        }
6256        synchronized (mPackages) {
6257            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6258                    packageName, cookie, userId);
6259        }
6260    }
6261
6262    @Override
6263    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6264        if (DISABLE_EPHEMERAL_APPS) {
6265            return null;
6266        }
6267
6268        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6269                "getEphemeralApplicationIcon");
6270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6271                true /* requireFullPermission */, false /* checkShell */,
6272                "getEphemeralApplicationIcon");
6273        synchronized (mPackages) {
6274            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6275                    packageName, userId);
6276        }
6277    }
6278
6279    private boolean isCallerSameApp(String packageName) {
6280        PackageParser.Package pkg = mPackages.get(packageName);
6281        return pkg != null
6282                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6283    }
6284
6285    @Override
6286    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6287        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6288    }
6289
6290    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6291        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6292
6293        // reader
6294        synchronized (mPackages) {
6295            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6296            final int userId = UserHandle.getCallingUserId();
6297            while (i.hasNext()) {
6298                final PackageParser.Package p = i.next();
6299                if (p.applicationInfo == null) continue;
6300
6301                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6302                        && !p.applicationInfo.isDirectBootAware();
6303                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6304                        && p.applicationInfo.isDirectBootAware();
6305
6306                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6307                        && (!mSafeMode || isSystemApp(p))
6308                        && (matchesUnaware || matchesAware)) {
6309                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6310                    if (ps != null) {
6311                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6312                                ps.readUserState(userId), userId);
6313                        if (ai != null) {
6314                            finalList.add(ai);
6315                        }
6316                    }
6317                }
6318            }
6319        }
6320
6321        return finalList;
6322    }
6323
6324    @Override
6325    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6326        if (!sUserManager.exists(userId)) return null;
6327        flags = updateFlagsForComponent(flags, userId, name);
6328        // reader
6329        synchronized (mPackages) {
6330            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6331            PackageSetting ps = provider != null
6332                    ? mSettings.mPackages.get(provider.owner.packageName)
6333                    : null;
6334            return ps != null
6335                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6336                    ? PackageParser.generateProviderInfo(provider, flags,
6337                            ps.readUserState(userId), userId)
6338                    : null;
6339        }
6340    }
6341
6342    /**
6343     * @deprecated
6344     */
6345    @Deprecated
6346    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6347        // reader
6348        synchronized (mPackages) {
6349            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6350                    .entrySet().iterator();
6351            final int userId = UserHandle.getCallingUserId();
6352            while (i.hasNext()) {
6353                Map.Entry<String, PackageParser.Provider> entry = i.next();
6354                PackageParser.Provider p = entry.getValue();
6355                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6356
6357                if (ps != null && p.syncable
6358                        && (!mSafeMode || (p.info.applicationInfo.flags
6359                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6360                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6361                            ps.readUserState(userId), userId);
6362                    if (info != null) {
6363                        outNames.add(entry.getKey());
6364                        outInfo.add(info);
6365                    }
6366                }
6367            }
6368        }
6369    }
6370
6371    @Override
6372    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6373            int uid, int flags) {
6374        final int userId = processName != null ? UserHandle.getUserId(uid)
6375                : UserHandle.getCallingUserId();
6376        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6377        flags = updateFlagsForComponent(flags, userId, processName);
6378
6379        ArrayList<ProviderInfo> finalList = null;
6380        // reader
6381        synchronized (mPackages) {
6382            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6383            while (i.hasNext()) {
6384                final PackageParser.Provider p = i.next();
6385                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6386                if (ps != null && p.info.authority != null
6387                        && (processName == null
6388                                || (p.info.processName.equals(processName)
6389                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6390                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6391                    if (finalList == null) {
6392                        finalList = new ArrayList<ProviderInfo>(3);
6393                    }
6394                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6395                            ps.readUserState(userId), userId);
6396                    if (info != null) {
6397                        finalList.add(info);
6398                    }
6399                }
6400            }
6401        }
6402
6403        if (finalList != null) {
6404            Collections.sort(finalList, mProviderInitOrderSorter);
6405            return new ParceledListSlice<ProviderInfo>(finalList);
6406        }
6407
6408        return ParceledListSlice.emptyList();
6409    }
6410
6411    @Override
6412    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6413        // reader
6414        synchronized (mPackages) {
6415            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6416            return PackageParser.generateInstrumentationInfo(i, flags);
6417        }
6418    }
6419
6420    @Override
6421    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6422            String targetPackage, int flags) {
6423        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6424    }
6425
6426    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6427            int flags) {
6428        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6429
6430        // reader
6431        synchronized (mPackages) {
6432            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6433            while (i.hasNext()) {
6434                final PackageParser.Instrumentation p = i.next();
6435                if (targetPackage == null
6436                        || targetPackage.equals(p.info.targetPackage)) {
6437                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6438                            flags);
6439                    if (ii != null) {
6440                        finalList.add(ii);
6441                    }
6442                }
6443            }
6444        }
6445
6446        return finalList;
6447    }
6448
6449    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6450        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6451        if (overlays == null) {
6452            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6453            return;
6454        }
6455        for (PackageParser.Package opkg : overlays.values()) {
6456            // Not much to do if idmap fails: we already logged the error
6457            // and we certainly don't want to abort installation of pkg simply
6458            // because an overlay didn't fit properly. For these reasons,
6459            // ignore the return value of createIdmapForPackagePairLI.
6460            createIdmapForPackagePairLI(pkg, opkg);
6461        }
6462    }
6463
6464    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6465            PackageParser.Package opkg) {
6466        if (!opkg.mTrustedOverlay) {
6467            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6468                    opkg.baseCodePath + ": overlay not trusted");
6469            return false;
6470        }
6471        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6472        if (overlaySet == null) {
6473            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6474                    opkg.baseCodePath + " but target package has no known overlays");
6475            return false;
6476        }
6477        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6478        // TODO: generate idmap for split APKs
6479        try {
6480            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6481        } catch (InstallerException e) {
6482            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6483                    + opkg.baseCodePath);
6484            return false;
6485        }
6486        PackageParser.Package[] overlayArray =
6487            overlaySet.values().toArray(new PackageParser.Package[0]);
6488        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6489            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6490                return p1.mOverlayPriority - p2.mOverlayPriority;
6491            }
6492        };
6493        Arrays.sort(overlayArray, cmp);
6494
6495        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6496        int i = 0;
6497        for (PackageParser.Package p : overlayArray) {
6498            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6499        }
6500        return true;
6501    }
6502
6503    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6504        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6505        try {
6506            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6507        } finally {
6508            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6509        }
6510    }
6511
6512    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6513        final File[] files = dir.listFiles();
6514        if (ArrayUtils.isEmpty(files)) {
6515            Log.d(TAG, "No files in app dir " + dir);
6516            return;
6517        }
6518
6519        if (DEBUG_PACKAGE_SCANNING) {
6520            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6521                    + " flags=0x" + Integer.toHexString(parseFlags));
6522        }
6523
6524        for (File file : files) {
6525            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6526                    && !PackageInstallerService.isStageName(file.getName());
6527            if (!isPackage) {
6528                // Ignore entries which are not packages
6529                continue;
6530            }
6531            try {
6532                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6533                        scanFlags, currentTime, null);
6534            } catch (PackageManagerException e) {
6535                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6536
6537                // Delete invalid userdata apps
6538                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6539                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6540                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6541                    removeCodePathLI(file);
6542                }
6543            }
6544        }
6545    }
6546
6547    private static File getSettingsProblemFile() {
6548        File dataDir = Environment.getDataDirectory();
6549        File systemDir = new File(dataDir, "system");
6550        File fname = new File(systemDir, "uiderrors.txt");
6551        return fname;
6552    }
6553
6554    static void reportSettingsProblem(int priority, String msg) {
6555        logCriticalInfo(priority, msg);
6556    }
6557
6558    static void logCriticalInfo(int priority, String msg) {
6559        Slog.println(priority, TAG, msg);
6560        EventLogTags.writePmCriticalInfo(msg);
6561        try {
6562            File fname = getSettingsProblemFile();
6563            FileOutputStream out = new FileOutputStream(fname, true);
6564            PrintWriter pw = new FastPrintWriter(out);
6565            SimpleDateFormat formatter = new SimpleDateFormat();
6566            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6567            pw.println(dateString + ": " + msg);
6568            pw.close();
6569            FileUtils.setPermissions(
6570                    fname.toString(),
6571                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6572                    -1, -1);
6573        } catch (java.io.IOException e) {
6574        }
6575    }
6576
6577    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6578            int parseFlags) throws PackageManagerException {
6579        if (ps != null
6580                && ps.codePath.equals(srcFile)
6581                && ps.timeStamp == srcFile.lastModified()
6582                && !isCompatSignatureUpdateNeeded(pkg)
6583                && !isRecoverSignatureUpdateNeeded(pkg)) {
6584            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6585            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6586            ArraySet<PublicKey> signingKs;
6587            synchronized (mPackages) {
6588                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6589            }
6590            if (ps.signatures.mSignatures != null
6591                    && ps.signatures.mSignatures.length != 0
6592                    && signingKs != null) {
6593                // Optimization: reuse the existing cached certificates
6594                // if the package appears to be unchanged.
6595                pkg.mSignatures = ps.signatures.mSignatures;
6596                pkg.mSigningKeys = signingKs;
6597                return;
6598            }
6599
6600            Slog.w(TAG, "PackageSetting for " + ps.name
6601                    + " is missing signatures.  Collecting certs again to recover them.");
6602        } else {
6603            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6604        }
6605
6606        try {
6607            PackageParser.collectCertificates(pkg, parseFlags);
6608        } catch (PackageParserException e) {
6609            throw PackageManagerException.from(e);
6610        }
6611    }
6612
6613    /**
6614     *  Traces a package scan.
6615     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6616     */
6617    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6618            long currentTime, UserHandle user) throws PackageManagerException {
6619        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6620        try {
6621            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6622        } finally {
6623            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6624        }
6625    }
6626
6627    /**
6628     *  Scans a package and returns the newly parsed package.
6629     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6630     */
6631    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6632            long currentTime, UserHandle user) throws PackageManagerException {
6633        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6634        parseFlags |= mDefParseFlags;
6635        PackageParser pp = new PackageParser();
6636        pp.setSeparateProcesses(mSeparateProcesses);
6637        pp.setOnlyCoreApps(mOnlyCore);
6638        pp.setDisplayMetrics(mMetrics);
6639
6640        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6641            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6642        }
6643
6644        final PackageParser.Package pkg;
6645        try {
6646            pkg = pp.parsePackage(scanFile, parseFlags);
6647        } catch (PackageParserException e) {
6648            throw PackageManagerException.from(e);
6649        }
6650
6651        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6652    }
6653
6654    /**
6655     *  Scans a package and returns the newly parsed package.
6656     *  @throws PackageManagerException on a parse error.
6657     */
6658    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6659            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6660            throws PackageManagerException {
6661        // If the package has children and this is the first dive in the function
6662        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6663        // packages (parent and children) would be successfully scanned before the
6664        // actual scan since scanning mutates internal state and we want to atomically
6665        // install the package and its children.
6666        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6667            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6668                scanFlags |= SCAN_CHECK_ONLY;
6669            }
6670        } else {
6671            scanFlags &= ~SCAN_CHECK_ONLY;
6672        }
6673
6674        // Scan the parent
6675        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6676                scanFlags, currentTime, user);
6677
6678        // Scan the children
6679        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6680        for (int i = 0; i < childCount; i++) {
6681            PackageParser.Package childPackage = pkg.childPackages.get(i);
6682            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6683                    currentTime, user);
6684        }
6685
6686
6687        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6688            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6689        }
6690
6691        return scannedPkg;
6692    }
6693
6694    /**
6695     *  Scans a package and returns the newly parsed package.
6696     *  @throws PackageManagerException on a parse error.
6697     */
6698    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6699            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6700            throws PackageManagerException {
6701        PackageSetting ps = null;
6702        PackageSetting updatedPkg;
6703        // reader
6704        synchronized (mPackages) {
6705            // Look to see if we already know about this package.
6706            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6707            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6708                // This package has been renamed to its original name.  Let's
6709                // use that.
6710                ps = mSettings.peekPackageLPr(oldName);
6711            }
6712            // If there was no original package, see one for the real package name.
6713            if (ps == null) {
6714                ps = mSettings.peekPackageLPr(pkg.packageName);
6715            }
6716            // Check to see if this package could be hiding/updating a system
6717            // package.  Must look for it either under the original or real
6718            // package name depending on our state.
6719            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6720            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6721
6722            // If this is a package we don't know about on the system partition, we
6723            // may need to remove disabled child packages on the system partition
6724            // or may need to not add child packages if the parent apk is updated
6725            // on the data partition and no longer defines this child package.
6726            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6727                // If this is a parent package for an updated system app and this system
6728                // app got an OTA update which no longer defines some of the child packages
6729                // we have to prune them from the disabled system packages.
6730                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6731                if (disabledPs != null) {
6732                    final int scannedChildCount = (pkg.childPackages != null)
6733                            ? pkg.childPackages.size() : 0;
6734                    final int disabledChildCount = disabledPs.childPackageNames != null
6735                            ? disabledPs.childPackageNames.size() : 0;
6736                    for (int i = 0; i < disabledChildCount; i++) {
6737                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6738                        boolean disabledPackageAvailable = false;
6739                        for (int j = 0; j < scannedChildCount; j++) {
6740                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6741                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6742                                disabledPackageAvailable = true;
6743                                break;
6744                            }
6745                         }
6746                         if (!disabledPackageAvailable) {
6747                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6748                         }
6749                    }
6750                }
6751            }
6752        }
6753
6754        boolean updatedPkgBetter = false;
6755        // First check if this is a system package that may involve an update
6756        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6757            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6758            // it needs to drop FLAG_PRIVILEGED.
6759            if (locationIsPrivileged(scanFile)) {
6760                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6761            } else {
6762                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6763            }
6764
6765            if (ps != null && !ps.codePath.equals(scanFile)) {
6766                // The path has changed from what was last scanned...  check the
6767                // version of the new path against what we have stored to determine
6768                // what to do.
6769                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6770                if (pkg.mVersionCode <= ps.versionCode) {
6771                    // The system package has been updated and the code path does not match
6772                    // Ignore entry. Skip it.
6773                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6774                            + " ignored: updated version " + ps.versionCode
6775                            + " better than this " + pkg.mVersionCode);
6776                    if (!updatedPkg.codePath.equals(scanFile)) {
6777                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6778                                + ps.name + " changing from " + updatedPkg.codePathString
6779                                + " to " + scanFile);
6780                        updatedPkg.codePath = scanFile;
6781                        updatedPkg.codePathString = scanFile.toString();
6782                        updatedPkg.resourcePath = scanFile;
6783                        updatedPkg.resourcePathString = scanFile.toString();
6784                    }
6785                    updatedPkg.pkg = pkg;
6786                    updatedPkg.versionCode = pkg.mVersionCode;
6787
6788                    // Update the disabled system child packages to point to the package too.
6789                    final int childCount = updatedPkg.childPackageNames != null
6790                            ? updatedPkg.childPackageNames.size() : 0;
6791                    for (int i = 0; i < childCount; i++) {
6792                        String childPackageName = updatedPkg.childPackageNames.get(i);
6793                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6794                                childPackageName);
6795                        if (updatedChildPkg != null) {
6796                            updatedChildPkg.pkg = pkg;
6797                            updatedChildPkg.versionCode = pkg.mVersionCode;
6798                        }
6799                    }
6800
6801                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6802                            + scanFile + " ignored: updated version " + ps.versionCode
6803                            + " better than this " + pkg.mVersionCode);
6804                } else {
6805                    // The current app on the system partition is better than
6806                    // what we have updated to on the data partition; switch
6807                    // back to the system partition version.
6808                    // At this point, its safely assumed that package installation for
6809                    // apps in system partition will go through. If not there won't be a working
6810                    // version of the app
6811                    // writer
6812                    synchronized (mPackages) {
6813                        // Just remove the loaded entries from package lists.
6814                        mPackages.remove(ps.name);
6815                    }
6816
6817                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6818                            + " reverting from " + ps.codePathString
6819                            + ": new version " + pkg.mVersionCode
6820                            + " better than installed " + ps.versionCode);
6821
6822                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6823                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6824                    synchronized (mInstallLock) {
6825                        args.cleanUpResourcesLI();
6826                    }
6827                    synchronized (mPackages) {
6828                        mSettings.enableSystemPackageLPw(ps.name);
6829                    }
6830                    updatedPkgBetter = true;
6831                }
6832            }
6833        }
6834
6835        if (updatedPkg != null) {
6836            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6837            // initially
6838            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6839
6840            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6841            // flag set initially
6842            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6843                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6844            }
6845        }
6846
6847        // Verify certificates against what was last scanned
6848        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6849
6850        /*
6851         * A new system app appeared, but we already had a non-system one of the
6852         * same name installed earlier.
6853         */
6854        boolean shouldHideSystemApp = false;
6855        if (updatedPkg == null && ps != null
6856                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6857            /*
6858             * Check to make sure the signatures match first. If they don't,
6859             * wipe the installed application and its data.
6860             */
6861            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6862                    != PackageManager.SIGNATURE_MATCH) {
6863                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6864                        + " signatures don't match existing userdata copy; removing");
6865                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6866                        "scanPackageInternalLI")) {
6867                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6868                }
6869                ps = null;
6870            } else {
6871                /*
6872                 * If the newly-added system app is an older version than the
6873                 * already installed version, hide it. It will be scanned later
6874                 * and re-added like an update.
6875                 */
6876                if (pkg.mVersionCode <= ps.versionCode) {
6877                    shouldHideSystemApp = true;
6878                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6879                            + " but new version " + pkg.mVersionCode + " better than installed "
6880                            + ps.versionCode + "; hiding system");
6881                } else {
6882                    /*
6883                     * The newly found system app is a newer version that the
6884                     * one previously installed. Simply remove the
6885                     * already-installed application and replace it with our own
6886                     * while keeping the application data.
6887                     */
6888                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6889                            + " reverting from " + ps.codePathString + ": new version "
6890                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6891                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6892                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6893                    synchronized (mInstallLock) {
6894                        args.cleanUpResourcesLI();
6895                    }
6896                }
6897            }
6898        }
6899
6900        // The apk is forward locked (not public) if its code and resources
6901        // are kept in different files. (except for app in either system or
6902        // vendor path).
6903        // TODO grab this value from PackageSettings
6904        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6905            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6906                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6907            }
6908        }
6909
6910        // TODO: extend to support forward-locked splits
6911        String resourcePath = null;
6912        String baseResourcePath = null;
6913        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6914            if (ps != null && ps.resourcePathString != null) {
6915                resourcePath = ps.resourcePathString;
6916                baseResourcePath = ps.resourcePathString;
6917            } else {
6918                // Should not happen at all. Just log an error.
6919                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6920            }
6921        } else {
6922            resourcePath = pkg.codePath;
6923            baseResourcePath = pkg.baseCodePath;
6924        }
6925
6926        // Set application objects path explicitly.
6927        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6928        pkg.setApplicationInfoCodePath(pkg.codePath);
6929        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6930        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6931        pkg.setApplicationInfoResourcePath(resourcePath);
6932        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6933        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6934
6935        // Note that we invoke the following method only if we are about to unpack an application
6936        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6937                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6938
6939        /*
6940         * If the system app should be overridden by a previously installed
6941         * data, hide the system app now and let the /data/app scan pick it up
6942         * again.
6943         */
6944        if (shouldHideSystemApp) {
6945            synchronized (mPackages) {
6946                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6947            }
6948        }
6949
6950        return scannedPkg;
6951    }
6952
6953    private static String fixProcessName(String defProcessName,
6954            String processName, int uid) {
6955        if (processName == null) {
6956            return defProcessName;
6957        }
6958        return processName;
6959    }
6960
6961    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6962            throws PackageManagerException {
6963        if (pkgSetting.signatures.mSignatures != null) {
6964            // Already existing package. Make sure signatures match
6965            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6966                    == PackageManager.SIGNATURE_MATCH;
6967            if (!match) {
6968                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6969                        == PackageManager.SIGNATURE_MATCH;
6970            }
6971            if (!match) {
6972                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6973                        == PackageManager.SIGNATURE_MATCH;
6974            }
6975            if (!match) {
6976                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6977                        + pkg.packageName + " signatures do not match the "
6978                        + "previously installed version; ignoring!");
6979            }
6980        }
6981
6982        // Check for shared user signatures
6983        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6984            // Already existing package. Make sure signatures match
6985            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6986                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6987            if (!match) {
6988                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6989                        == PackageManager.SIGNATURE_MATCH;
6990            }
6991            if (!match) {
6992                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6993                        == PackageManager.SIGNATURE_MATCH;
6994            }
6995            if (!match) {
6996                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6997                        "Package " + pkg.packageName
6998                        + " has no signatures that match those in shared user "
6999                        + pkgSetting.sharedUser.name + "; ignoring!");
7000            }
7001        }
7002    }
7003
7004    /**
7005     * Enforces that only the system UID or root's UID can call a method exposed
7006     * via Binder.
7007     *
7008     * @param message used as message if SecurityException is thrown
7009     * @throws SecurityException if the caller is not system or root
7010     */
7011    private static final void enforceSystemOrRoot(String message) {
7012        final int uid = Binder.getCallingUid();
7013        if (uid != Process.SYSTEM_UID && uid != 0) {
7014            throw new SecurityException(message);
7015        }
7016    }
7017
7018    @Override
7019    public void performFstrimIfNeeded() {
7020        enforceSystemOrRoot("Only the system can request fstrim");
7021
7022        // Before everything else, see whether we need to fstrim.
7023        try {
7024            IMountService ms = PackageHelper.getMountService();
7025            if (ms != null) {
7026                final boolean isUpgrade = isUpgrade();
7027                boolean doTrim = isUpgrade;
7028                if (doTrim) {
7029                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7030                } else {
7031                    final long interval = android.provider.Settings.Global.getLong(
7032                            mContext.getContentResolver(),
7033                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7034                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7035                    if (interval > 0) {
7036                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7037                        if (timeSinceLast > interval) {
7038                            doTrim = true;
7039                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7040                                    + "; running immediately");
7041                        }
7042                    }
7043                }
7044                if (doTrim) {
7045                    if (!isFirstBoot()) {
7046                        try {
7047                            ActivityManagerNative.getDefault().showBootMessage(
7048                                    mContext.getResources().getString(
7049                                            R.string.android_upgrading_fstrim), true);
7050                        } catch (RemoteException e) {
7051                        }
7052                    }
7053                    ms.runMaintenance();
7054                }
7055            } else {
7056                Slog.e(TAG, "Mount service unavailable!");
7057            }
7058        } catch (RemoteException e) {
7059            // Can't happen; MountService is local
7060        }
7061    }
7062
7063    @Override
7064    public void updatePackagesIfNeeded() {
7065        enforceSystemOrRoot("Only the system can request package update");
7066
7067        // We need to re-extract after an OTA.
7068        boolean causeUpgrade = isUpgrade();
7069
7070        // First boot or factory reset.
7071        // Note: we also handle devices that are upgrading to N right now as if it is their
7072        //       first boot, as they do not have profile data.
7073        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7074
7075        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7076        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7077
7078        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7079            return;
7080        }
7081
7082        List<PackageParser.Package> pkgs;
7083        synchronized (mPackages) {
7084            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7085        }
7086
7087        UsageStatsManager usageMgr =
7088                (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
7089
7090        int curr = 0;
7091        int total = pkgs.size();
7092        for (PackageParser.Package pkg : pkgs) {
7093            curr++;
7094
7095            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7096                if (DEBUG_DEXOPT) {
7097                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7098                }
7099                continue;
7100            }
7101
7102            if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) {
7103                if (DEBUG_DEXOPT) {
7104                    Log.i(TAG, "Skipping update of of idle app " + pkg.packageName);
7105                }
7106                continue;
7107            }
7108
7109            if (DEBUG_DEXOPT) {
7110                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7111            }
7112
7113            if (!isFirstBoot()) {
7114                try {
7115                    ActivityManagerNative.getDefault().showBootMessage(
7116                            mContext.getResources().getString(R.string.android_upgrading_apk,
7117                                    curr, total), true);
7118                } catch (RemoteException e) {
7119                }
7120            }
7121
7122            performDexOpt(pkg.packageName,
7123                    null /* instructionSet */,
7124                    false /* checkProfiles */,
7125                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7126                    false /* force */);
7127        }
7128    }
7129
7130    @Override
7131    public void notifyPackageUse(String packageName) {
7132        synchronized (mPackages) {
7133            PackageParser.Package p = mPackages.get(packageName);
7134            if (p == null) {
7135                return;
7136            }
7137            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
7138        }
7139    }
7140
7141    // TODO: this is not used nor needed. Delete it.
7142    @Override
7143    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7144        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7145                getFullCompilerFilter(), false /* force */);
7146    }
7147
7148    @Override
7149    public boolean performDexOpt(String packageName, String instructionSet,
7150            boolean checkProfiles, int compileReason, boolean force) {
7151        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7152                getCompilerFilterForReason(compileReason), force);
7153    }
7154
7155    @Override
7156    public boolean performDexOptMode(String packageName, String instructionSet,
7157            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7158        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7159                targetCompilerFilter, force);
7160    }
7161
7162    private boolean performDexOptTraced(String packageName, String instructionSet,
7163                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7164        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7165        try {
7166            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7167                    targetCompilerFilter, force);
7168        } finally {
7169            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7170        }
7171    }
7172
7173    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7174    // if the package can now be considered up to date for the given filter.
7175    private boolean performDexOptInternal(String packageName, String instructionSet,
7176                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7177        PackageParser.Package p;
7178        final String targetInstructionSet;
7179        synchronized (mPackages) {
7180            p = mPackages.get(packageName);
7181            if (p == null) {
7182                return false;
7183            }
7184            mPackageUsage.write(false);
7185
7186            targetInstructionSet = instructionSet != null ? instructionSet :
7187                    getPrimaryInstructionSet(p.applicationInfo);
7188        }
7189        long callingId = Binder.clearCallingIdentity();
7190        try {
7191            synchronized (mInstallLock) {
7192                final String[] instructionSets = new String[] { targetInstructionSet };
7193                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7194                        checkProfiles, targetCompilerFilter, force);
7195                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7196            }
7197        } finally {
7198            Binder.restoreCallingIdentity(callingId);
7199        }
7200    }
7201
7202    public ArraySet<String> getOptimizablePackages() {
7203        ArraySet<String> pkgs = new ArraySet<String>();
7204        synchronized (mPackages) {
7205            for (PackageParser.Package p : mPackages.values()) {
7206                if (PackageDexOptimizer.canOptimizePackage(p)) {
7207                    pkgs.add(p.packageName);
7208                }
7209            }
7210        }
7211        return pkgs;
7212    }
7213
7214    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7215            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7216            boolean force) {
7217        // Select the dex optimizer based on the force parameter.
7218        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7219        //       allocate an object here.
7220        PackageDexOptimizer pdo = force
7221                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7222                : mPackageDexOptimizer;
7223
7224        // Optimize all dependencies first. Note: we ignore the return value and march on
7225        // on errors.
7226        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7227        if (!deps.isEmpty()) {
7228            for (PackageParser.Package depPackage : deps) {
7229                // TODO: Analyze and investigate if we (should) profile libraries.
7230                // Currently this will do a full compilation of the library by default.
7231                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7232                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7233            }
7234        }
7235
7236        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7237    }
7238
7239    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7240        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7241            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7242            Set<String> collectedNames = new HashSet<>();
7243            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7244
7245            retValue.remove(p);
7246
7247            return retValue;
7248        } else {
7249            return Collections.emptyList();
7250        }
7251    }
7252
7253    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7254            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7255        if (!collectedNames.contains(p.packageName)) {
7256            collectedNames.add(p.packageName);
7257            collected.add(p);
7258
7259            if (p.usesLibraries != null) {
7260                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7261            }
7262            if (p.usesOptionalLibraries != null) {
7263                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7264                        collectedNames);
7265            }
7266        }
7267    }
7268
7269    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7270            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7271        for (String libName : libs) {
7272            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7273            if (libPkg != null) {
7274                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7275            }
7276        }
7277    }
7278
7279    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7280        synchronized (mPackages) {
7281            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7282            if (lib != null && lib.apk != null) {
7283                return mPackages.get(lib.apk);
7284            }
7285        }
7286        return null;
7287    }
7288
7289    public void shutdown() {
7290        mPackageUsage.write(true);
7291    }
7292
7293    @Override
7294    public void forceDexOpt(String packageName) {
7295        enforceSystemOrRoot("forceDexOpt");
7296
7297        PackageParser.Package pkg;
7298        synchronized (mPackages) {
7299            pkg = mPackages.get(packageName);
7300            if (pkg == null) {
7301                throw new IllegalArgumentException("Unknown package: " + packageName);
7302            }
7303        }
7304
7305        synchronized (mInstallLock) {
7306            final String[] instructionSets = new String[] {
7307                    getPrimaryInstructionSet(pkg.applicationInfo) };
7308
7309            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7310
7311            // Whoever is calling forceDexOpt wants a fully compiled package.
7312            // Don't use profiles since that may cause compilation to be skipped.
7313            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7314                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7315                    true /* force */);
7316
7317            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7318            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7319                throw new IllegalStateException("Failed to dexopt: " + res);
7320            }
7321        }
7322    }
7323
7324    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7325        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7326            Slog.w(TAG, "Unable to update from " + oldPkg.name
7327                    + " to " + newPkg.packageName
7328                    + ": old package not in system partition");
7329            return false;
7330        } else if (mPackages.get(oldPkg.name) != null) {
7331            Slog.w(TAG, "Unable to update from " + oldPkg.name
7332                    + " to " + newPkg.packageName
7333                    + ": old package still exists");
7334            return false;
7335        }
7336        return true;
7337    }
7338
7339    void removeCodePathLI(File codePath) {
7340        if (codePath.isDirectory()) {
7341            try {
7342                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7343            } catch (InstallerException e) {
7344                Slog.w(TAG, "Failed to remove code path", e);
7345            }
7346        } else {
7347            codePath.delete();
7348        }
7349    }
7350
7351    private int[] resolveUserIds(int userId) {
7352        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7353    }
7354
7355    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7356        if (pkg == null) {
7357            Slog.wtf(TAG, "Package was null!", new Throwable());
7358            return;
7359        }
7360        clearAppDataLeafLIF(pkg, userId, flags);
7361        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7362        for (int i = 0; i < childCount; i++) {
7363            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7364        }
7365    }
7366
7367    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7368        final PackageSetting ps;
7369        synchronized (mPackages) {
7370            ps = mSettings.mPackages.get(pkg.packageName);
7371        }
7372        for (int realUserId : resolveUserIds(userId)) {
7373            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7374            try {
7375                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7376                        ceDataInode);
7377            } catch (InstallerException e) {
7378                Slog.w(TAG, String.valueOf(e));
7379            }
7380        }
7381    }
7382
7383    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7384        if (pkg == null) {
7385            Slog.wtf(TAG, "Package was null!", new Throwable());
7386            return;
7387        }
7388        destroyAppDataLeafLIF(pkg, userId, flags);
7389        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7390        for (int i = 0; i < childCount; i++) {
7391            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7392        }
7393    }
7394
7395    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7396        final PackageSetting ps;
7397        synchronized (mPackages) {
7398            ps = mSettings.mPackages.get(pkg.packageName);
7399        }
7400        for (int realUserId : resolveUserIds(userId)) {
7401            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7402            try {
7403                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7404                        ceDataInode);
7405            } catch (InstallerException e) {
7406                Slog.w(TAG, String.valueOf(e));
7407            }
7408        }
7409    }
7410
7411    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7412        if (pkg == null) {
7413            Slog.wtf(TAG, "Package was null!", new Throwable());
7414            return;
7415        }
7416        destroyAppProfilesLeafLIF(pkg);
7417        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7418        for (int i = 0; i < childCount; i++) {
7419            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7420        }
7421    }
7422
7423    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7424        try {
7425            mInstaller.destroyAppProfiles(pkg.packageName);
7426        } catch (InstallerException e) {
7427            Slog.w(TAG, String.valueOf(e));
7428        }
7429    }
7430
7431    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7432        if (pkg == null) {
7433            Slog.wtf(TAG, "Package was null!", new Throwable());
7434            return;
7435        }
7436        clearAppProfilesLeafLIF(pkg);
7437        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7438        for (int i = 0; i < childCount; i++) {
7439            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7440        }
7441    }
7442
7443    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7444        try {
7445            mInstaller.clearAppProfiles(pkg.packageName);
7446        } catch (InstallerException e) {
7447            Slog.w(TAG, String.valueOf(e));
7448        }
7449    }
7450
7451    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7452            long lastUpdateTime) {
7453        // Set parent install/update time
7454        PackageSetting ps = (PackageSetting) pkg.mExtras;
7455        if (ps != null) {
7456            ps.firstInstallTime = firstInstallTime;
7457            ps.lastUpdateTime = lastUpdateTime;
7458        }
7459        // Set children install/update time
7460        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7461        for (int i = 0; i < childCount; i++) {
7462            PackageParser.Package childPkg = pkg.childPackages.get(i);
7463            ps = (PackageSetting) childPkg.mExtras;
7464            if (ps != null) {
7465                ps.firstInstallTime = firstInstallTime;
7466                ps.lastUpdateTime = lastUpdateTime;
7467            }
7468        }
7469    }
7470
7471    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7472            PackageParser.Package changingLib) {
7473        if (file.path != null) {
7474            usesLibraryFiles.add(file.path);
7475            return;
7476        }
7477        PackageParser.Package p = mPackages.get(file.apk);
7478        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7479            // If we are doing this while in the middle of updating a library apk,
7480            // then we need to make sure to use that new apk for determining the
7481            // dependencies here.  (We haven't yet finished committing the new apk
7482            // to the package manager state.)
7483            if (p == null || p.packageName.equals(changingLib.packageName)) {
7484                p = changingLib;
7485            }
7486        }
7487        if (p != null) {
7488            usesLibraryFiles.addAll(p.getAllCodePaths());
7489        }
7490    }
7491
7492    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7493            PackageParser.Package changingLib) throws PackageManagerException {
7494        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7495            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7496            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7497            for (int i=0; i<N; i++) {
7498                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7499                if (file == null) {
7500                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7501                            "Package " + pkg.packageName + " requires unavailable shared library "
7502                            + pkg.usesLibraries.get(i) + "; failing!");
7503                }
7504                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7505            }
7506            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7507            for (int i=0; i<N; i++) {
7508                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7509                if (file == null) {
7510                    Slog.w(TAG, "Package " + pkg.packageName
7511                            + " desires unavailable shared library "
7512                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7513                } else {
7514                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7515                }
7516            }
7517            N = usesLibraryFiles.size();
7518            if (N > 0) {
7519                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7520            } else {
7521                pkg.usesLibraryFiles = null;
7522            }
7523        }
7524    }
7525
7526    private static boolean hasString(List<String> list, List<String> which) {
7527        if (list == null) {
7528            return false;
7529        }
7530        for (int i=list.size()-1; i>=0; i--) {
7531            for (int j=which.size()-1; j>=0; j--) {
7532                if (which.get(j).equals(list.get(i))) {
7533                    return true;
7534                }
7535            }
7536        }
7537        return false;
7538    }
7539
7540    private void updateAllSharedLibrariesLPw() {
7541        for (PackageParser.Package pkg : mPackages.values()) {
7542            try {
7543                updateSharedLibrariesLPw(pkg, null);
7544            } catch (PackageManagerException e) {
7545                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7546            }
7547        }
7548    }
7549
7550    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7551            PackageParser.Package changingPkg) {
7552        ArrayList<PackageParser.Package> res = null;
7553        for (PackageParser.Package pkg : mPackages.values()) {
7554            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7555                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7556                if (res == null) {
7557                    res = new ArrayList<PackageParser.Package>();
7558                }
7559                res.add(pkg);
7560                try {
7561                    updateSharedLibrariesLPw(pkg, changingPkg);
7562                } catch (PackageManagerException e) {
7563                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7564                }
7565            }
7566        }
7567        return res;
7568    }
7569
7570    /**
7571     * Derive the value of the {@code cpuAbiOverride} based on the provided
7572     * value and an optional stored value from the package settings.
7573     */
7574    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7575        String cpuAbiOverride = null;
7576
7577        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7578            cpuAbiOverride = null;
7579        } else if (abiOverride != null) {
7580            cpuAbiOverride = abiOverride;
7581        } else if (settings != null) {
7582            cpuAbiOverride = settings.cpuAbiOverrideString;
7583        }
7584
7585        return cpuAbiOverride;
7586    }
7587
7588    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7589            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7590        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7591        // If the package has children and this is the first dive in the function
7592        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7593        // whether all packages (parent and children) would be successfully scanned
7594        // before the actual scan since scanning mutates internal state and we want
7595        // to atomically install the package and its children.
7596        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7597            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7598                scanFlags |= SCAN_CHECK_ONLY;
7599            }
7600        } else {
7601            scanFlags &= ~SCAN_CHECK_ONLY;
7602        }
7603
7604        final PackageParser.Package scannedPkg;
7605        try {
7606            // Scan the parent
7607            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7608            // Scan the children
7609            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7610            for (int i = 0; i < childCount; i++) {
7611                PackageParser.Package childPkg = pkg.childPackages.get(i);
7612                scanPackageLI(childPkg, parseFlags,
7613                        scanFlags, currentTime, user);
7614            }
7615        } finally {
7616            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7617        }
7618
7619        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7620            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7621        }
7622
7623        return scannedPkg;
7624    }
7625
7626    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7627            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7628        boolean success = false;
7629        try {
7630            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7631                    currentTime, user);
7632            success = true;
7633            return res;
7634        } finally {
7635            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7636                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7637                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7638                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7639                destroyAppProfilesLIF(pkg);
7640            }
7641        }
7642    }
7643
7644    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7645            int scanFlags, long currentTime, UserHandle user)
7646            throws PackageManagerException {
7647        final File scanFile = new File(pkg.codePath);
7648        if (pkg.applicationInfo.getCodePath() == null ||
7649                pkg.applicationInfo.getResourcePath() == null) {
7650            // Bail out. The resource and code paths haven't been set.
7651            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7652                    "Code and resource paths haven't been set correctly");
7653        }
7654
7655        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7656            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7657        } else {
7658            // Only allow system apps to be flagged as core apps.
7659            pkg.coreApp = false;
7660        }
7661
7662        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7663            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7664        }
7665
7666        if (mCustomResolverComponentName != null &&
7667                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7668            setUpCustomResolverActivity(pkg);
7669        }
7670
7671        if (pkg.packageName.equals("android")) {
7672            synchronized (mPackages) {
7673                if (mAndroidApplication != null) {
7674                    Slog.w(TAG, "*************************************************");
7675                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7676                    Slog.w(TAG, " file=" + scanFile);
7677                    Slog.w(TAG, "*************************************************");
7678                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7679                            "Core android package being redefined.  Skipping.");
7680                }
7681
7682                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7683                    // Set up information for our fall-back user intent resolution activity.
7684                    mPlatformPackage = pkg;
7685                    pkg.mVersionCode = mSdkVersion;
7686                    mAndroidApplication = pkg.applicationInfo;
7687
7688                    if (!mResolverReplaced) {
7689                        mResolveActivity.applicationInfo = mAndroidApplication;
7690                        mResolveActivity.name = ResolverActivity.class.getName();
7691                        mResolveActivity.packageName = mAndroidApplication.packageName;
7692                        mResolveActivity.processName = "system:ui";
7693                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7694                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7695                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7696                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7697                        mResolveActivity.exported = true;
7698                        mResolveActivity.enabled = true;
7699                        mResolveInfo.activityInfo = mResolveActivity;
7700                        mResolveInfo.priority = 0;
7701                        mResolveInfo.preferredOrder = 0;
7702                        mResolveInfo.match = 0;
7703                        mResolveComponentName = new ComponentName(
7704                                mAndroidApplication.packageName, mResolveActivity.name);
7705                    }
7706                }
7707            }
7708        }
7709
7710        if (DEBUG_PACKAGE_SCANNING) {
7711            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7712                Log.d(TAG, "Scanning package " + pkg.packageName);
7713        }
7714
7715        synchronized (mPackages) {
7716            if (mPackages.containsKey(pkg.packageName)
7717                    || mSharedLibraries.containsKey(pkg.packageName)) {
7718                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7719                        "Application package " + pkg.packageName
7720                                + " already installed.  Skipping duplicate.");
7721            }
7722
7723            // If we're only installing presumed-existing packages, require that the
7724            // scanned APK is both already known and at the path previously established
7725            // for it.  Previously unknown packages we pick up normally, but if we have an
7726            // a priori expectation about this package's install presence, enforce it.
7727            // With a singular exception for new system packages. When an OTA contains
7728            // a new system package, we allow the codepath to change from a system location
7729            // to the user-installed location. If we don't allow this change, any newer,
7730            // user-installed version of the application will be ignored.
7731            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7732                if (mExpectingBetter.containsKey(pkg.packageName)) {
7733                    logCriticalInfo(Log.WARN,
7734                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7735                } else {
7736                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7737                    if (known != null) {
7738                        if (DEBUG_PACKAGE_SCANNING) {
7739                            Log.d(TAG, "Examining " + pkg.codePath
7740                                    + " and requiring known paths " + known.codePathString
7741                                    + " & " + known.resourcePathString);
7742                        }
7743                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7744                                || !pkg.applicationInfo.getResourcePath().equals(
7745                                known.resourcePathString)) {
7746                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7747                                    "Application package " + pkg.packageName
7748                                            + " found at " + pkg.applicationInfo.getCodePath()
7749                                            + " but expected at " + known.codePathString
7750                                            + "; ignoring.");
7751                        }
7752                    }
7753                }
7754            }
7755        }
7756
7757        // Initialize package source and resource directories
7758        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7759        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7760
7761        SharedUserSetting suid = null;
7762        PackageSetting pkgSetting = null;
7763
7764        if (!isSystemApp(pkg)) {
7765            // Only system apps can use these features.
7766            pkg.mOriginalPackages = null;
7767            pkg.mRealPackage = null;
7768            pkg.mAdoptPermissions = null;
7769        }
7770
7771        // Getting the package setting may have a side-effect, so if we
7772        // are only checking if scan would succeed, stash a copy of the
7773        // old setting to restore at the end.
7774        PackageSetting nonMutatedPs = null;
7775
7776        // writer
7777        synchronized (mPackages) {
7778            if (pkg.mSharedUserId != null) {
7779                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7780                if (suid == null) {
7781                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7782                            "Creating application package " + pkg.packageName
7783                            + " for shared user failed");
7784                }
7785                if (DEBUG_PACKAGE_SCANNING) {
7786                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7787                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7788                                + "): packages=" + suid.packages);
7789                }
7790            }
7791
7792            // Check if we are renaming from an original package name.
7793            PackageSetting origPackage = null;
7794            String realName = null;
7795            if (pkg.mOriginalPackages != null) {
7796                // This package may need to be renamed to a previously
7797                // installed name.  Let's check on that...
7798                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7799                if (pkg.mOriginalPackages.contains(renamed)) {
7800                    // This package had originally been installed as the
7801                    // original name, and we have already taken care of
7802                    // transitioning to the new one.  Just update the new
7803                    // one to continue using the old name.
7804                    realName = pkg.mRealPackage;
7805                    if (!pkg.packageName.equals(renamed)) {
7806                        // Callers into this function may have already taken
7807                        // care of renaming the package; only do it here if
7808                        // it is not already done.
7809                        pkg.setPackageName(renamed);
7810                    }
7811
7812                } else {
7813                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7814                        if ((origPackage = mSettings.peekPackageLPr(
7815                                pkg.mOriginalPackages.get(i))) != null) {
7816                            // We do have the package already installed under its
7817                            // original name...  should we use it?
7818                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7819                                // New package is not compatible with original.
7820                                origPackage = null;
7821                                continue;
7822                            } else if (origPackage.sharedUser != null) {
7823                                // Make sure uid is compatible between packages.
7824                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7825                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7826                                            + " to " + pkg.packageName + ": old uid "
7827                                            + origPackage.sharedUser.name
7828                                            + " differs from " + pkg.mSharedUserId);
7829                                    origPackage = null;
7830                                    continue;
7831                                }
7832                            } else {
7833                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7834                                        + pkg.packageName + " to old name " + origPackage.name);
7835                            }
7836                            break;
7837                        }
7838                    }
7839                }
7840            }
7841
7842            if (mTransferedPackages.contains(pkg.packageName)) {
7843                Slog.w(TAG, "Package " + pkg.packageName
7844                        + " was transferred to another, but its .apk remains");
7845            }
7846
7847            // See comments in nonMutatedPs declaration
7848            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7849                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7850                if (foundPs != null) {
7851                    nonMutatedPs = new PackageSetting(foundPs);
7852                }
7853            }
7854
7855            // Just create the setting, don't add it yet. For already existing packages
7856            // the PkgSetting exists already and doesn't have to be created.
7857            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7858                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7859                    pkg.applicationInfo.primaryCpuAbi,
7860                    pkg.applicationInfo.secondaryCpuAbi,
7861                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7862                    user, false);
7863            if (pkgSetting == null) {
7864                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7865                        "Creating application package " + pkg.packageName + " failed");
7866            }
7867
7868            if (pkgSetting.origPackage != null) {
7869                // If we are first transitioning from an original package,
7870                // fix up the new package's name now.  We need to do this after
7871                // looking up the package under its new name, so getPackageLP
7872                // can take care of fiddling things correctly.
7873                pkg.setPackageName(origPackage.name);
7874
7875                // File a report about this.
7876                String msg = "New package " + pkgSetting.realName
7877                        + " renamed to replace old package " + pkgSetting.name;
7878                reportSettingsProblem(Log.WARN, msg);
7879
7880                // Make a note of it.
7881                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7882                    mTransferedPackages.add(origPackage.name);
7883                }
7884
7885                // No longer need to retain this.
7886                pkgSetting.origPackage = null;
7887            }
7888
7889            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7890                // Make a note of it.
7891                mTransferedPackages.add(pkg.packageName);
7892            }
7893
7894            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7895                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7896            }
7897
7898            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7899                // Check all shared libraries and map to their actual file path.
7900                // We only do this here for apps not on a system dir, because those
7901                // are the only ones that can fail an install due to this.  We
7902                // will take care of the system apps by updating all of their
7903                // library paths after the scan is done.
7904                updateSharedLibrariesLPw(pkg, null);
7905            }
7906
7907            if (mFoundPolicyFile) {
7908                SELinuxMMAC.assignSeinfoValue(pkg);
7909            }
7910
7911            pkg.applicationInfo.uid = pkgSetting.appId;
7912            pkg.mExtras = pkgSetting;
7913            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7914                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7915                    // We just determined the app is signed correctly, so bring
7916                    // over the latest parsed certs.
7917                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7918                } else {
7919                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7920                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7921                                "Package " + pkg.packageName + " upgrade keys do not match the "
7922                                + "previously installed version");
7923                    } else {
7924                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7925                        String msg = "System package " + pkg.packageName
7926                            + " signature changed; retaining data.";
7927                        reportSettingsProblem(Log.WARN, msg);
7928                    }
7929                }
7930            } else {
7931                try {
7932                    verifySignaturesLP(pkgSetting, pkg);
7933                    // We just determined the app is signed correctly, so bring
7934                    // over the latest parsed certs.
7935                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7936                } catch (PackageManagerException e) {
7937                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7938                        throw e;
7939                    }
7940                    // The signature has changed, but this package is in the system
7941                    // image...  let's recover!
7942                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7943                    // However...  if this package is part of a shared user, but it
7944                    // doesn't match the signature of the shared user, let's fail.
7945                    // What this means is that you can't change the signatures
7946                    // associated with an overall shared user, which doesn't seem all
7947                    // that unreasonable.
7948                    if (pkgSetting.sharedUser != null) {
7949                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7950                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7951                            throw new PackageManagerException(
7952                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7953                                            "Signature mismatch for shared user: "
7954                                            + pkgSetting.sharedUser);
7955                        }
7956                    }
7957                    // File a report about this.
7958                    String msg = "System package " + pkg.packageName
7959                        + " signature changed; retaining data.";
7960                    reportSettingsProblem(Log.WARN, msg);
7961                }
7962            }
7963            // Verify that this new package doesn't have any content providers
7964            // that conflict with existing packages.  Only do this if the
7965            // package isn't already installed, since we don't want to break
7966            // things that are installed.
7967            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7968                final int N = pkg.providers.size();
7969                int i;
7970                for (i=0; i<N; i++) {
7971                    PackageParser.Provider p = pkg.providers.get(i);
7972                    if (p.info.authority != null) {
7973                        String names[] = p.info.authority.split(";");
7974                        for (int j = 0; j < names.length; j++) {
7975                            if (mProvidersByAuthority.containsKey(names[j])) {
7976                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7977                                final String otherPackageName =
7978                                        ((other != null && other.getComponentName() != null) ?
7979                                                other.getComponentName().getPackageName() : "?");
7980                                throw new PackageManagerException(
7981                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7982                                                "Can't install because provider name " + names[j]
7983                                                + " (in package " + pkg.applicationInfo.packageName
7984                                                + ") is already used by " + otherPackageName);
7985                            }
7986                        }
7987                    }
7988                }
7989            }
7990
7991            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7992                // This package wants to adopt ownership of permissions from
7993                // another package.
7994                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7995                    final String origName = pkg.mAdoptPermissions.get(i);
7996                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7997                    if (orig != null) {
7998                        if (verifyPackageUpdateLPr(orig, pkg)) {
7999                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8000                                    + pkg.packageName);
8001                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8002                        }
8003                    }
8004                }
8005            }
8006        }
8007
8008        final String pkgName = pkg.packageName;
8009
8010        final long scanFileTime = scanFile.lastModified();
8011        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8012        pkg.applicationInfo.processName = fixProcessName(
8013                pkg.applicationInfo.packageName,
8014                pkg.applicationInfo.processName,
8015                pkg.applicationInfo.uid);
8016
8017        if (pkg != mPlatformPackage) {
8018            // Get all of our default paths setup
8019            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8020        }
8021
8022        final String path = scanFile.getPath();
8023        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8024
8025        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8026            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8027
8028            // Some system apps still use directory structure for native libraries
8029            // in which case we might end up not detecting abi solely based on apk
8030            // structure. Try to detect abi based on directory structure.
8031            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8032                    pkg.applicationInfo.primaryCpuAbi == null) {
8033                setBundledAppAbisAndRoots(pkg, pkgSetting);
8034                setNativeLibraryPaths(pkg);
8035            }
8036
8037        } else {
8038            if ((scanFlags & SCAN_MOVE) != 0) {
8039                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8040                // but we already have this packages package info in the PackageSetting. We just
8041                // use that and derive the native library path based on the new codepath.
8042                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8043                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8044            }
8045
8046            // Set native library paths again. For moves, the path will be updated based on the
8047            // ABIs we've determined above. For non-moves, the path will be updated based on the
8048            // ABIs we determined during compilation, but the path will depend on the final
8049            // package path (after the rename away from the stage path).
8050            setNativeLibraryPaths(pkg);
8051        }
8052
8053        // This is a special case for the "system" package, where the ABI is
8054        // dictated by the zygote configuration (and init.rc). We should keep track
8055        // of this ABI so that we can deal with "normal" applications that run under
8056        // the same UID correctly.
8057        if (mPlatformPackage == pkg) {
8058            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8059                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8060        }
8061
8062        // If there's a mismatch between the abi-override in the package setting
8063        // and the abiOverride specified for the install. Warn about this because we
8064        // would've already compiled the app without taking the package setting into
8065        // account.
8066        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8067            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8068                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8069                        " for package " + pkg.packageName);
8070            }
8071        }
8072
8073        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8074        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8075        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8076
8077        // Copy the derived override back to the parsed package, so that we can
8078        // update the package settings accordingly.
8079        pkg.cpuAbiOverride = cpuAbiOverride;
8080
8081        if (DEBUG_ABI_SELECTION) {
8082            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8083                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8084                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8085        }
8086
8087        // Push the derived path down into PackageSettings so we know what to
8088        // clean up at uninstall time.
8089        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8090
8091        if (DEBUG_ABI_SELECTION) {
8092            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8093                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8094                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8095        }
8096
8097        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8098            // We don't do this here during boot because we can do it all
8099            // at once after scanning all existing packages.
8100            //
8101            // We also do this *before* we perform dexopt on this package, so that
8102            // we can avoid redundant dexopts, and also to make sure we've got the
8103            // code and package path correct.
8104            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8105                    pkg, true /* boot complete */);
8106        }
8107
8108        if (mFactoryTest && pkg.requestedPermissions.contains(
8109                android.Manifest.permission.FACTORY_TEST)) {
8110            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8111        }
8112
8113        ArrayList<PackageParser.Package> clientLibPkgs = null;
8114
8115        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8116            if (nonMutatedPs != null) {
8117                synchronized (mPackages) {
8118                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8119                }
8120            }
8121            return pkg;
8122        }
8123
8124        // Only privileged apps and updated privileged apps can add child packages.
8125        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8126            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
8127                throw new PackageManagerException("Only privileged apps and updated "
8128                        + "privileged apps can add child packages. Ignoring package "
8129                        + pkg.packageName);
8130            }
8131            final int childCount = pkg.childPackages.size();
8132            for (int i = 0; i < childCount; i++) {
8133                PackageParser.Package childPkg = pkg.childPackages.get(i);
8134                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8135                        childPkg.packageName)) {
8136                    throw new PackageManagerException("Cannot override a child package of "
8137                            + "another disabled system app. Ignoring package " + pkg.packageName);
8138                }
8139            }
8140        }
8141
8142        // writer
8143        synchronized (mPackages) {
8144            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8145                // Only system apps can add new shared libraries.
8146                if (pkg.libraryNames != null) {
8147                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8148                        String name = pkg.libraryNames.get(i);
8149                        boolean allowed = false;
8150                        if (pkg.isUpdatedSystemApp()) {
8151                            // New library entries can only be added through the
8152                            // system image.  This is important to get rid of a lot
8153                            // of nasty edge cases: for example if we allowed a non-
8154                            // system update of the app to add a library, then uninstalling
8155                            // the update would make the library go away, and assumptions
8156                            // we made such as through app install filtering would now
8157                            // have allowed apps on the device which aren't compatible
8158                            // with it.  Better to just have the restriction here, be
8159                            // conservative, and create many fewer cases that can negatively
8160                            // impact the user experience.
8161                            final PackageSetting sysPs = mSettings
8162                                    .getDisabledSystemPkgLPr(pkg.packageName);
8163                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8164                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8165                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8166                                        allowed = true;
8167                                        break;
8168                                    }
8169                                }
8170                            }
8171                        } else {
8172                            allowed = true;
8173                        }
8174                        if (allowed) {
8175                            if (!mSharedLibraries.containsKey(name)) {
8176                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8177                            } else if (!name.equals(pkg.packageName)) {
8178                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8179                                        + name + " already exists; skipping");
8180                            }
8181                        } else {
8182                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8183                                    + name + " that is not declared on system image; skipping");
8184                        }
8185                    }
8186                    if ((scanFlags & SCAN_BOOTING) == 0) {
8187                        // If we are not booting, we need to update any applications
8188                        // that are clients of our shared library.  If we are booting,
8189                        // this will all be done once the scan is complete.
8190                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8191                    }
8192                }
8193            }
8194        }
8195
8196        if ((scanFlags & SCAN_BOOTING) != 0) {
8197            // No apps can run during boot scan, so they don't need to be frozen
8198        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8199            // Caller asked to not kill app, so it's probably not frozen
8200        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8201            // Caller asked us to ignore frozen check for some reason; they
8202            // probably didn't know the package name
8203        } else {
8204            // We're doing major surgery on this package, so it better be frozen
8205            // right now to keep it from launching
8206            checkPackageFrozen(pkgName);
8207        }
8208
8209        // Also need to kill any apps that are dependent on the library.
8210        if (clientLibPkgs != null) {
8211            for (int i=0; i<clientLibPkgs.size(); i++) {
8212                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8213                killApplication(clientPkg.applicationInfo.packageName,
8214                        clientPkg.applicationInfo.uid, "update lib");
8215            }
8216        }
8217
8218        // Make sure we're not adding any bogus keyset info
8219        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8220        ksms.assertScannedPackageValid(pkg);
8221
8222        // writer
8223        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8224
8225        boolean createIdmapFailed = false;
8226        synchronized (mPackages) {
8227            // We don't expect installation to fail beyond this point
8228
8229            // Add the new setting to mSettings
8230            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8231            // Add the new setting to mPackages
8232            mPackages.put(pkg.applicationInfo.packageName, pkg);
8233            // Make sure we don't accidentally delete its data.
8234            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8235            while (iter.hasNext()) {
8236                PackageCleanItem item = iter.next();
8237                if (pkgName.equals(item.packageName)) {
8238                    iter.remove();
8239                }
8240            }
8241
8242            // Take care of first install / last update times.
8243            if (currentTime != 0) {
8244                if (pkgSetting.firstInstallTime == 0) {
8245                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8246                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8247                    pkgSetting.lastUpdateTime = currentTime;
8248                }
8249            } else if (pkgSetting.firstInstallTime == 0) {
8250                // We need *something*.  Take time time stamp of the file.
8251                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8252            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8253                if (scanFileTime != pkgSetting.timeStamp) {
8254                    // A package on the system image has changed; consider this
8255                    // to be an update.
8256                    pkgSetting.lastUpdateTime = scanFileTime;
8257                }
8258            }
8259
8260            // Add the package's KeySets to the global KeySetManagerService
8261            ksms.addScannedPackageLPw(pkg);
8262
8263            int N = pkg.providers.size();
8264            StringBuilder r = null;
8265            int i;
8266            for (i=0; i<N; i++) {
8267                PackageParser.Provider p = pkg.providers.get(i);
8268                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8269                        p.info.processName, pkg.applicationInfo.uid);
8270                mProviders.addProvider(p);
8271                p.syncable = p.info.isSyncable;
8272                if (p.info.authority != null) {
8273                    String names[] = p.info.authority.split(";");
8274                    p.info.authority = null;
8275                    for (int j = 0; j < names.length; j++) {
8276                        if (j == 1 && p.syncable) {
8277                            // We only want the first authority for a provider to possibly be
8278                            // syncable, so if we already added this provider using a different
8279                            // authority clear the syncable flag. We copy the provider before
8280                            // changing it because the mProviders object contains a reference
8281                            // to a provider that we don't want to change.
8282                            // Only do this for the second authority since the resulting provider
8283                            // object can be the same for all future authorities for this provider.
8284                            p = new PackageParser.Provider(p);
8285                            p.syncable = false;
8286                        }
8287                        if (!mProvidersByAuthority.containsKey(names[j])) {
8288                            mProvidersByAuthority.put(names[j], p);
8289                            if (p.info.authority == null) {
8290                                p.info.authority = names[j];
8291                            } else {
8292                                p.info.authority = p.info.authority + ";" + names[j];
8293                            }
8294                            if (DEBUG_PACKAGE_SCANNING) {
8295                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8296                                    Log.d(TAG, "Registered content provider: " + names[j]
8297                                            + ", className = " + p.info.name + ", isSyncable = "
8298                                            + p.info.isSyncable);
8299                            }
8300                        } else {
8301                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8302                            Slog.w(TAG, "Skipping provider name " + names[j] +
8303                                    " (in package " + pkg.applicationInfo.packageName +
8304                                    "): name already used by "
8305                                    + ((other != null && other.getComponentName() != null)
8306                                            ? other.getComponentName().getPackageName() : "?"));
8307                        }
8308                    }
8309                }
8310                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8311                    if (r == null) {
8312                        r = new StringBuilder(256);
8313                    } else {
8314                        r.append(' ');
8315                    }
8316                    r.append(p.info.name);
8317                }
8318            }
8319            if (r != null) {
8320                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8321            }
8322
8323            N = pkg.services.size();
8324            r = null;
8325            for (i=0; i<N; i++) {
8326                PackageParser.Service s = pkg.services.get(i);
8327                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8328                        s.info.processName, pkg.applicationInfo.uid);
8329                mServices.addService(s);
8330                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8331                    if (r == null) {
8332                        r = new StringBuilder(256);
8333                    } else {
8334                        r.append(' ');
8335                    }
8336                    r.append(s.info.name);
8337                }
8338            }
8339            if (r != null) {
8340                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8341            }
8342
8343            N = pkg.receivers.size();
8344            r = null;
8345            for (i=0; i<N; i++) {
8346                PackageParser.Activity a = pkg.receivers.get(i);
8347                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8348                        a.info.processName, pkg.applicationInfo.uid);
8349                mReceivers.addActivity(a, "receiver");
8350                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8351                    if (r == null) {
8352                        r = new StringBuilder(256);
8353                    } else {
8354                        r.append(' ');
8355                    }
8356                    r.append(a.info.name);
8357                }
8358            }
8359            if (r != null) {
8360                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8361            }
8362
8363            N = pkg.activities.size();
8364            r = null;
8365            for (i=0; i<N; i++) {
8366                PackageParser.Activity a = pkg.activities.get(i);
8367                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8368                        a.info.processName, pkg.applicationInfo.uid);
8369                mActivities.addActivity(a, "activity");
8370                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8371                    if (r == null) {
8372                        r = new StringBuilder(256);
8373                    } else {
8374                        r.append(' ');
8375                    }
8376                    r.append(a.info.name);
8377                }
8378            }
8379            if (r != null) {
8380                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8381            }
8382
8383            N = pkg.permissionGroups.size();
8384            r = null;
8385            for (i=0; i<N; i++) {
8386                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8387                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8388                if (cur == null) {
8389                    mPermissionGroups.put(pg.info.name, pg);
8390                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8391                        if (r == null) {
8392                            r = new StringBuilder(256);
8393                        } else {
8394                            r.append(' ');
8395                        }
8396                        r.append(pg.info.name);
8397                    }
8398                } else {
8399                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8400                            + pg.info.packageName + " ignored: original from "
8401                            + cur.info.packageName);
8402                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8403                        if (r == null) {
8404                            r = new StringBuilder(256);
8405                        } else {
8406                            r.append(' ');
8407                        }
8408                        r.append("DUP:");
8409                        r.append(pg.info.name);
8410                    }
8411                }
8412            }
8413            if (r != null) {
8414                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8415            }
8416
8417            N = pkg.permissions.size();
8418            r = null;
8419            for (i=0; i<N; i++) {
8420                PackageParser.Permission p = pkg.permissions.get(i);
8421
8422                // Assume by default that we did not install this permission into the system.
8423                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8424
8425                // Now that permission groups have a special meaning, we ignore permission
8426                // groups for legacy apps to prevent unexpected behavior. In particular,
8427                // permissions for one app being granted to someone just becase they happen
8428                // to be in a group defined by another app (before this had no implications).
8429                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8430                    p.group = mPermissionGroups.get(p.info.group);
8431                    // Warn for a permission in an unknown group.
8432                    if (p.info.group != null && p.group == null) {
8433                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8434                                + p.info.packageName + " in an unknown group " + p.info.group);
8435                    }
8436                }
8437
8438                ArrayMap<String, BasePermission> permissionMap =
8439                        p.tree ? mSettings.mPermissionTrees
8440                                : mSettings.mPermissions;
8441                BasePermission bp = permissionMap.get(p.info.name);
8442
8443                // Allow system apps to redefine non-system permissions
8444                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8445                    final boolean currentOwnerIsSystem = (bp.perm != null
8446                            && isSystemApp(bp.perm.owner));
8447                    if (isSystemApp(p.owner)) {
8448                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8449                            // It's a built-in permission and no owner, take ownership now
8450                            bp.packageSetting = pkgSetting;
8451                            bp.perm = p;
8452                            bp.uid = pkg.applicationInfo.uid;
8453                            bp.sourcePackage = p.info.packageName;
8454                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8455                        } else if (!currentOwnerIsSystem) {
8456                            String msg = "New decl " + p.owner + " of permission  "
8457                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8458                            reportSettingsProblem(Log.WARN, msg);
8459                            bp = null;
8460                        }
8461                    }
8462                }
8463
8464                if (bp == null) {
8465                    bp = new BasePermission(p.info.name, p.info.packageName,
8466                            BasePermission.TYPE_NORMAL);
8467                    permissionMap.put(p.info.name, bp);
8468                }
8469
8470                if (bp.perm == null) {
8471                    if (bp.sourcePackage == null
8472                            || bp.sourcePackage.equals(p.info.packageName)) {
8473                        BasePermission tree = findPermissionTreeLP(p.info.name);
8474                        if (tree == null
8475                                || tree.sourcePackage.equals(p.info.packageName)) {
8476                            bp.packageSetting = pkgSetting;
8477                            bp.perm = p;
8478                            bp.uid = pkg.applicationInfo.uid;
8479                            bp.sourcePackage = p.info.packageName;
8480                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8481                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8482                                if (r == null) {
8483                                    r = new StringBuilder(256);
8484                                } else {
8485                                    r.append(' ');
8486                                }
8487                                r.append(p.info.name);
8488                            }
8489                        } else {
8490                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8491                                    + p.info.packageName + " ignored: base tree "
8492                                    + tree.name + " is from package "
8493                                    + tree.sourcePackage);
8494                        }
8495                    } else {
8496                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8497                                + p.info.packageName + " ignored: original from "
8498                                + bp.sourcePackage);
8499                    }
8500                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8501                    if (r == null) {
8502                        r = new StringBuilder(256);
8503                    } else {
8504                        r.append(' ');
8505                    }
8506                    r.append("DUP:");
8507                    r.append(p.info.name);
8508                }
8509                if (bp.perm == p) {
8510                    bp.protectionLevel = p.info.protectionLevel;
8511                }
8512            }
8513
8514            if (r != null) {
8515                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8516            }
8517
8518            N = pkg.instrumentation.size();
8519            r = null;
8520            for (i=0; i<N; i++) {
8521                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8522                a.info.packageName = pkg.applicationInfo.packageName;
8523                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8524                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8525                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8526                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8527                a.info.dataDir = pkg.applicationInfo.dataDir;
8528                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8529                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8530
8531                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8532                // need other information about the application, like the ABI and what not ?
8533                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8534                mInstrumentation.put(a.getComponentName(), a);
8535                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8536                    if (r == null) {
8537                        r = new StringBuilder(256);
8538                    } else {
8539                        r.append(' ');
8540                    }
8541                    r.append(a.info.name);
8542                }
8543            }
8544            if (r != null) {
8545                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8546            }
8547
8548            if (pkg.protectedBroadcasts != null) {
8549                N = pkg.protectedBroadcasts.size();
8550                for (i=0; i<N; i++) {
8551                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8552                }
8553            }
8554
8555            pkgSetting.setTimeStamp(scanFileTime);
8556
8557            // Create idmap files for pairs of (packages, overlay packages).
8558            // Note: "android", ie framework-res.apk, is handled by native layers.
8559            if (pkg.mOverlayTarget != null) {
8560                // This is an overlay package.
8561                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8562                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8563                        mOverlays.put(pkg.mOverlayTarget,
8564                                new ArrayMap<String, PackageParser.Package>());
8565                    }
8566                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8567                    map.put(pkg.packageName, pkg);
8568                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8569                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8570                        createIdmapFailed = true;
8571                    }
8572                }
8573            } else if (mOverlays.containsKey(pkg.packageName) &&
8574                    !pkg.packageName.equals("android")) {
8575                // This is a regular package, with one or more known overlay packages.
8576                createIdmapsForPackageLI(pkg);
8577            }
8578        }
8579
8580        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8581
8582        if (createIdmapFailed) {
8583            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8584                    "scanPackageLI failed to createIdmap");
8585        }
8586        return pkg;
8587    }
8588
8589    /**
8590     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8591     * is derived purely on the basis of the contents of {@code scanFile} and
8592     * {@code cpuAbiOverride}.
8593     *
8594     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8595     */
8596    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8597                                 String cpuAbiOverride, boolean extractLibs)
8598            throws PackageManagerException {
8599        // TODO: We can probably be smarter about this stuff. For installed apps,
8600        // we can calculate this information at install time once and for all. For
8601        // system apps, we can probably assume that this information doesn't change
8602        // after the first boot scan. As things stand, we do lots of unnecessary work.
8603
8604        // Give ourselves some initial paths; we'll come back for another
8605        // pass once we've determined ABI below.
8606        setNativeLibraryPaths(pkg);
8607
8608        // We would never need to extract libs for forward-locked and external packages,
8609        // since the container service will do it for us. We shouldn't attempt to
8610        // extract libs from system app when it was not updated.
8611        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8612                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8613            extractLibs = false;
8614        }
8615
8616        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8617        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8618
8619        NativeLibraryHelper.Handle handle = null;
8620        try {
8621            handle = NativeLibraryHelper.Handle.create(pkg);
8622            // TODO(multiArch): This can be null for apps that didn't go through the
8623            // usual installation process. We can calculate it again, like we
8624            // do during install time.
8625            //
8626            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8627            // unnecessary.
8628            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8629
8630            // Null out the abis so that they can be recalculated.
8631            pkg.applicationInfo.primaryCpuAbi = null;
8632            pkg.applicationInfo.secondaryCpuAbi = null;
8633            if (isMultiArch(pkg.applicationInfo)) {
8634                // Warn if we've set an abiOverride for multi-lib packages..
8635                // By definition, we need to copy both 32 and 64 bit libraries for
8636                // such packages.
8637                if (pkg.cpuAbiOverride != null
8638                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8639                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8640                }
8641
8642                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8643                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8644                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8645                    if (extractLibs) {
8646                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8647                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8648                                useIsaSpecificSubdirs);
8649                    } else {
8650                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8651                    }
8652                }
8653
8654                maybeThrowExceptionForMultiArchCopy(
8655                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8656
8657                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8658                    if (extractLibs) {
8659                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8660                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8661                                useIsaSpecificSubdirs);
8662                    } else {
8663                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8664                    }
8665                }
8666
8667                maybeThrowExceptionForMultiArchCopy(
8668                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8669
8670                if (abi64 >= 0) {
8671                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8672                }
8673
8674                if (abi32 >= 0) {
8675                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8676                    if (abi64 >= 0) {
8677                        if (pkg.use32bitAbi) {
8678                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8679                            pkg.applicationInfo.primaryCpuAbi = abi;
8680                        } else {
8681                            pkg.applicationInfo.secondaryCpuAbi = abi;
8682                        }
8683                    } else {
8684                        pkg.applicationInfo.primaryCpuAbi = abi;
8685                    }
8686                }
8687
8688            } else {
8689                String[] abiList = (cpuAbiOverride != null) ?
8690                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8691
8692                // Enable gross and lame hacks for apps that are built with old
8693                // SDK tools. We must scan their APKs for renderscript bitcode and
8694                // not launch them if it's present. Don't bother checking on devices
8695                // that don't have 64 bit support.
8696                boolean needsRenderScriptOverride = false;
8697                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8698                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8699                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8700                    needsRenderScriptOverride = true;
8701                }
8702
8703                final int copyRet;
8704                if (extractLibs) {
8705                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8706                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8707                } else {
8708                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8709                }
8710
8711                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8712                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8713                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8714                }
8715
8716                if (copyRet >= 0) {
8717                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8718                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8719                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8720                } else if (needsRenderScriptOverride) {
8721                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8722                }
8723            }
8724        } catch (IOException ioe) {
8725            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8726        } finally {
8727            IoUtils.closeQuietly(handle);
8728        }
8729
8730        // Now that we've calculated the ABIs and determined if it's an internal app,
8731        // we will go ahead and populate the nativeLibraryPath.
8732        setNativeLibraryPaths(pkg);
8733    }
8734
8735    /**
8736     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8737     * i.e, so that all packages can be run inside a single process if required.
8738     *
8739     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8740     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8741     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8742     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8743     * updating a package that belongs to a shared user.
8744     *
8745     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8746     * adds unnecessary complexity.
8747     */
8748    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8749            PackageParser.Package scannedPackage, boolean bootComplete) {
8750        String requiredInstructionSet = null;
8751        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8752            requiredInstructionSet = VMRuntime.getInstructionSet(
8753                     scannedPackage.applicationInfo.primaryCpuAbi);
8754        }
8755
8756        PackageSetting requirer = null;
8757        for (PackageSetting ps : packagesForUser) {
8758            // If packagesForUser contains scannedPackage, we skip it. This will happen
8759            // when scannedPackage is an update of an existing package. Without this check,
8760            // we will never be able to change the ABI of any package belonging to a shared
8761            // user, even if it's compatible with other packages.
8762            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8763                if (ps.primaryCpuAbiString == null) {
8764                    continue;
8765                }
8766
8767                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8768                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8769                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8770                    // this but there's not much we can do.
8771                    String errorMessage = "Instruction set mismatch, "
8772                            + ((requirer == null) ? "[caller]" : requirer)
8773                            + " requires " + requiredInstructionSet + " whereas " + ps
8774                            + " requires " + instructionSet;
8775                    Slog.w(TAG, errorMessage);
8776                }
8777
8778                if (requiredInstructionSet == null) {
8779                    requiredInstructionSet = instructionSet;
8780                    requirer = ps;
8781                }
8782            }
8783        }
8784
8785        if (requiredInstructionSet != null) {
8786            String adjustedAbi;
8787            if (requirer != null) {
8788                // requirer != null implies that either scannedPackage was null or that scannedPackage
8789                // did not require an ABI, in which case we have to adjust scannedPackage to match
8790                // the ABI of the set (which is the same as requirer's ABI)
8791                adjustedAbi = requirer.primaryCpuAbiString;
8792                if (scannedPackage != null) {
8793                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8794                }
8795            } else {
8796                // requirer == null implies that we're updating all ABIs in the set to
8797                // match scannedPackage.
8798                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8799            }
8800
8801            for (PackageSetting ps : packagesForUser) {
8802                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8803                    if (ps.primaryCpuAbiString != null) {
8804                        continue;
8805                    }
8806
8807                    ps.primaryCpuAbiString = adjustedAbi;
8808                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8809                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8810                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8811                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8812                                + " (requirer="
8813                                + (requirer == null ? "null" : requirer.pkg.packageName)
8814                                + ", scannedPackage="
8815                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8816                                + ")");
8817                        try {
8818                            mInstaller.rmdex(ps.codePathString,
8819                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8820                        } catch (InstallerException ignored) {
8821                        }
8822                    }
8823                }
8824            }
8825        }
8826    }
8827
8828    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8829        synchronized (mPackages) {
8830            mResolverReplaced = true;
8831            // Set up information for custom user intent resolution activity.
8832            mResolveActivity.applicationInfo = pkg.applicationInfo;
8833            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8834            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8835            mResolveActivity.processName = pkg.applicationInfo.packageName;
8836            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8837            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8838                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8839            mResolveActivity.theme = 0;
8840            mResolveActivity.exported = true;
8841            mResolveActivity.enabled = true;
8842            mResolveInfo.activityInfo = mResolveActivity;
8843            mResolveInfo.priority = 0;
8844            mResolveInfo.preferredOrder = 0;
8845            mResolveInfo.match = 0;
8846            mResolveComponentName = mCustomResolverComponentName;
8847            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8848                    mResolveComponentName);
8849        }
8850    }
8851
8852    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8853        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8854
8855        // Set up information for ephemeral installer activity
8856        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8857        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8858        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8859        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8860        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8861        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8862                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8863        mEphemeralInstallerActivity.theme = 0;
8864        mEphemeralInstallerActivity.exported = true;
8865        mEphemeralInstallerActivity.enabled = true;
8866        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8867        mEphemeralInstallerInfo.priority = 0;
8868        mEphemeralInstallerInfo.preferredOrder = 0;
8869        mEphemeralInstallerInfo.match = 0;
8870
8871        if (DEBUG_EPHEMERAL) {
8872            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8873        }
8874    }
8875
8876    private static String calculateBundledApkRoot(final String codePathString) {
8877        final File codePath = new File(codePathString);
8878        final File codeRoot;
8879        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8880            codeRoot = Environment.getRootDirectory();
8881        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8882            codeRoot = Environment.getOemDirectory();
8883        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8884            codeRoot = Environment.getVendorDirectory();
8885        } else {
8886            // Unrecognized code path; take its top real segment as the apk root:
8887            // e.g. /something/app/blah.apk => /something
8888            try {
8889                File f = codePath.getCanonicalFile();
8890                File parent = f.getParentFile();    // non-null because codePath is a file
8891                File tmp;
8892                while ((tmp = parent.getParentFile()) != null) {
8893                    f = parent;
8894                    parent = tmp;
8895                }
8896                codeRoot = f;
8897                Slog.w(TAG, "Unrecognized code path "
8898                        + codePath + " - using " + codeRoot);
8899            } catch (IOException e) {
8900                // Can't canonicalize the code path -- shenanigans?
8901                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8902                return Environment.getRootDirectory().getPath();
8903            }
8904        }
8905        return codeRoot.getPath();
8906    }
8907
8908    /**
8909     * Derive and set the location of native libraries for the given package,
8910     * which varies depending on where and how the package was installed.
8911     */
8912    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8913        final ApplicationInfo info = pkg.applicationInfo;
8914        final String codePath = pkg.codePath;
8915        final File codeFile = new File(codePath);
8916        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8917        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8918
8919        info.nativeLibraryRootDir = null;
8920        info.nativeLibraryRootRequiresIsa = false;
8921        info.nativeLibraryDir = null;
8922        info.secondaryNativeLibraryDir = null;
8923
8924        if (isApkFile(codeFile)) {
8925            // Monolithic install
8926            if (bundledApp) {
8927                // If "/system/lib64/apkname" exists, assume that is the per-package
8928                // native library directory to use; otherwise use "/system/lib/apkname".
8929                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8930                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8931                        getPrimaryInstructionSet(info));
8932
8933                // This is a bundled system app so choose the path based on the ABI.
8934                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8935                // is just the default path.
8936                final String apkName = deriveCodePathName(codePath);
8937                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8938                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8939                        apkName).getAbsolutePath();
8940
8941                if (info.secondaryCpuAbi != null) {
8942                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8943                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8944                            secondaryLibDir, apkName).getAbsolutePath();
8945                }
8946            } else if (asecApp) {
8947                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8948                        .getAbsolutePath();
8949            } else {
8950                final String apkName = deriveCodePathName(codePath);
8951                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8952                        .getAbsolutePath();
8953            }
8954
8955            info.nativeLibraryRootRequiresIsa = false;
8956            info.nativeLibraryDir = info.nativeLibraryRootDir;
8957        } else {
8958            // Cluster install
8959            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8960            info.nativeLibraryRootRequiresIsa = true;
8961
8962            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8963                    getPrimaryInstructionSet(info)).getAbsolutePath();
8964
8965            if (info.secondaryCpuAbi != null) {
8966                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8967                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8968            }
8969        }
8970    }
8971
8972    /**
8973     * Calculate the abis and roots for a bundled app. These can uniquely
8974     * be determined from the contents of the system partition, i.e whether
8975     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8976     * of this information, and instead assume that the system was built
8977     * sensibly.
8978     */
8979    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8980                                           PackageSetting pkgSetting) {
8981        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8982
8983        // If "/system/lib64/apkname" exists, assume that is the per-package
8984        // native library directory to use; otherwise use "/system/lib/apkname".
8985        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8986        setBundledAppAbi(pkg, apkRoot, apkName);
8987        // pkgSetting might be null during rescan following uninstall of updates
8988        // to a bundled app, so accommodate that possibility.  The settings in
8989        // that case will be established later from the parsed package.
8990        //
8991        // If the settings aren't null, sync them up with what we've just derived.
8992        // note that apkRoot isn't stored in the package settings.
8993        if (pkgSetting != null) {
8994            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8995            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8996        }
8997    }
8998
8999    /**
9000     * Deduces the ABI of a bundled app and sets the relevant fields on the
9001     * parsed pkg object.
9002     *
9003     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9004     *        under which system libraries are installed.
9005     * @param apkName the name of the installed package.
9006     */
9007    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9008        final File codeFile = new File(pkg.codePath);
9009
9010        final boolean has64BitLibs;
9011        final boolean has32BitLibs;
9012        if (isApkFile(codeFile)) {
9013            // Monolithic install
9014            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9015            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9016        } else {
9017            // Cluster install
9018            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9019            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9020                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9021                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9022                has64BitLibs = (new File(rootDir, isa)).exists();
9023            } else {
9024                has64BitLibs = false;
9025            }
9026            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9027                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9028                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9029                has32BitLibs = (new File(rootDir, isa)).exists();
9030            } else {
9031                has32BitLibs = false;
9032            }
9033        }
9034
9035        if (has64BitLibs && !has32BitLibs) {
9036            // The package has 64 bit libs, but not 32 bit libs. Its primary
9037            // ABI should be 64 bit. We can safely assume here that the bundled
9038            // native libraries correspond to the most preferred ABI in the list.
9039
9040            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9041            pkg.applicationInfo.secondaryCpuAbi = null;
9042        } else if (has32BitLibs && !has64BitLibs) {
9043            // The package has 32 bit libs but not 64 bit libs. Its primary
9044            // ABI should be 32 bit.
9045
9046            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9047            pkg.applicationInfo.secondaryCpuAbi = null;
9048        } else if (has32BitLibs && has64BitLibs) {
9049            // The application has both 64 and 32 bit bundled libraries. We check
9050            // here that the app declares multiArch support, and warn if it doesn't.
9051            //
9052            // We will be lenient here and record both ABIs. The primary will be the
9053            // ABI that's higher on the list, i.e, a device that's configured to prefer
9054            // 64 bit apps will see a 64 bit primary ABI,
9055
9056            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9057                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9058            }
9059
9060            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9061                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9062                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9063            } else {
9064                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9065                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9066            }
9067        } else {
9068            pkg.applicationInfo.primaryCpuAbi = null;
9069            pkg.applicationInfo.secondaryCpuAbi = null;
9070        }
9071    }
9072
9073    private void killApplication(String pkgName, int appId, String reason) {
9074        // Request the ActivityManager to kill the process(only for existing packages)
9075        // so that we do not end up in a confused state while the user is still using the older
9076        // version of the application while the new one gets installed.
9077        final long token = Binder.clearCallingIdentity();
9078        try {
9079            IActivityManager am = ActivityManagerNative.getDefault();
9080            if (am != null) {
9081                try {
9082                    am.killApplicationWithAppId(pkgName, appId, reason);
9083                } catch (RemoteException e) {
9084                }
9085            }
9086        } finally {
9087            Binder.restoreCallingIdentity(token);
9088        }
9089    }
9090
9091    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9092        // Remove the parent package setting
9093        PackageSetting ps = (PackageSetting) pkg.mExtras;
9094        if (ps != null) {
9095            removePackageLI(ps, chatty);
9096        }
9097        // Remove the child package setting
9098        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9099        for (int i = 0; i < childCount; i++) {
9100            PackageParser.Package childPkg = pkg.childPackages.get(i);
9101            ps = (PackageSetting) childPkg.mExtras;
9102            if (ps != null) {
9103                removePackageLI(ps, chatty);
9104            }
9105        }
9106    }
9107
9108    void removePackageLI(PackageSetting ps, boolean chatty) {
9109        if (DEBUG_INSTALL) {
9110            if (chatty)
9111                Log.d(TAG, "Removing package " + ps.name);
9112        }
9113
9114        // writer
9115        synchronized (mPackages) {
9116            mPackages.remove(ps.name);
9117            final PackageParser.Package pkg = ps.pkg;
9118            if (pkg != null) {
9119                cleanPackageDataStructuresLILPw(pkg, chatty);
9120            }
9121        }
9122    }
9123
9124    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9125        if (DEBUG_INSTALL) {
9126            if (chatty)
9127                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9128        }
9129
9130        // writer
9131        synchronized (mPackages) {
9132            // Remove the parent package
9133            mPackages.remove(pkg.applicationInfo.packageName);
9134            cleanPackageDataStructuresLILPw(pkg, chatty);
9135
9136            // Remove the child packages
9137            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9138            for (int i = 0; i < childCount; i++) {
9139                PackageParser.Package childPkg = pkg.childPackages.get(i);
9140                mPackages.remove(childPkg.applicationInfo.packageName);
9141                cleanPackageDataStructuresLILPw(childPkg, chatty);
9142            }
9143        }
9144    }
9145
9146    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9147        int N = pkg.providers.size();
9148        StringBuilder r = null;
9149        int i;
9150        for (i=0; i<N; i++) {
9151            PackageParser.Provider p = pkg.providers.get(i);
9152            mProviders.removeProvider(p);
9153            if (p.info.authority == null) {
9154
9155                /* There was another ContentProvider with this authority when
9156                 * this app was installed so this authority is null,
9157                 * Ignore it as we don't have to unregister the provider.
9158                 */
9159                continue;
9160            }
9161            String names[] = p.info.authority.split(";");
9162            for (int j = 0; j < names.length; j++) {
9163                if (mProvidersByAuthority.get(names[j]) == p) {
9164                    mProvidersByAuthority.remove(names[j]);
9165                    if (DEBUG_REMOVE) {
9166                        if (chatty)
9167                            Log.d(TAG, "Unregistered content provider: " + names[j]
9168                                    + ", className = " + p.info.name + ", isSyncable = "
9169                                    + p.info.isSyncable);
9170                    }
9171                }
9172            }
9173            if (DEBUG_REMOVE && chatty) {
9174                if (r == null) {
9175                    r = new StringBuilder(256);
9176                } else {
9177                    r.append(' ');
9178                }
9179                r.append(p.info.name);
9180            }
9181        }
9182        if (r != null) {
9183            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9184        }
9185
9186        N = pkg.services.size();
9187        r = null;
9188        for (i=0; i<N; i++) {
9189            PackageParser.Service s = pkg.services.get(i);
9190            mServices.removeService(s);
9191            if (chatty) {
9192                if (r == null) {
9193                    r = new StringBuilder(256);
9194                } else {
9195                    r.append(' ');
9196                }
9197                r.append(s.info.name);
9198            }
9199        }
9200        if (r != null) {
9201            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9202        }
9203
9204        N = pkg.receivers.size();
9205        r = null;
9206        for (i=0; i<N; i++) {
9207            PackageParser.Activity a = pkg.receivers.get(i);
9208            mReceivers.removeActivity(a, "receiver");
9209            if (DEBUG_REMOVE && chatty) {
9210                if (r == null) {
9211                    r = new StringBuilder(256);
9212                } else {
9213                    r.append(' ');
9214                }
9215                r.append(a.info.name);
9216            }
9217        }
9218        if (r != null) {
9219            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9220        }
9221
9222        N = pkg.activities.size();
9223        r = null;
9224        for (i=0; i<N; i++) {
9225            PackageParser.Activity a = pkg.activities.get(i);
9226            mActivities.removeActivity(a, "activity");
9227            if (DEBUG_REMOVE && chatty) {
9228                if (r == null) {
9229                    r = new StringBuilder(256);
9230                } else {
9231                    r.append(' ');
9232                }
9233                r.append(a.info.name);
9234            }
9235        }
9236        if (r != null) {
9237            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9238        }
9239
9240        N = pkg.permissions.size();
9241        r = null;
9242        for (i=0; i<N; i++) {
9243            PackageParser.Permission p = pkg.permissions.get(i);
9244            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9245            if (bp == null) {
9246                bp = mSettings.mPermissionTrees.get(p.info.name);
9247            }
9248            if (bp != null && bp.perm == p) {
9249                bp.perm = null;
9250                if (DEBUG_REMOVE && chatty) {
9251                    if (r == null) {
9252                        r = new StringBuilder(256);
9253                    } else {
9254                        r.append(' ');
9255                    }
9256                    r.append(p.info.name);
9257                }
9258            }
9259            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9260                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9261                if (appOpPkgs != null) {
9262                    appOpPkgs.remove(pkg.packageName);
9263                }
9264            }
9265        }
9266        if (r != null) {
9267            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9268        }
9269
9270        N = pkg.requestedPermissions.size();
9271        r = null;
9272        for (i=0; i<N; i++) {
9273            String perm = pkg.requestedPermissions.get(i);
9274            BasePermission bp = mSettings.mPermissions.get(perm);
9275            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9276                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9277                if (appOpPkgs != null) {
9278                    appOpPkgs.remove(pkg.packageName);
9279                    if (appOpPkgs.isEmpty()) {
9280                        mAppOpPermissionPackages.remove(perm);
9281                    }
9282                }
9283            }
9284        }
9285        if (r != null) {
9286            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9287        }
9288
9289        N = pkg.instrumentation.size();
9290        r = null;
9291        for (i=0; i<N; i++) {
9292            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9293            mInstrumentation.remove(a.getComponentName());
9294            if (DEBUG_REMOVE && chatty) {
9295                if (r == null) {
9296                    r = new StringBuilder(256);
9297                } else {
9298                    r.append(' ');
9299                }
9300                r.append(a.info.name);
9301            }
9302        }
9303        if (r != null) {
9304            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9305        }
9306
9307        r = null;
9308        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9309            // Only system apps can hold shared libraries.
9310            if (pkg.libraryNames != null) {
9311                for (i=0; i<pkg.libraryNames.size(); i++) {
9312                    String name = pkg.libraryNames.get(i);
9313                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9314                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9315                        mSharedLibraries.remove(name);
9316                        if (DEBUG_REMOVE && chatty) {
9317                            if (r == null) {
9318                                r = new StringBuilder(256);
9319                            } else {
9320                                r.append(' ');
9321                            }
9322                            r.append(name);
9323                        }
9324                    }
9325                }
9326            }
9327        }
9328        if (r != null) {
9329            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9330        }
9331    }
9332
9333    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9334        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9335            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9336                return true;
9337            }
9338        }
9339        return false;
9340    }
9341
9342    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9343    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9344    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9345
9346    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9347        // Update the parent permissions
9348        updatePermissionsLPw(pkg.packageName, pkg, flags);
9349        // Update the child permissions
9350        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9351        for (int i = 0; i < childCount; i++) {
9352            PackageParser.Package childPkg = pkg.childPackages.get(i);
9353            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9354        }
9355    }
9356
9357    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9358            int flags) {
9359        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9360        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9361    }
9362
9363    private void updatePermissionsLPw(String changingPkg,
9364            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9365        // Make sure there are no dangling permission trees.
9366        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9367        while (it.hasNext()) {
9368            final BasePermission bp = it.next();
9369            if (bp.packageSetting == null) {
9370                // We may not yet have parsed the package, so just see if
9371                // we still know about its settings.
9372                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9373            }
9374            if (bp.packageSetting == null) {
9375                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9376                        + " from package " + bp.sourcePackage);
9377                it.remove();
9378            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9379                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9380                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9381                            + " from package " + bp.sourcePackage);
9382                    flags |= UPDATE_PERMISSIONS_ALL;
9383                    it.remove();
9384                }
9385            }
9386        }
9387
9388        // Make sure all dynamic permissions have been assigned to a package,
9389        // and make sure there are no dangling permissions.
9390        it = mSettings.mPermissions.values().iterator();
9391        while (it.hasNext()) {
9392            final BasePermission bp = it.next();
9393            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9394                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9395                        + bp.name + " pkg=" + bp.sourcePackage
9396                        + " info=" + bp.pendingInfo);
9397                if (bp.packageSetting == null && bp.pendingInfo != null) {
9398                    final BasePermission tree = findPermissionTreeLP(bp.name);
9399                    if (tree != null && tree.perm != null) {
9400                        bp.packageSetting = tree.packageSetting;
9401                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9402                                new PermissionInfo(bp.pendingInfo));
9403                        bp.perm.info.packageName = tree.perm.info.packageName;
9404                        bp.perm.info.name = bp.name;
9405                        bp.uid = tree.uid;
9406                    }
9407                }
9408            }
9409            if (bp.packageSetting == null) {
9410                // We may not yet have parsed the package, so just see if
9411                // we still know about its settings.
9412                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9413            }
9414            if (bp.packageSetting == null) {
9415                Slog.w(TAG, "Removing dangling permission: " + bp.name
9416                        + " from package " + bp.sourcePackage);
9417                it.remove();
9418            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9419                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9420                    Slog.i(TAG, "Removing old permission: " + bp.name
9421                            + " from package " + bp.sourcePackage);
9422                    flags |= UPDATE_PERMISSIONS_ALL;
9423                    it.remove();
9424                }
9425            }
9426        }
9427
9428        // Now update the permissions for all packages, in particular
9429        // replace the granted permissions of the system packages.
9430        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9431            for (PackageParser.Package pkg : mPackages.values()) {
9432                if (pkg != pkgInfo) {
9433                    // Only replace for packages on requested volume
9434                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9435                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9436                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9437                    grantPermissionsLPw(pkg, replace, changingPkg);
9438                }
9439            }
9440        }
9441
9442        if (pkgInfo != null) {
9443            // Only replace for packages on requested volume
9444            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9445            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9446                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9447            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9448        }
9449    }
9450
9451    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9452            String packageOfInterest) {
9453        // IMPORTANT: There are two types of permissions: install and runtime.
9454        // Install time permissions are granted when the app is installed to
9455        // all device users and users added in the future. Runtime permissions
9456        // are granted at runtime explicitly to specific users. Normal and signature
9457        // protected permissions are install time permissions. Dangerous permissions
9458        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9459        // otherwise they are runtime permissions. This function does not manage
9460        // runtime permissions except for the case an app targeting Lollipop MR1
9461        // being upgraded to target a newer SDK, in which case dangerous permissions
9462        // are transformed from install time to runtime ones.
9463
9464        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9465        if (ps == null) {
9466            return;
9467        }
9468
9469        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9470
9471        PermissionsState permissionsState = ps.getPermissionsState();
9472        PermissionsState origPermissions = permissionsState;
9473
9474        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9475
9476        boolean runtimePermissionsRevoked = false;
9477        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9478
9479        boolean changedInstallPermission = false;
9480
9481        if (replace) {
9482            ps.installPermissionsFixed = false;
9483            if (!ps.isSharedUser()) {
9484                origPermissions = new PermissionsState(permissionsState);
9485                permissionsState.reset();
9486            } else {
9487                // We need to know only about runtime permission changes since the
9488                // calling code always writes the install permissions state but
9489                // the runtime ones are written only if changed. The only cases of
9490                // changed runtime permissions here are promotion of an install to
9491                // runtime and revocation of a runtime from a shared user.
9492                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9493                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9494                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9495                    runtimePermissionsRevoked = true;
9496                }
9497            }
9498        }
9499
9500        permissionsState.setGlobalGids(mGlobalGids);
9501
9502        final int N = pkg.requestedPermissions.size();
9503        for (int i=0; i<N; i++) {
9504            final String name = pkg.requestedPermissions.get(i);
9505            final BasePermission bp = mSettings.mPermissions.get(name);
9506
9507            if (DEBUG_INSTALL) {
9508                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9509            }
9510
9511            if (bp == null || bp.packageSetting == null) {
9512                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9513                    Slog.w(TAG, "Unknown permission " + name
9514                            + " in package " + pkg.packageName);
9515                }
9516                continue;
9517            }
9518
9519            final String perm = bp.name;
9520            boolean allowedSig = false;
9521            int grant = GRANT_DENIED;
9522
9523            // Keep track of app op permissions.
9524            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9525                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9526                if (pkgs == null) {
9527                    pkgs = new ArraySet<>();
9528                    mAppOpPermissionPackages.put(bp.name, pkgs);
9529                }
9530                pkgs.add(pkg.packageName);
9531            }
9532
9533            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9534            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9535                    >= Build.VERSION_CODES.M;
9536            switch (level) {
9537                case PermissionInfo.PROTECTION_NORMAL: {
9538                    // For all apps normal permissions are install time ones.
9539                    grant = GRANT_INSTALL;
9540                } break;
9541
9542                case PermissionInfo.PROTECTION_DANGEROUS: {
9543                    // If a permission review is required for legacy apps we represent
9544                    // their permissions as always granted runtime ones since we need
9545                    // to keep the review required permission flag per user while an
9546                    // install permission's state is shared across all users.
9547                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9548                        // For legacy apps dangerous permissions are install time ones.
9549                        grant = GRANT_INSTALL;
9550                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9551                        // For legacy apps that became modern, install becomes runtime.
9552                        grant = GRANT_UPGRADE;
9553                    } else if (mPromoteSystemApps
9554                            && isSystemApp(ps)
9555                            && mExistingSystemPackages.contains(ps.name)) {
9556                        // For legacy system apps, install becomes runtime.
9557                        // We cannot check hasInstallPermission() for system apps since those
9558                        // permissions were granted implicitly and not persisted pre-M.
9559                        grant = GRANT_UPGRADE;
9560                    } else {
9561                        // For modern apps keep runtime permissions unchanged.
9562                        grant = GRANT_RUNTIME;
9563                    }
9564                } break;
9565
9566                case PermissionInfo.PROTECTION_SIGNATURE: {
9567                    // For all apps signature permissions are install time ones.
9568                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9569                    if (allowedSig) {
9570                        grant = GRANT_INSTALL;
9571                    }
9572                } break;
9573            }
9574
9575            if (DEBUG_INSTALL) {
9576                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9577            }
9578
9579            if (grant != GRANT_DENIED) {
9580                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9581                    // If this is an existing, non-system package, then
9582                    // we can't add any new permissions to it.
9583                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9584                        // Except...  if this is a permission that was added
9585                        // to the platform (note: need to only do this when
9586                        // updating the platform).
9587                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9588                            grant = GRANT_DENIED;
9589                        }
9590                    }
9591                }
9592
9593                switch (grant) {
9594                    case GRANT_INSTALL: {
9595                        // Revoke this as runtime permission to handle the case of
9596                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9597                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9598                            if (origPermissions.getRuntimePermissionState(
9599                                    bp.name, userId) != null) {
9600                                // Revoke the runtime permission and clear the flags.
9601                                origPermissions.revokeRuntimePermission(bp, userId);
9602                                origPermissions.updatePermissionFlags(bp, userId,
9603                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9604                                // If we revoked a permission permission, we have to write.
9605                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9606                                        changedRuntimePermissionUserIds, userId);
9607                            }
9608                        }
9609                        // Grant an install permission.
9610                        if (permissionsState.grantInstallPermission(bp) !=
9611                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9612                            changedInstallPermission = true;
9613                        }
9614                    } break;
9615
9616                    case GRANT_RUNTIME: {
9617                        // Grant previously granted runtime permissions.
9618                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9619                            PermissionState permissionState = origPermissions
9620                                    .getRuntimePermissionState(bp.name, userId);
9621                            int flags = permissionState != null
9622                                    ? permissionState.getFlags() : 0;
9623                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9624                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9625                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9626                                    // If we cannot put the permission as it was, we have to write.
9627                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9628                                            changedRuntimePermissionUserIds, userId);
9629                                }
9630                                // If the app supports runtime permissions no need for a review.
9631                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9632                                        && appSupportsRuntimePermissions
9633                                        && (flags & PackageManager
9634                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9635                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9636                                    // Since we changed the flags, we have to write.
9637                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9638                                            changedRuntimePermissionUserIds, userId);
9639                                }
9640                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9641                                    && !appSupportsRuntimePermissions) {
9642                                // For legacy apps that need a permission review, every new
9643                                // runtime permission is granted but it is pending a review.
9644                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9645                                    permissionsState.grantRuntimePermission(bp, userId);
9646                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9647                                    // We changed the permission and flags, hence have to write.
9648                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9649                                            changedRuntimePermissionUserIds, userId);
9650                                }
9651                            }
9652                            // Propagate the permission flags.
9653                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9654                        }
9655                    } break;
9656
9657                    case GRANT_UPGRADE: {
9658                        // Grant runtime permissions for a previously held install permission.
9659                        PermissionState permissionState = origPermissions
9660                                .getInstallPermissionState(bp.name);
9661                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9662
9663                        if (origPermissions.revokeInstallPermission(bp)
9664                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9665                            // We will be transferring the permission flags, so clear them.
9666                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9667                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9668                            changedInstallPermission = true;
9669                        }
9670
9671                        // If the permission is not to be promoted to runtime we ignore it and
9672                        // also its other flags as they are not applicable to install permissions.
9673                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9674                            for (int userId : currentUserIds) {
9675                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9676                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9677                                    // Transfer the permission flags.
9678                                    permissionsState.updatePermissionFlags(bp, userId,
9679                                            flags, flags);
9680                                    // If we granted the permission, we have to write.
9681                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9682                                            changedRuntimePermissionUserIds, userId);
9683                                }
9684                            }
9685                        }
9686                    } break;
9687
9688                    default: {
9689                        if (packageOfInterest == null
9690                                || packageOfInterest.equals(pkg.packageName)) {
9691                            Slog.w(TAG, "Not granting permission " + perm
9692                                    + " to package " + pkg.packageName
9693                                    + " because it was previously installed without");
9694                        }
9695                    } break;
9696                }
9697            } else {
9698                if (permissionsState.revokeInstallPermission(bp) !=
9699                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9700                    // Also drop the permission flags.
9701                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9702                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9703                    changedInstallPermission = true;
9704                    Slog.i(TAG, "Un-granting permission " + perm
9705                            + " from package " + pkg.packageName
9706                            + " (protectionLevel=" + bp.protectionLevel
9707                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9708                            + ")");
9709                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9710                    // Don't print warning for app op permissions, since it is fine for them
9711                    // not to be granted, there is a UI for the user to decide.
9712                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9713                        Slog.w(TAG, "Not granting permission " + perm
9714                                + " to package " + pkg.packageName
9715                                + " (protectionLevel=" + bp.protectionLevel
9716                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9717                                + ")");
9718                    }
9719                }
9720            }
9721        }
9722
9723        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9724                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9725            // This is the first that we have heard about this package, so the
9726            // permissions we have now selected are fixed until explicitly
9727            // changed.
9728            ps.installPermissionsFixed = true;
9729        }
9730
9731        // Persist the runtime permissions state for users with changes. If permissions
9732        // were revoked because no app in the shared user declares them we have to
9733        // write synchronously to avoid losing runtime permissions state.
9734        for (int userId : changedRuntimePermissionUserIds) {
9735            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9736        }
9737
9738        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9739    }
9740
9741    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9742        boolean allowed = false;
9743        final int NP = PackageParser.NEW_PERMISSIONS.length;
9744        for (int ip=0; ip<NP; ip++) {
9745            final PackageParser.NewPermissionInfo npi
9746                    = PackageParser.NEW_PERMISSIONS[ip];
9747            if (npi.name.equals(perm)
9748                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9749                allowed = true;
9750                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9751                        + pkg.packageName);
9752                break;
9753            }
9754        }
9755        return allowed;
9756    }
9757
9758    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9759            BasePermission bp, PermissionsState origPermissions) {
9760        boolean allowed;
9761        allowed = (compareSignatures(
9762                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9763                        == PackageManager.SIGNATURE_MATCH)
9764                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9765                        == PackageManager.SIGNATURE_MATCH);
9766        if (!allowed && (bp.protectionLevel
9767                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9768            if (isSystemApp(pkg)) {
9769                // For updated system applications, a system permission
9770                // is granted only if it had been defined by the original application.
9771                if (pkg.isUpdatedSystemApp()) {
9772                    final PackageSetting sysPs = mSettings
9773                            .getDisabledSystemPkgLPr(pkg.packageName);
9774                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9775                        // If the original was granted this permission, we take
9776                        // that grant decision as read and propagate it to the
9777                        // update.
9778                        if (sysPs.isPrivileged()) {
9779                            allowed = true;
9780                        }
9781                    } else {
9782                        // The system apk may have been updated with an older
9783                        // version of the one on the data partition, but which
9784                        // granted a new system permission that it didn't have
9785                        // before.  In this case we do want to allow the app to
9786                        // now get the new permission if the ancestral apk is
9787                        // privileged to get it.
9788                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9789                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9790                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9791                                    allowed = true;
9792                                    break;
9793                                }
9794                            }
9795                        }
9796                        // Also if a privileged parent package on the system image or any of
9797                        // its children requested a privileged permission, the updated child
9798                        // packages can also get the permission.
9799                        if (pkg.parentPackage != null) {
9800                            final PackageSetting disabledSysParentPs = mSettings
9801                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9802                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9803                                    && disabledSysParentPs.isPrivileged()) {
9804                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9805                                    allowed = true;
9806                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9807                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9808                                    for (int i = 0; i < count; i++) {
9809                                        PackageParser.Package disabledSysChildPkg =
9810                                                disabledSysParentPs.pkg.childPackages.get(i);
9811                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9812                                                perm)) {
9813                                            allowed = true;
9814                                            break;
9815                                        }
9816                                    }
9817                                }
9818                            }
9819                        }
9820                    }
9821                } else {
9822                    allowed = isPrivilegedApp(pkg);
9823                }
9824            }
9825        }
9826        if (!allowed) {
9827            if (!allowed && (bp.protectionLevel
9828                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9829                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9830                // If this was a previously normal/dangerous permission that got moved
9831                // to a system permission as part of the runtime permission redesign, then
9832                // we still want to blindly grant it to old apps.
9833                allowed = true;
9834            }
9835            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9836                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9837                // If this permission is to be granted to the system installer and
9838                // this app is an installer, then it gets the permission.
9839                allowed = true;
9840            }
9841            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9842                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9843                // If this permission is to be granted to the system verifier and
9844                // this app is a verifier, then it gets the permission.
9845                allowed = true;
9846            }
9847            if (!allowed && (bp.protectionLevel
9848                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9849                    && isSystemApp(pkg)) {
9850                // Any pre-installed system app is allowed to get this permission.
9851                allowed = true;
9852            }
9853            if (!allowed && (bp.protectionLevel
9854                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9855                // For development permissions, a development permission
9856                // is granted only if it was already granted.
9857                allowed = origPermissions.hasInstallPermission(perm);
9858            }
9859            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
9860                    && pkg.packageName.equals(mSetupWizardPackage)) {
9861                // If this permission is to be granted to the system setup wizard and
9862                // this app is a setup wizard, then it gets the permission.
9863                allowed = true;
9864            }
9865        }
9866        return allowed;
9867    }
9868
9869    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9870        final int permCount = pkg.requestedPermissions.size();
9871        for (int j = 0; j < permCount; j++) {
9872            String requestedPermission = pkg.requestedPermissions.get(j);
9873            if (permission.equals(requestedPermission)) {
9874                return true;
9875            }
9876        }
9877        return false;
9878    }
9879
9880    final class ActivityIntentResolver
9881            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9882        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9883                boolean defaultOnly, int userId) {
9884            if (!sUserManager.exists(userId)) return null;
9885            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9886            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9887        }
9888
9889        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9890                int userId) {
9891            if (!sUserManager.exists(userId)) return null;
9892            mFlags = flags;
9893            return super.queryIntent(intent, resolvedType,
9894                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9895        }
9896
9897        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9898                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9899            if (!sUserManager.exists(userId)) return null;
9900            if (packageActivities == null) {
9901                return null;
9902            }
9903            mFlags = flags;
9904            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9905            final int N = packageActivities.size();
9906            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9907                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9908
9909            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9910            for (int i = 0; i < N; ++i) {
9911                intentFilters = packageActivities.get(i).intents;
9912                if (intentFilters != null && intentFilters.size() > 0) {
9913                    PackageParser.ActivityIntentInfo[] array =
9914                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9915                    intentFilters.toArray(array);
9916                    listCut.add(array);
9917                }
9918            }
9919            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9920        }
9921
9922        /**
9923         * Finds a privileged activity that matches the specified activity names.
9924         */
9925        private PackageParser.Activity findMatchingActivity(
9926                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
9927            for (PackageParser.Activity sysActivity : activityList) {
9928                if (sysActivity.info.name.equals(activityInfo.name)) {
9929                    return sysActivity;
9930                }
9931                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
9932                    return sysActivity;
9933                }
9934                if (sysActivity.info.targetActivity != null) {
9935                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
9936                        return sysActivity;
9937                    }
9938                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
9939                        return sysActivity;
9940                    }
9941                }
9942            }
9943            return null;
9944        }
9945
9946        public class IterGenerator<E> {
9947            public Iterator<E> generate(ActivityIntentInfo info) {
9948                return null;
9949            }
9950        }
9951
9952        public class ActionIterGenerator extends IterGenerator<String> {
9953            @Override
9954            public Iterator<String> generate(ActivityIntentInfo info) {
9955                return info.actionsIterator();
9956            }
9957        }
9958
9959        public class CategoriesIterGenerator extends IterGenerator<String> {
9960            @Override
9961            public Iterator<String> generate(ActivityIntentInfo info) {
9962                return info.categoriesIterator();
9963            }
9964        }
9965
9966        public class SchemesIterGenerator extends IterGenerator<String> {
9967            @Override
9968            public Iterator<String> generate(ActivityIntentInfo info) {
9969                return info.schemesIterator();
9970            }
9971        }
9972
9973        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
9974            @Override
9975            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
9976                return info.authoritiesIterator();
9977            }
9978        }
9979
9980        /**
9981         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
9982         * MODIFIED. Do not pass in a list that should not be changed.
9983         */
9984        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
9985                IterGenerator<T> generator, Iterator<T> searchIterator) {
9986            // loop through the set of actions; every one must be found in the intent filter
9987            while (searchIterator.hasNext()) {
9988                // we must have at least one filter in the list to consider a match
9989                if (intentList.size() == 0) {
9990                    break;
9991                }
9992
9993                final T searchAction = searchIterator.next();
9994
9995                // loop through the set of intent filters
9996                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
9997                while (intentIter.hasNext()) {
9998                    final ActivityIntentInfo intentInfo = intentIter.next();
9999                    boolean selectionFound = false;
10000
10001                    // loop through the intent filter's selection criteria; at least one
10002                    // of them must match the searched criteria
10003                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10004                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10005                        final T intentSelection = intentSelectionIter.next();
10006                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10007                            selectionFound = true;
10008                            break;
10009                        }
10010                    }
10011
10012                    // the selection criteria wasn't found in this filter's set; this filter
10013                    // is not a potential match
10014                    if (!selectionFound) {
10015                        intentIter.remove();
10016                    }
10017                }
10018            }
10019        }
10020
10021        private boolean isProtectedAction(ActivityIntentInfo filter) {
10022            final Iterator<String> actionsIter = filter.actionsIterator();
10023            while (actionsIter != null && actionsIter.hasNext()) {
10024                final String filterAction = actionsIter.next();
10025                if (PROTECTED_ACTIONS.contains(filterAction)) {
10026                    return true;
10027                }
10028            }
10029            return false;
10030        }
10031
10032        /**
10033         * Adjusts the priority of the given intent filter according to policy.
10034         * <p>
10035         * <ul>
10036         * <li>The priority for non privileged applications is capped to '0'</li>
10037         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10038         * <li>The priority for unbundled updates to privileged applications is capped to the
10039         *      priority defined on the system partition</li>
10040         * </ul>
10041         * <p>
10042         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10043         * allowed to obtain any priority on any action.
10044         */
10045        private void adjustPriority(
10046                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10047            // nothing to do; priority is fine as-is
10048            if (intent.getPriority() <= 0) {
10049                return;
10050            }
10051
10052            final ActivityInfo activityInfo = intent.activity.info;
10053            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10054
10055            final boolean privilegedApp =
10056                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10057            if (!privilegedApp) {
10058                // non-privileged applications can never define a priority >0
10059                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10060                        + " package: " + applicationInfo.packageName
10061                        + " activity: " + intent.activity.className
10062                        + " origPrio: " + intent.getPriority());
10063                intent.setPriority(0);
10064                return;
10065            }
10066
10067            if (systemActivities == null) {
10068                // the system package is not disabled; we're parsing the system partition
10069                if (isProtectedAction(intent)) {
10070                    if (mDeferProtectedFilters) {
10071                        // We can't deal with these just yet. No component should ever obtain a
10072                        // >0 priority for a protected actions, with ONE exception -- the setup
10073                        // wizard. The setup wizard, however, cannot be known until we're able to
10074                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10075                        // until all intent filters have been processed. Chicken, meet egg.
10076                        // Let the filter temporarily have a high priority and rectify the
10077                        // priorities after all system packages have been scanned.
10078                        mProtectedFilters.add(intent);
10079                        if (DEBUG_FILTERS) {
10080                            Slog.i(TAG, "Protected action; save for later;"
10081                                    + " package: " + applicationInfo.packageName
10082                                    + " activity: " + intent.activity.className
10083                                    + " origPrio: " + intent.getPriority());
10084                        }
10085                        return;
10086                    } else {
10087                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10088                            Slog.i(TAG, "No setup wizard;"
10089                                + " All protected intents capped to priority 0");
10090                        }
10091                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10092                            if (DEBUG_FILTERS) {
10093                                Slog.i(TAG, "Found setup wizard;"
10094                                    + " allow priority " + intent.getPriority() + ";"
10095                                    + " package: " + intent.activity.info.packageName
10096                                    + " activity: " + intent.activity.className
10097                                    + " priority: " + intent.getPriority());
10098                            }
10099                            // setup wizard gets whatever it wants
10100                            return;
10101                        }
10102                        Slog.w(TAG, "Protected action; cap priority to 0;"
10103                                + " package: " + intent.activity.info.packageName
10104                                + " activity: " + intent.activity.className
10105                                + " origPrio: " + intent.getPriority());
10106                        intent.setPriority(0);
10107                        return;
10108                    }
10109                }
10110                // privileged apps on the system image get whatever priority they request
10111                return;
10112            }
10113
10114            // privileged app unbundled update ... try to find the same activity
10115            final PackageParser.Activity foundActivity =
10116                    findMatchingActivity(systemActivities, activityInfo);
10117            if (foundActivity == null) {
10118                // this is a new activity; it cannot obtain >0 priority
10119                if (DEBUG_FILTERS) {
10120                    Slog.i(TAG, "New activity; cap priority to 0;"
10121                            + " package: " + applicationInfo.packageName
10122                            + " activity: " + intent.activity.className
10123                            + " origPrio: " + intent.getPriority());
10124                }
10125                intent.setPriority(0);
10126                return;
10127            }
10128
10129            // found activity, now check for filter equivalence
10130
10131            // a shallow copy is enough; we modify the list, not its contents
10132            final List<ActivityIntentInfo> intentListCopy =
10133                    new ArrayList<>(foundActivity.intents);
10134            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10135
10136            // find matching action subsets
10137            final Iterator<String> actionsIterator = intent.actionsIterator();
10138            if (actionsIterator != null) {
10139                getIntentListSubset(
10140                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10141                if (intentListCopy.size() == 0) {
10142                    // no more intents to match; we're not equivalent
10143                    if (DEBUG_FILTERS) {
10144                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10145                                + " package: " + applicationInfo.packageName
10146                                + " activity: " + intent.activity.className
10147                                + " origPrio: " + intent.getPriority());
10148                    }
10149                    intent.setPriority(0);
10150                    return;
10151                }
10152            }
10153
10154            // find matching category subsets
10155            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10156            if (categoriesIterator != null) {
10157                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10158                        categoriesIterator);
10159                if (intentListCopy.size() == 0) {
10160                    // no more intents to match; we're not equivalent
10161                    if (DEBUG_FILTERS) {
10162                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10163                                + " package: " + applicationInfo.packageName
10164                                + " activity: " + intent.activity.className
10165                                + " origPrio: " + intent.getPriority());
10166                    }
10167                    intent.setPriority(0);
10168                    return;
10169                }
10170            }
10171
10172            // find matching schemes subsets
10173            final Iterator<String> schemesIterator = intent.schemesIterator();
10174            if (schemesIterator != null) {
10175                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10176                        schemesIterator);
10177                if (intentListCopy.size() == 0) {
10178                    // no more intents to match; we're not equivalent
10179                    if (DEBUG_FILTERS) {
10180                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10181                                + " package: " + applicationInfo.packageName
10182                                + " activity: " + intent.activity.className
10183                                + " origPrio: " + intent.getPriority());
10184                    }
10185                    intent.setPriority(0);
10186                    return;
10187                }
10188            }
10189
10190            // find matching authorities subsets
10191            final Iterator<IntentFilter.AuthorityEntry>
10192                    authoritiesIterator = intent.authoritiesIterator();
10193            if (authoritiesIterator != null) {
10194                getIntentListSubset(intentListCopy,
10195                        new AuthoritiesIterGenerator(),
10196                        authoritiesIterator);
10197                if (intentListCopy.size() == 0) {
10198                    // no more intents to match; we're not equivalent
10199                    if (DEBUG_FILTERS) {
10200                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10201                                + " package: " + applicationInfo.packageName
10202                                + " activity: " + intent.activity.className
10203                                + " origPrio: " + intent.getPriority());
10204                    }
10205                    intent.setPriority(0);
10206                    return;
10207                }
10208            }
10209
10210            // we found matching filter(s); app gets the max priority of all intents
10211            int cappedPriority = 0;
10212            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10213                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10214            }
10215            if (intent.getPriority() > cappedPriority) {
10216                if (DEBUG_FILTERS) {
10217                    Slog.i(TAG, "Found matching filter(s);"
10218                            + " cap priority to " + cappedPriority + ";"
10219                            + " package: " + applicationInfo.packageName
10220                            + " activity: " + intent.activity.className
10221                            + " origPrio: " + intent.getPriority());
10222                }
10223                intent.setPriority(cappedPriority);
10224                return;
10225            }
10226            // all this for nothing; the requested priority was <= what was on the system
10227        }
10228
10229        public final void addActivity(PackageParser.Activity a, String type) {
10230            mActivities.put(a.getComponentName(), a);
10231            if (DEBUG_SHOW_INFO)
10232                Log.v(
10233                TAG, "  " + type + " " +
10234                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10235            if (DEBUG_SHOW_INFO)
10236                Log.v(TAG, "    Class=" + a.info.name);
10237            final int NI = a.intents.size();
10238            for (int j=0; j<NI; j++) {
10239                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10240                if ("activity".equals(type)) {
10241                    final PackageSetting ps =
10242                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10243                    final List<PackageParser.Activity> systemActivities =
10244                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10245                    adjustPriority(systemActivities, intent);
10246                }
10247                if (DEBUG_SHOW_INFO) {
10248                    Log.v(TAG, "    IntentFilter:");
10249                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10250                }
10251                if (!intent.debugCheck()) {
10252                    Log.w(TAG, "==> For Activity " + a.info.name);
10253                }
10254                addFilter(intent);
10255            }
10256        }
10257
10258        public final void removeActivity(PackageParser.Activity a, String type) {
10259            mActivities.remove(a.getComponentName());
10260            if (DEBUG_SHOW_INFO) {
10261                Log.v(TAG, "  " + type + " "
10262                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10263                                : a.info.name) + ":");
10264                Log.v(TAG, "    Class=" + a.info.name);
10265            }
10266            final int NI = a.intents.size();
10267            for (int j=0; j<NI; j++) {
10268                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10269                if (DEBUG_SHOW_INFO) {
10270                    Log.v(TAG, "    IntentFilter:");
10271                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10272                }
10273                removeFilter(intent);
10274            }
10275        }
10276
10277        @Override
10278        protected boolean allowFilterResult(
10279                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10280            ActivityInfo filterAi = filter.activity.info;
10281            for (int i=dest.size()-1; i>=0; i--) {
10282                ActivityInfo destAi = dest.get(i).activityInfo;
10283                if (destAi.name == filterAi.name
10284                        && destAi.packageName == filterAi.packageName) {
10285                    return false;
10286                }
10287            }
10288            return true;
10289        }
10290
10291        @Override
10292        protected ActivityIntentInfo[] newArray(int size) {
10293            return new ActivityIntentInfo[size];
10294        }
10295
10296        @Override
10297        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10298            if (!sUserManager.exists(userId)) return true;
10299            PackageParser.Package p = filter.activity.owner;
10300            if (p != null) {
10301                PackageSetting ps = (PackageSetting)p.mExtras;
10302                if (ps != null) {
10303                    // System apps are never considered stopped for purposes of
10304                    // filtering, because there may be no way for the user to
10305                    // actually re-launch them.
10306                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10307                            && ps.getStopped(userId);
10308                }
10309            }
10310            return false;
10311        }
10312
10313        @Override
10314        protected boolean isPackageForFilter(String packageName,
10315                PackageParser.ActivityIntentInfo info) {
10316            return packageName.equals(info.activity.owner.packageName);
10317        }
10318
10319        @Override
10320        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10321                int match, int userId) {
10322            if (!sUserManager.exists(userId)) return null;
10323            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10324                return null;
10325            }
10326            final PackageParser.Activity activity = info.activity;
10327            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10328            if (ps == null) {
10329                return null;
10330            }
10331            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10332                    ps.readUserState(userId), userId);
10333            if (ai == null) {
10334                return null;
10335            }
10336            final ResolveInfo res = new ResolveInfo();
10337            res.activityInfo = ai;
10338            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10339                res.filter = info;
10340            }
10341            if (info != null) {
10342                res.handleAllWebDataURI = info.handleAllWebDataURI();
10343            }
10344            res.priority = info.getPriority();
10345            res.preferredOrder = activity.owner.mPreferredOrder;
10346            //System.out.println("Result: " + res.activityInfo.className +
10347            //                   " = " + res.priority);
10348            res.match = match;
10349            res.isDefault = info.hasDefault;
10350            res.labelRes = info.labelRes;
10351            res.nonLocalizedLabel = info.nonLocalizedLabel;
10352            if (userNeedsBadging(userId)) {
10353                res.noResourceId = true;
10354            } else {
10355                res.icon = info.icon;
10356            }
10357            res.iconResourceId = info.icon;
10358            res.system = res.activityInfo.applicationInfo.isSystemApp();
10359            return res;
10360        }
10361
10362        @Override
10363        protected void sortResults(List<ResolveInfo> results) {
10364            Collections.sort(results, mResolvePrioritySorter);
10365        }
10366
10367        @Override
10368        protected void dumpFilter(PrintWriter out, String prefix,
10369                PackageParser.ActivityIntentInfo filter) {
10370            out.print(prefix); out.print(
10371                    Integer.toHexString(System.identityHashCode(filter.activity)));
10372                    out.print(' ');
10373                    filter.activity.printComponentShortName(out);
10374                    out.print(" filter ");
10375                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10376        }
10377
10378        @Override
10379        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10380            return filter.activity;
10381        }
10382
10383        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10384            PackageParser.Activity activity = (PackageParser.Activity)label;
10385            out.print(prefix); out.print(
10386                    Integer.toHexString(System.identityHashCode(activity)));
10387                    out.print(' ');
10388                    activity.printComponentShortName(out);
10389            if (count > 1) {
10390                out.print(" ("); out.print(count); out.print(" filters)");
10391            }
10392            out.println();
10393        }
10394
10395        // Keys are String (activity class name), values are Activity.
10396        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10397                = new ArrayMap<ComponentName, PackageParser.Activity>();
10398        private int mFlags;
10399    }
10400
10401    private final class ServiceIntentResolver
10402            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10403        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10404                boolean defaultOnly, int userId) {
10405            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10406            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10407        }
10408
10409        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10410                int userId) {
10411            if (!sUserManager.exists(userId)) return null;
10412            mFlags = flags;
10413            return super.queryIntent(intent, resolvedType,
10414                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10415        }
10416
10417        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10418                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10419            if (!sUserManager.exists(userId)) return null;
10420            if (packageServices == null) {
10421                return null;
10422            }
10423            mFlags = flags;
10424            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10425            final int N = packageServices.size();
10426            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10427                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10428
10429            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10430            for (int i = 0; i < N; ++i) {
10431                intentFilters = packageServices.get(i).intents;
10432                if (intentFilters != null && intentFilters.size() > 0) {
10433                    PackageParser.ServiceIntentInfo[] array =
10434                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10435                    intentFilters.toArray(array);
10436                    listCut.add(array);
10437                }
10438            }
10439            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10440        }
10441
10442        public final void addService(PackageParser.Service s) {
10443            mServices.put(s.getComponentName(), s);
10444            if (DEBUG_SHOW_INFO) {
10445                Log.v(TAG, "  "
10446                        + (s.info.nonLocalizedLabel != null
10447                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10448                Log.v(TAG, "    Class=" + s.info.name);
10449            }
10450            final int NI = s.intents.size();
10451            int j;
10452            for (j=0; j<NI; j++) {
10453                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10454                if (DEBUG_SHOW_INFO) {
10455                    Log.v(TAG, "    IntentFilter:");
10456                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10457                }
10458                if (!intent.debugCheck()) {
10459                    Log.w(TAG, "==> For Service " + s.info.name);
10460                }
10461                addFilter(intent);
10462            }
10463        }
10464
10465        public final void removeService(PackageParser.Service s) {
10466            mServices.remove(s.getComponentName());
10467            if (DEBUG_SHOW_INFO) {
10468                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10469                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10470                Log.v(TAG, "    Class=" + s.info.name);
10471            }
10472            final int NI = s.intents.size();
10473            int j;
10474            for (j=0; j<NI; j++) {
10475                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10476                if (DEBUG_SHOW_INFO) {
10477                    Log.v(TAG, "    IntentFilter:");
10478                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10479                }
10480                removeFilter(intent);
10481            }
10482        }
10483
10484        @Override
10485        protected boolean allowFilterResult(
10486                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10487            ServiceInfo filterSi = filter.service.info;
10488            for (int i=dest.size()-1; i>=0; i--) {
10489                ServiceInfo destAi = dest.get(i).serviceInfo;
10490                if (destAi.name == filterSi.name
10491                        && destAi.packageName == filterSi.packageName) {
10492                    return false;
10493                }
10494            }
10495            return true;
10496        }
10497
10498        @Override
10499        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10500            return new PackageParser.ServiceIntentInfo[size];
10501        }
10502
10503        @Override
10504        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10505            if (!sUserManager.exists(userId)) return true;
10506            PackageParser.Package p = filter.service.owner;
10507            if (p != null) {
10508                PackageSetting ps = (PackageSetting)p.mExtras;
10509                if (ps != null) {
10510                    // System apps are never considered stopped for purposes of
10511                    // filtering, because there may be no way for the user to
10512                    // actually re-launch them.
10513                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10514                            && ps.getStopped(userId);
10515                }
10516            }
10517            return false;
10518        }
10519
10520        @Override
10521        protected boolean isPackageForFilter(String packageName,
10522                PackageParser.ServiceIntentInfo info) {
10523            return packageName.equals(info.service.owner.packageName);
10524        }
10525
10526        @Override
10527        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10528                int match, int userId) {
10529            if (!sUserManager.exists(userId)) return null;
10530            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10531            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10532                return null;
10533            }
10534            final PackageParser.Service service = info.service;
10535            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10536            if (ps == null) {
10537                return null;
10538            }
10539            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10540                    ps.readUserState(userId), userId);
10541            if (si == null) {
10542                return null;
10543            }
10544            final ResolveInfo res = new ResolveInfo();
10545            res.serviceInfo = si;
10546            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10547                res.filter = filter;
10548            }
10549            res.priority = info.getPriority();
10550            res.preferredOrder = service.owner.mPreferredOrder;
10551            res.match = match;
10552            res.isDefault = info.hasDefault;
10553            res.labelRes = info.labelRes;
10554            res.nonLocalizedLabel = info.nonLocalizedLabel;
10555            res.icon = info.icon;
10556            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10557            return res;
10558        }
10559
10560        @Override
10561        protected void sortResults(List<ResolveInfo> results) {
10562            Collections.sort(results, mResolvePrioritySorter);
10563        }
10564
10565        @Override
10566        protected void dumpFilter(PrintWriter out, String prefix,
10567                PackageParser.ServiceIntentInfo filter) {
10568            out.print(prefix); out.print(
10569                    Integer.toHexString(System.identityHashCode(filter.service)));
10570                    out.print(' ');
10571                    filter.service.printComponentShortName(out);
10572                    out.print(" filter ");
10573                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10574        }
10575
10576        @Override
10577        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10578            return filter.service;
10579        }
10580
10581        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10582            PackageParser.Service service = (PackageParser.Service)label;
10583            out.print(prefix); out.print(
10584                    Integer.toHexString(System.identityHashCode(service)));
10585                    out.print(' ');
10586                    service.printComponentShortName(out);
10587            if (count > 1) {
10588                out.print(" ("); out.print(count); out.print(" filters)");
10589            }
10590            out.println();
10591        }
10592
10593//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10594//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10595//            final List<ResolveInfo> retList = Lists.newArrayList();
10596//            while (i.hasNext()) {
10597//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10598//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10599//                    retList.add(resolveInfo);
10600//                }
10601//            }
10602//            return retList;
10603//        }
10604
10605        // Keys are String (activity class name), values are Activity.
10606        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10607                = new ArrayMap<ComponentName, PackageParser.Service>();
10608        private int mFlags;
10609    };
10610
10611    private final class ProviderIntentResolver
10612            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10613        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10614                boolean defaultOnly, int userId) {
10615            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10616            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10617        }
10618
10619        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10620                int userId) {
10621            if (!sUserManager.exists(userId))
10622                return null;
10623            mFlags = flags;
10624            return super.queryIntent(intent, resolvedType,
10625                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10626        }
10627
10628        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10629                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10630            if (!sUserManager.exists(userId))
10631                return null;
10632            if (packageProviders == null) {
10633                return null;
10634            }
10635            mFlags = flags;
10636            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10637            final int N = packageProviders.size();
10638            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10639                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10640
10641            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10642            for (int i = 0; i < N; ++i) {
10643                intentFilters = packageProviders.get(i).intents;
10644                if (intentFilters != null && intentFilters.size() > 0) {
10645                    PackageParser.ProviderIntentInfo[] array =
10646                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10647                    intentFilters.toArray(array);
10648                    listCut.add(array);
10649                }
10650            }
10651            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10652        }
10653
10654        public final void addProvider(PackageParser.Provider p) {
10655            if (mProviders.containsKey(p.getComponentName())) {
10656                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10657                return;
10658            }
10659
10660            mProviders.put(p.getComponentName(), p);
10661            if (DEBUG_SHOW_INFO) {
10662                Log.v(TAG, "  "
10663                        + (p.info.nonLocalizedLabel != null
10664                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10665                Log.v(TAG, "    Class=" + p.info.name);
10666            }
10667            final int NI = p.intents.size();
10668            int j;
10669            for (j = 0; j < NI; j++) {
10670                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10671                if (DEBUG_SHOW_INFO) {
10672                    Log.v(TAG, "    IntentFilter:");
10673                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10674                }
10675                if (!intent.debugCheck()) {
10676                    Log.w(TAG, "==> For Provider " + p.info.name);
10677                }
10678                addFilter(intent);
10679            }
10680        }
10681
10682        public final void removeProvider(PackageParser.Provider p) {
10683            mProviders.remove(p.getComponentName());
10684            if (DEBUG_SHOW_INFO) {
10685                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10686                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10687                Log.v(TAG, "    Class=" + p.info.name);
10688            }
10689            final int NI = p.intents.size();
10690            int j;
10691            for (j = 0; j < NI; j++) {
10692                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10693                if (DEBUG_SHOW_INFO) {
10694                    Log.v(TAG, "    IntentFilter:");
10695                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10696                }
10697                removeFilter(intent);
10698            }
10699        }
10700
10701        @Override
10702        protected boolean allowFilterResult(
10703                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10704            ProviderInfo filterPi = filter.provider.info;
10705            for (int i = dest.size() - 1; i >= 0; i--) {
10706                ProviderInfo destPi = dest.get(i).providerInfo;
10707                if (destPi.name == filterPi.name
10708                        && destPi.packageName == filterPi.packageName) {
10709                    return false;
10710                }
10711            }
10712            return true;
10713        }
10714
10715        @Override
10716        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10717            return new PackageParser.ProviderIntentInfo[size];
10718        }
10719
10720        @Override
10721        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10722            if (!sUserManager.exists(userId))
10723                return true;
10724            PackageParser.Package p = filter.provider.owner;
10725            if (p != null) {
10726                PackageSetting ps = (PackageSetting) p.mExtras;
10727                if (ps != null) {
10728                    // System apps are never considered stopped for purposes of
10729                    // filtering, because there may be no way for the user to
10730                    // actually re-launch them.
10731                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10732                            && ps.getStopped(userId);
10733                }
10734            }
10735            return false;
10736        }
10737
10738        @Override
10739        protected boolean isPackageForFilter(String packageName,
10740                PackageParser.ProviderIntentInfo info) {
10741            return packageName.equals(info.provider.owner.packageName);
10742        }
10743
10744        @Override
10745        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10746                int match, int userId) {
10747            if (!sUserManager.exists(userId))
10748                return null;
10749            final PackageParser.ProviderIntentInfo info = filter;
10750            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10751                return null;
10752            }
10753            final PackageParser.Provider provider = info.provider;
10754            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10755            if (ps == null) {
10756                return null;
10757            }
10758            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10759                    ps.readUserState(userId), userId);
10760            if (pi == null) {
10761                return null;
10762            }
10763            final ResolveInfo res = new ResolveInfo();
10764            res.providerInfo = pi;
10765            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10766                res.filter = filter;
10767            }
10768            res.priority = info.getPriority();
10769            res.preferredOrder = provider.owner.mPreferredOrder;
10770            res.match = match;
10771            res.isDefault = info.hasDefault;
10772            res.labelRes = info.labelRes;
10773            res.nonLocalizedLabel = info.nonLocalizedLabel;
10774            res.icon = info.icon;
10775            res.system = res.providerInfo.applicationInfo.isSystemApp();
10776            return res;
10777        }
10778
10779        @Override
10780        protected void sortResults(List<ResolveInfo> results) {
10781            Collections.sort(results, mResolvePrioritySorter);
10782        }
10783
10784        @Override
10785        protected void dumpFilter(PrintWriter out, String prefix,
10786                PackageParser.ProviderIntentInfo filter) {
10787            out.print(prefix);
10788            out.print(
10789                    Integer.toHexString(System.identityHashCode(filter.provider)));
10790            out.print(' ');
10791            filter.provider.printComponentShortName(out);
10792            out.print(" filter ");
10793            out.println(Integer.toHexString(System.identityHashCode(filter)));
10794        }
10795
10796        @Override
10797        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10798            return filter.provider;
10799        }
10800
10801        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10802            PackageParser.Provider provider = (PackageParser.Provider)label;
10803            out.print(prefix); out.print(
10804                    Integer.toHexString(System.identityHashCode(provider)));
10805                    out.print(' ');
10806                    provider.printComponentShortName(out);
10807            if (count > 1) {
10808                out.print(" ("); out.print(count); out.print(" filters)");
10809            }
10810            out.println();
10811        }
10812
10813        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10814                = new ArrayMap<ComponentName, PackageParser.Provider>();
10815        private int mFlags;
10816    }
10817
10818    private static final class EphemeralIntentResolver
10819            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10820        @Override
10821        protected EphemeralResolveIntentInfo[] newArray(int size) {
10822            return new EphemeralResolveIntentInfo[size];
10823        }
10824
10825        @Override
10826        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10827            return true;
10828        }
10829
10830        @Override
10831        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10832                int userId) {
10833            if (!sUserManager.exists(userId)) {
10834                return null;
10835            }
10836            return info.getEphemeralResolveInfo();
10837        }
10838    }
10839
10840    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10841            new Comparator<ResolveInfo>() {
10842        public int compare(ResolveInfo r1, ResolveInfo r2) {
10843            int v1 = r1.priority;
10844            int v2 = r2.priority;
10845            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10846            if (v1 != v2) {
10847                return (v1 > v2) ? -1 : 1;
10848            }
10849            v1 = r1.preferredOrder;
10850            v2 = r2.preferredOrder;
10851            if (v1 != v2) {
10852                return (v1 > v2) ? -1 : 1;
10853            }
10854            if (r1.isDefault != r2.isDefault) {
10855                return r1.isDefault ? -1 : 1;
10856            }
10857            v1 = r1.match;
10858            v2 = r2.match;
10859            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10860            if (v1 != v2) {
10861                return (v1 > v2) ? -1 : 1;
10862            }
10863            if (r1.system != r2.system) {
10864                return r1.system ? -1 : 1;
10865            }
10866            if (r1.activityInfo != null) {
10867                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10868            }
10869            if (r1.serviceInfo != null) {
10870                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10871            }
10872            if (r1.providerInfo != null) {
10873                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10874            }
10875            return 0;
10876        }
10877    };
10878
10879    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10880            new Comparator<ProviderInfo>() {
10881        public int compare(ProviderInfo p1, ProviderInfo p2) {
10882            final int v1 = p1.initOrder;
10883            final int v2 = p2.initOrder;
10884            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10885        }
10886    };
10887
10888    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10889            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10890            final int[] userIds) {
10891        mHandler.post(new Runnable() {
10892            @Override
10893            public void run() {
10894                try {
10895                    final IActivityManager am = ActivityManagerNative.getDefault();
10896                    if (am == null) return;
10897                    final int[] resolvedUserIds;
10898                    if (userIds == null) {
10899                        resolvedUserIds = am.getRunningUserIds();
10900                    } else {
10901                        resolvedUserIds = userIds;
10902                    }
10903                    for (int id : resolvedUserIds) {
10904                        final Intent intent = new Intent(action,
10905                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10906                        if (extras != null) {
10907                            intent.putExtras(extras);
10908                        }
10909                        if (targetPkg != null) {
10910                            intent.setPackage(targetPkg);
10911                        }
10912                        // Modify the UID when posting to other users
10913                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10914                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10915                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10916                            intent.putExtra(Intent.EXTRA_UID, uid);
10917                        }
10918                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10919                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10920                        if (DEBUG_BROADCASTS) {
10921                            RuntimeException here = new RuntimeException("here");
10922                            here.fillInStackTrace();
10923                            Slog.d(TAG, "Sending to user " + id + ": "
10924                                    + intent.toShortString(false, true, false, false)
10925                                    + " " + intent.getExtras(), here);
10926                        }
10927                        am.broadcastIntent(null, intent, null, finishedReceiver,
10928                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10929                                null, finishedReceiver != null, false, id);
10930                    }
10931                } catch (RemoteException ex) {
10932                }
10933            }
10934        });
10935    }
10936
10937    /**
10938     * Check if the external storage media is available. This is true if there
10939     * is a mounted external storage medium or if the external storage is
10940     * emulated.
10941     */
10942    private boolean isExternalMediaAvailable() {
10943        return mMediaMounted || Environment.isExternalStorageEmulated();
10944    }
10945
10946    @Override
10947    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10948        // writer
10949        synchronized (mPackages) {
10950            if (!isExternalMediaAvailable()) {
10951                // If the external storage is no longer mounted at this point,
10952                // the caller may not have been able to delete all of this
10953                // packages files and can not delete any more.  Bail.
10954                return null;
10955            }
10956            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10957            if (lastPackage != null) {
10958                pkgs.remove(lastPackage);
10959            }
10960            if (pkgs.size() > 0) {
10961                return pkgs.get(0);
10962            }
10963        }
10964        return null;
10965    }
10966
10967    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10968        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10969                userId, andCode ? 1 : 0, packageName);
10970        if (mSystemReady) {
10971            msg.sendToTarget();
10972        } else {
10973            if (mPostSystemReadyMessages == null) {
10974                mPostSystemReadyMessages = new ArrayList<>();
10975            }
10976            mPostSystemReadyMessages.add(msg);
10977        }
10978    }
10979
10980    void startCleaningPackages() {
10981        // reader
10982        if (!isExternalMediaAvailable()) {
10983            return;
10984        }
10985        synchronized (mPackages) {
10986            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10987                return;
10988            }
10989        }
10990        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10991        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10992        IActivityManager am = ActivityManagerNative.getDefault();
10993        if (am != null) {
10994            try {
10995                am.startService(null, intent, null, mContext.getOpPackageName(),
10996                        UserHandle.USER_SYSTEM);
10997            } catch (RemoteException e) {
10998            }
10999        }
11000    }
11001
11002    @Override
11003    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11004            int installFlags, String installerPackageName, int userId) {
11005        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11006
11007        final int callingUid = Binder.getCallingUid();
11008        enforceCrossUserPermission(callingUid, userId,
11009                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11010
11011        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11012            try {
11013                if (observer != null) {
11014                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11015                }
11016            } catch (RemoteException re) {
11017            }
11018            return;
11019        }
11020
11021        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11022            installFlags |= PackageManager.INSTALL_FROM_ADB;
11023
11024        } else {
11025            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11026            // about installerPackageName.
11027
11028            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11029            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11030        }
11031
11032        UserHandle user;
11033        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11034            user = UserHandle.ALL;
11035        } else {
11036            user = new UserHandle(userId);
11037        }
11038
11039        // Only system components can circumvent runtime permissions when installing.
11040        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11041                && mContext.checkCallingOrSelfPermission(Manifest.permission
11042                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11043            throw new SecurityException("You need the "
11044                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11045                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11046        }
11047
11048        final File originFile = new File(originPath);
11049        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11050
11051        final Message msg = mHandler.obtainMessage(INIT_COPY);
11052        final VerificationInfo verificationInfo = new VerificationInfo(
11053                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11054        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11055                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11056                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11057                null /*certificates*/);
11058        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11059        msg.obj = params;
11060
11061        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11062                System.identityHashCode(msg.obj));
11063        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11064                System.identityHashCode(msg.obj));
11065
11066        mHandler.sendMessage(msg);
11067    }
11068
11069    void installStage(String packageName, File stagedDir, String stagedCid,
11070            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11071            String installerPackageName, int installerUid, UserHandle user,
11072            Certificate[][] certificates) {
11073        if (DEBUG_EPHEMERAL) {
11074            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11075                Slog.d(TAG, "Ephemeral install of " + packageName);
11076            }
11077        }
11078        final VerificationInfo verificationInfo = new VerificationInfo(
11079                sessionParams.originatingUri, sessionParams.referrerUri,
11080                sessionParams.originatingUid, installerUid);
11081
11082        final OriginInfo origin;
11083        if (stagedDir != null) {
11084            origin = OriginInfo.fromStagedFile(stagedDir);
11085        } else {
11086            origin = OriginInfo.fromStagedContainer(stagedCid);
11087        }
11088
11089        final Message msg = mHandler.obtainMessage(INIT_COPY);
11090        final InstallParams params = new InstallParams(origin, null, observer,
11091                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11092                verificationInfo, user, sessionParams.abiOverride,
11093                sessionParams.grantedRuntimePermissions, certificates);
11094        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11095        msg.obj = params;
11096
11097        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11098                System.identityHashCode(msg.obj));
11099        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11100                System.identityHashCode(msg.obj));
11101
11102        mHandler.sendMessage(msg);
11103    }
11104
11105    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11106            int userId) {
11107        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11108        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11109    }
11110
11111    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11112            int appId, int userId) {
11113        Bundle extras = new Bundle(1);
11114        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11115
11116        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11117                packageName, extras, 0, null, null, new int[] {userId});
11118        try {
11119            IActivityManager am = ActivityManagerNative.getDefault();
11120            if (isSystem && am.isUserRunning(userId, 0)) {
11121                // The just-installed/enabled app is bundled on the system, so presumed
11122                // to be able to run automatically without needing an explicit launch.
11123                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11124                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11125                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11126                        .setPackage(packageName);
11127                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11128                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11129            }
11130        } catch (RemoteException e) {
11131            // shouldn't happen
11132            Slog.w(TAG, "Unable to bootstrap installed package", e);
11133        }
11134    }
11135
11136    @Override
11137    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11138            int userId) {
11139        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11140        PackageSetting pkgSetting;
11141        final int uid = Binder.getCallingUid();
11142        enforceCrossUserPermission(uid, userId,
11143                true /* requireFullPermission */, true /* checkShell */,
11144                "setApplicationHiddenSetting for user " + userId);
11145
11146        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11147            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11148            return false;
11149        }
11150
11151        long callingId = Binder.clearCallingIdentity();
11152        try {
11153            boolean sendAdded = false;
11154            boolean sendRemoved = false;
11155            // writer
11156            synchronized (mPackages) {
11157                pkgSetting = mSettings.mPackages.get(packageName);
11158                if (pkgSetting == null) {
11159                    return false;
11160                }
11161                if (pkgSetting.getHidden(userId) != hidden) {
11162                    pkgSetting.setHidden(hidden, userId);
11163                    mSettings.writePackageRestrictionsLPr(userId);
11164                    if (hidden) {
11165                        sendRemoved = true;
11166                    } else {
11167                        sendAdded = true;
11168                    }
11169                }
11170            }
11171            if (sendAdded) {
11172                sendPackageAddedForUser(packageName, pkgSetting, userId);
11173                return true;
11174            }
11175            if (sendRemoved) {
11176                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11177                        "hiding pkg");
11178                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11179                return true;
11180            }
11181        } finally {
11182            Binder.restoreCallingIdentity(callingId);
11183        }
11184        return false;
11185    }
11186
11187    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11188            int userId) {
11189        final PackageRemovedInfo info = new PackageRemovedInfo();
11190        info.removedPackage = packageName;
11191        info.removedUsers = new int[] {userId};
11192        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11193        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11194    }
11195
11196    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11197        if (pkgList.length > 0) {
11198            Bundle extras = new Bundle(1);
11199            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11200
11201            sendPackageBroadcast(
11202                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11203                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11204                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11205                    new int[] {userId});
11206        }
11207    }
11208
11209    /**
11210     * Returns true if application is not found or there was an error. Otherwise it returns
11211     * the hidden state of the package for the given user.
11212     */
11213    @Override
11214    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11215        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11216        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11217                true /* requireFullPermission */, false /* checkShell */,
11218                "getApplicationHidden for user " + userId);
11219        PackageSetting pkgSetting;
11220        long callingId = Binder.clearCallingIdentity();
11221        try {
11222            // writer
11223            synchronized (mPackages) {
11224                pkgSetting = mSettings.mPackages.get(packageName);
11225                if (pkgSetting == null) {
11226                    return true;
11227                }
11228                return pkgSetting.getHidden(userId);
11229            }
11230        } finally {
11231            Binder.restoreCallingIdentity(callingId);
11232        }
11233    }
11234
11235    /**
11236     * @hide
11237     */
11238    @Override
11239    public int installExistingPackageAsUser(String packageName, int userId) {
11240        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11241                null);
11242        PackageSetting pkgSetting;
11243        final int uid = Binder.getCallingUid();
11244        enforceCrossUserPermission(uid, userId,
11245                true /* requireFullPermission */, true /* checkShell */,
11246                "installExistingPackage for user " + userId);
11247        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11248            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11249        }
11250
11251        long callingId = Binder.clearCallingIdentity();
11252        try {
11253            boolean installed = false;
11254
11255            // writer
11256            synchronized (mPackages) {
11257                pkgSetting = mSettings.mPackages.get(packageName);
11258                if (pkgSetting == null) {
11259                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11260                }
11261                if (!pkgSetting.getInstalled(userId)) {
11262                    pkgSetting.setInstalled(true, userId);
11263                    pkgSetting.setHidden(false, userId);
11264                    mSettings.writePackageRestrictionsLPr(userId);
11265                    installed = true;
11266                }
11267            }
11268
11269            if (installed) {
11270                if (pkgSetting.pkg != null) {
11271                    synchronized (mInstallLock) {
11272                        // We don't need to freeze for a brand new install
11273                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11274                    }
11275                }
11276                sendPackageAddedForUser(packageName, pkgSetting, userId);
11277            }
11278        } finally {
11279            Binder.restoreCallingIdentity(callingId);
11280        }
11281
11282        return PackageManager.INSTALL_SUCCEEDED;
11283    }
11284
11285    boolean isUserRestricted(int userId, String restrictionKey) {
11286        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11287        if (restrictions.getBoolean(restrictionKey, false)) {
11288            Log.w(TAG, "User is restricted: " + restrictionKey);
11289            return true;
11290        }
11291        return false;
11292    }
11293
11294    @Override
11295    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11296            int userId) {
11297        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11299                true /* requireFullPermission */, true /* checkShell */,
11300                "setPackagesSuspended for user " + userId);
11301
11302        if (ArrayUtils.isEmpty(packageNames)) {
11303            return packageNames;
11304        }
11305
11306        // List of package names for whom the suspended state has changed.
11307        List<String> changedPackages = new ArrayList<>(packageNames.length);
11308        // List of package names for whom the suspended state is not set as requested in this
11309        // method.
11310        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11311        for (int i = 0; i < packageNames.length; i++) {
11312            String packageName = packageNames[i];
11313            long callingId = Binder.clearCallingIdentity();
11314            try {
11315                boolean changed = false;
11316                final int appId;
11317                synchronized (mPackages) {
11318                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11319                    if (pkgSetting == null) {
11320                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11321                                + "\". Skipping suspending/un-suspending.");
11322                        unactionedPackages.add(packageName);
11323                        continue;
11324                    }
11325                    appId = pkgSetting.appId;
11326                    if (pkgSetting.getSuspended(userId) != suspended) {
11327                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11328                            unactionedPackages.add(packageName);
11329                            continue;
11330                        }
11331                        pkgSetting.setSuspended(suspended, userId);
11332                        mSettings.writePackageRestrictionsLPr(userId);
11333                        changed = true;
11334                        changedPackages.add(packageName);
11335                    }
11336                }
11337
11338                if (changed && suspended) {
11339                    killApplication(packageName, UserHandle.getUid(userId, appId),
11340                            "suspending package");
11341                }
11342            } finally {
11343                Binder.restoreCallingIdentity(callingId);
11344            }
11345        }
11346
11347        if (!changedPackages.isEmpty()) {
11348            sendPackagesSuspendedForUser(changedPackages.toArray(
11349                    new String[changedPackages.size()]), userId, suspended);
11350        }
11351
11352        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11353    }
11354
11355    @Override
11356    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11357        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11358                true /* requireFullPermission */, false /* checkShell */,
11359                "isPackageSuspendedForUser for user " + userId);
11360        synchronized (mPackages) {
11361            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11362            if (pkgSetting == null) {
11363                throw new IllegalArgumentException("Unknown target package: " + packageName);
11364            }
11365            return pkgSetting.getSuspended(userId);
11366        }
11367    }
11368
11369    /**
11370     * TODO: cache and disallow blocking the active dialer.
11371     *
11372     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11373     */
11374    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11375        if (isPackageDeviceAdmin(packageName, userId)) {
11376            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11377                    + "\": has an active device admin");
11378            return false;
11379        }
11380
11381        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11382        if (packageName.equals(activeLauncherPackageName)) {
11383            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11384                    + "\": contains the active launcher");
11385            return false;
11386        }
11387
11388        if (packageName.equals(mRequiredInstallerPackage)) {
11389            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11390                    + "\": required for package installation");
11391            return false;
11392        }
11393
11394        if (packageName.equals(mRequiredVerifierPackage)) {
11395            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11396                    + "\": required for package verification");
11397            return false;
11398        }
11399
11400        final PackageParser.Package pkg = mPackages.get(packageName);
11401        if (pkg != null && isPrivilegedApp(pkg)) {
11402            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11403                    + "\": is a privileged app");
11404            return false;
11405        }
11406
11407        return true;
11408    }
11409
11410    private String getActiveLauncherPackageName(int userId) {
11411        Intent intent = new Intent(Intent.ACTION_MAIN);
11412        intent.addCategory(Intent.CATEGORY_HOME);
11413        ResolveInfo resolveInfo = resolveIntent(
11414                intent,
11415                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11416                PackageManager.MATCH_DEFAULT_ONLY,
11417                userId);
11418
11419        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11420    }
11421
11422    @Override
11423    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11424        mContext.enforceCallingOrSelfPermission(
11425                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11426                "Only package verification agents can verify applications");
11427
11428        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11429        final PackageVerificationResponse response = new PackageVerificationResponse(
11430                verificationCode, Binder.getCallingUid());
11431        msg.arg1 = id;
11432        msg.obj = response;
11433        mHandler.sendMessage(msg);
11434    }
11435
11436    @Override
11437    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11438            long millisecondsToDelay) {
11439        mContext.enforceCallingOrSelfPermission(
11440                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11441                "Only package verification agents can extend verification timeouts");
11442
11443        final PackageVerificationState state = mPendingVerification.get(id);
11444        final PackageVerificationResponse response = new PackageVerificationResponse(
11445                verificationCodeAtTimeout, Binder.getCallingUid());
11446
11447        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11448            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11449        }
11450        if (millisecondsToDelay < 0) {
11451            millisecondsToDelay = 0;
11452        }
11453        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11454                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11455            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11456        }
11457
11458        if ((state != null) && !state.timeoutExtended()) {
11459            state.extendTimeout();
11460
11461            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11462            msg.arg1 = id;
11463            msg.obj = response;
11464            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11465        }
11466    }
11467
11468    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11469            int verificationCode, UserHandle user) {
11470        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11471        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11472        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11473        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11474        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11475
11476        mContext.sendBroadcastAsUser(intent, user,
11477                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11478    }
11479
11480    private ComponentName matchComponentForVerifier(String packageName,
11481            List<ResolveInfo> receivers) {
11482        ActivityInfo targetReceiver = null;
11483
11484        final int NR = receivers.size();
11485        for (int i = 0; i < NR; i++) {
11486            final ResolveInfo info = receivers.get(i);
11487            if (info.activityInfo == null) {
11488                continue;
11489            }
11490
11491            if (packageName.equals(info.activityInfo.packageName)) {
11492                targetReceiver = info.activityInfo;
11493                break;
11494            }
11495        }
11496
11497        if (targetReceiver == null) {
11498            return null;
11499        }
11500
11501        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11502    }
11503
11504    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11505            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11506        if (pkgInfo.verifiers.length == 0) {
11507            return null;
11508        }
11509
11510        final int N = pkgInfo.verifiers.length;
11511        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11512        for (int i = 0; i < N; i++) {
11513            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11514
11515            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11516                    receivers);
11517            if (comp == null) {
11518                continue;
11519            }
11520
11521            final int verifierUid = getUidForVerifier(verifierInfo);
11522            if (verifierUid == -1) {
11523                continue;
11524            }
11525
11526            if (DEBUG_VERIFY) {
11527                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11528                        + " with the correct signature");
11529            }
11530            sufficientVerifiers.add(comp);
11531            verificationState.addSufficientVerifier(verifierUid);
11532        }
11533
11534        return sufficientVerifiers;
11535    }
11536
11537    private int getUidForVerifier(VerifierInfo verifierInfo) {
11538        synchronized (mPackages) {
11539            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11540            if (pkg == null) {
11541                return -1;
11542            } else if (pkg.mSignatures.length != 1) {
11543                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11544                        + " has more than one signature; ignoring");
11545                return -1;
11546            }
11547
11548            /*
11549             * If the public key of the package's signature does not match
11550             * our expected public key, then this is a different package and
11551             * we should skip.
11552             */
11553
11554            final byte[] expectedPublicKey;
11555            try {
11556                final Signature verifierSig = pkg.mSignatures[0];
11557                final PublicKey publicKey = verifierSig.getPublicKey();
11558                expectedPublicKey = publicKey.getEncoded();
11559            } catch (CertificateException e) {
11560                return -1;
11561            }
11562
11563            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11564
11565            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11566                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11567                        + " does not have the expected public key; ignoring");
11568                return -1;
11569            }
11570
11571            return pkg.applicationInfo.uid;
11572        }
11573    }
11574
11575    @Override
11576    public void finishPackageInstall(int token) {
11577        enforceSystemOrRoot("Only the system is allowed to finish installs");
11578
11579        if (DEBUG_INSTALL) {
11580            Slog.v(TAG, "BM finishing package install for " + token);
11581        }
11582        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11583
11584        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11585        mHandler.sendMessage(msg);
11586    }
11587
11588    /**
11589     * Get the verification agent timeout.
11590     *
11591     * @return verification timeout in milliseconds
11592     */
11593    private long getVerificationTimeout() {
11594        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11595                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11596                DEFAULT_VERIFICATION_TIMEOUT);
11597    }
11598
11599    /**
11600     * Get the default verification agent response code.
11601     *
11602     * @return default verification response code
11603     */
11604    private int getDefaultVerificationResponse() {
11605        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11606                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11607                DEFAULT_VERIFICATION_RESPONSE);
11608    }
11609
11610    /**
11611     * Check whether or not package verification has been enabled.
11612     *
11613     * @return true if verification should be performed
11614     */
11615    private boolean isVerificationEnabled(int userId, int installFlags) {
11616        if (!DEFAULT_VERIFY_ENABLE) {
11617            return false;
11618        }
11619        // Ephemeral apps don't get the full verification treatment
11620        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11621            if (DEBUG_EPHEMERAL) {
11622                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11623            }
11624            return false;
11625        }
11626
11627        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11628
11629        // Check if installing from ADB
11630        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11631            // Do not run verification in a test harness environment
11632            if (ActivityManager.isRunningInTestHarness()) {
11633                return false;
11634            }
11635            if (ensureVerifyAppsEnabled) {
11636                return true;
11637            }
11638            // Check if the developer does not want package verification for ADB installs
11639            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11640                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11641                return false;
11642            }
11643        }
11644
11645        if (ensureVerifyAppsEnabled) {
11646            return true;
11647        }
11648
11649        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11650                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11651    }
11652
11653    @Override
11654    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11655            throws RemoteException {
11656        mContext.enforceCallingOrSelfPermission(
11657                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11658                "Only intentfilter verification agents can verify applications");
11659
11660        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11661        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11662                Binder.getCallingUid(), verificationCode, failedDomains);
11663        msg.arg1 = id;
11664        msg.obj = response;
11665        mHandler.sendMessage(msg);
11666    }
11667
11668    @Override
11669    public int getIntentVerificationStatus(String packageName, int userId) {
11670        synchronized (mPackages) {
11671            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11672        }
11673    }
11674
11675    @Override
11676    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11677        mContext.enforceCallingOrSelfPermission(
11678                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11679
11680        boolean result = false;
11681        synchronized (mPackages) {
11682            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11683        }
11684        if (result) {
11685            scheduleWritePackageRestrictionsLocked(userId);
11686        }
11687        return result;
11688    }
11689
11690    @Override
11691    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11692            String packageName) {
11693        synchronized (mPackages) {
11694            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11695        }
11696    }
11697
11698    @Override
11699    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11700        if (TextUtils.isEmpty(packageName)) {
11701            return ParceledListSlice.emptyList();
11702        }
11703        synchronized (mPackages) {
11704            PackageParser.Package pkg = mPackages.get(packageName);
11705            if (pkg == null || pkg.activities == null) {
11706                return ParceledListSlice.emptyList();
11707            }
11708            final int count = pkg.activities.size();
11709            ArrayList<IntentFilter> result = new ArrayList<>();
11710            for (int n=0; n<count; n++) {
11711                PackageParser.Activity activity = pkg.activities.get(n);
11712                if (activity.intents != null && activity.intents.size() > 0) {
11713                    result.addAll(activity.intents);
11714                }
11715            }
11716            return new ParceledListSlice<>(result);
11717        }
11718    }
11719
11720    @Override
11721    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11722        mContext.enforceCallingOrSelfPermission(
11723                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11724
11725        synchronized (mPackages) {
11726            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11727            if (packageName != null) {
11728                result |= updateIntentVerificationStatus(packageName,
11729                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11730                        userId);
11731                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11732                        packageName, userId);
11733            }
11734            return result;
11735        }
11736    }
11737
11738    @Override
11739    public String getDefaultBrowserPackageName(int userId) {
11740        synchronized (mPackages) {
11741            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11742        }
11743    }
11744
11745    /**
11746     * Get the "allow unknown sources" setting.
11747     *
11748     * @return the current "allow unknown sources" setting
11749     */
11750    private int getUnknownSourcesSettings() {
11751        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11752                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11753                -1);
11754    }
11755
11756    @Override
11757    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11758        final int uid = Binder.getCallingUid();
11759        // writer
11760        synchronized (mPackages) {
11761            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11762            if (targetPackageSetting == null) {
11763                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11764            }
11765
11766            PackageSetting installerPackageSetting;
11767            if (installerPackageName != null) {
11768                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11769                if (installerPackageSetting == null) {
11770                    throw new IllegalArgumentException("Unknown installer package: "
11771                            + installerPackageName);
11772                }
11773            } else {
11774                installerPackageSetting = null;
11775            }
11776
11777            Signature[] callerSignature;
11778            Object obj = mSettings.getUserIdLPr(uid);
11779            if (obj != null) {
11780                if (obj instanceof SharedUserSetting) {
11781                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11782                } else if (obj instanceof PackageSetting) {
11783                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11784                } else {
11785                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11786                }
11787            } else {
11788                throw new SecurityException("Unknown calling UID: " + uid);
11789            }
11790
11791            // Verify: can't set installerPackageName to a package that is
11792            // not signed with the same cert as the caller.
11793            if (installerPackageSetting != null) {
11794                if (compareSignatures(callerSignature,
11795                        installerPackageSetting.signatures.mSignatures)
11796                        != PackageManager.SIGNATURE_MATCH) {
11797                    throw new SecurityException(
11798                            "Caller does not have same cert as new installer package "
11799                            + installerPackageName);
11800                }
11801            }
11802
11803            // Verify: if target already has an installer package, it must
11804            // be signed with the same cert as the caller.
11805            if (targetPackageSetting.installerPackageName != null) {
11806                PackageSetting setting = mSettings.mPackages.get(
11807                        targetPackageSetting.installerPackageName);
11808                // If the currently set package isn't valid, then it's always
11809                // okay to change it.
11810                if (setting != null) {
11811                    if (compareSignatures(callerSignature,
11812                            setting.signatures.mSignatures)
11813                            != PackageManager.SIGNATURE_MATCH) {
11814                        throw new SecurityException(
11815                                "Caller does not have same cert as old installer package "
11816                                + targetPackageSetting.installerPackageName);
11817                    }
11818                }
11819            }
11820
11821            // Okay!
11822            targetPackageSetting.installerPackageName = installerPackageName;
11823            if (installerPackageName != null) {
11824                mSettings.mInstallerPackages.add(installerPackageName);
11825            }
11826            scheduleWriteSettingsLocked();
11827        }
11828    }
11829
11830    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11831        // Queue up an async operation since the package installation may take a little while.
11832        mHandler.post(new Runnable() {
11833            public void run() {
11834                mHandler.removeCallbacks(this);
11835                 // Result object to be returned
11836                PackageInstalledInfo res = new PackageInstalledInfo();
11837                res.setReturnCode(currentStatus);
11838                res.uid = -1;
11839                res.pkg = null;
11840                res.removedInfo = null;
11841                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11842                    args.doPreInstall(res.returnCode);
11843                    synchronized (mInstallLock) {
11844                        installPackageTracedLI(args, res);
11845                    }
11846                    args.doPostInstall(res.returnCode, res.uid);
11847                }
11848
11849                // A restore should be performed at this point if (a) the install
11850                // succeeded, (b) the operation is not an update, and (c) the new
11851                // package has not opted out of backup participation.
11852                final boolean update = res.removedInfo != null
11853                        && res.removedInfo.removedPackage != null;
11854                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11855                boolean doRestore = !update
11856                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11857
11858                // Set up the post-install work request bookkeeping.  This will be used
11859                // and cleaned up by the post-install event handling regardless of whether
11860                // there's a restore pass performed.  Token values are >= 1.
11861                int token;
11862                if (mNextInstallToken < 0) mNextInstallToken = 1;
11863                token = mNextInstallToken++;
11864
11865                PostInstallData data = new PostInstallData(args, res);
11866                mRunningInstalls.put(token, data);
11867                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11868
11869                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11870                    // Pass responsibility to the Backup Manager.  It will perform a
11871                    // restore if appropriate, then pass responsibility back to the
11872                    // Package Manager to run the post-install observer callbacks
11873                    // and broadcasts.
11874                    IBackupManager bm = IBackupManager.Stub.asInterface(
11875                            ServiceManager.getService(Context.BACKUP_SERVICE));
11876                    if (bm != null) {
11877                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11878                                + " to BM for possible restore");
11879                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11880                        try {
11881                            // TODO: http://b/22388012
11882                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11883                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11884                            } else {
11885                                doRestore = false;
11886                            }
11887                        } catch (RemoteException e) {
11888                            // can't happen; the backup manager is local
11889                        } catch (Exception e) {
11890                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11891                            doRestore = false;
11892                        }
11893                    } else {
11894                        Slog.e(TAG, "Backup Manager not found!");
11895                        doRestore = false;
11896                    }
11897                }
11898
11899                if (!doRestore) {
11900                    // No restore possible, or the Backup Manager was mysteriously not
11901                    // available -- just fire the post-install work request directly.
11902                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11903
11904                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11905
11906                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11907                    mHandler.sendMessage(msg);
11908                }
11909            }
11910        });
11911    }
11912
11913    private abstract class HandlerParams {
11914        private static final int MAX_RETRIES = 4;
11915
11916        /**
11917         * Number of times startCopy() has been attempted and had a non-fatal
11918         * error.
11919         */
11920        private int mRetries = 0;
11921
11922        /** User handle for the user requesting the information or installation. */
11923        private final UserHandle mUser;
11924        String traceMethod;
11925        int traceCookie;
11926
11927        HandlerParams(UserHandle user) {
11928            mUser = user;
11929        }
11930
11931        UserHandle getUser() {
11932            return mUser;
11933        }
11934
11935        HandlerParams setTraceMethod(String traceMethod) {
11936            this.traceMethod = traceMethod;
11937            return this;
11938        }
11939
11940        HandlerParams setTraceCookie(int traceCookie) {
11941            this.traceCookie = traceCookie;
11942            return this;
11943        }
11944
11945        final boolean startCopy() {
11946            boolean res;
11947            try {
11948                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11949
11950                if (++mRetries > MAX_RETRIES) {
11951                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11952                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11953                    handleServiceError();
11954                    return false;
11955                } else {
11956                    handleStartCopy();
11957                    res = true;
11958                }
11959            } catch (RemoteException e) {
11960                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11961                mHandler.sendEmptyMessage(MCS_RECONNECT);
11962                res = false;
11963            }
11964            handleReturnCode();
11965            return res;
11966        }
11967
11968        final void serviceError() {
11969            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11970            handleServiceError();
11971            handleReturnCode();
11972        }
11973
11974        abstract void handleStartCopy() throws RemoteException;
11975        abstract void handleServiceError();
11976        abstract void handleReturnCode();
11977    }
11978
11979    class MeasureParams extends HandlerParams {
11980        private final PackageStats mStats;
11981        private boolean mSuccess;
11982
11983        private final IPackageStatsObserver mObserver;
11984
11985        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11986            super(new UserHandle(stats.userHandle));
11987            mObserver = observer;
11988            mStats = stats;
11989        }
11990
11991        @Override
11992        public String toString() {
11993            return "MeasureParams{"
11994                + Integer.toHexString(System.identityHashCode(this))
11995                + " " + mStats.packageName + "}";
11996        }
11997
11998        @Override
11999        void handleStartCopy() throws RemoteException {
12000            synchronized (mInstallLock) {
12001                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12002            }
12003
12004            if (mSuccess) {
12005                final boolean mounted;
12006                if (Environment.isExternalStorageEmulated()) {
12007                    mounted = true;
12008                } else {
12009                    final String status = Environment.getExternalStorageState();
12010                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12011                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12012                }
12013
12014                if (mounted) {
12015                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12016
12017                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12018                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12019
12020                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12021                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12022
12023                    // Always subtract cache size, since it's a subdirectory
12024                    mStats.externalDataSize -= mStats.externalCacheSize;
12025
12026                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12027                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12028
12029                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12030                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12031                }
12032            }
12033        }
12034
12035        @Override
12036        void handleReturnCode() {
12037            if (mObserver != null) {
12038                try {
12039                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12040                } catch (RemoteException e) {
12041                    Slog.i(TAG, "Observer no longer exists.");
12042                }
12043            }
12044        }
12045
12046        @Override
12047        void handleServiceError() {
12048            Slog.e(TAG, "Could not measure application " + mStats.packageName
12049                            + " external storage");
12050        }
12051    }
12052
12053    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12054            throws RemoteException {
12055        long result = 0;
12056        for (File path : paths) {
12057            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12058        }
12059        return result;
12060    }
12061
12062    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12063        for (File path : paths) {
12064            try {
12065                mcs.clearDirectory(path.getAbsolutePath());
12066            } catch (RemoteException e) {
12067            }
12068        }
12069    }
12070
12071    static class OriginInfo {
12072        /**
12073         * Location where install is coming from, before it has been
12074         * copied/renamed into place. This could be a single monolithic APK
12075         * file, or a cluster directory. This location may be untrusted.
12076         */
12077        final File file;
12078        final String cid;
12079
12080        /**
12081         * Flag indicating that {@link #file} or {@link #cid} has already been
12082         * staged, meaning downstream users don't need to defensively copy the
12083         * contents.
12084         */
12085        final boolean staged;
12086
12087        /**
12088         * Flag indicating that {@link #file} or {@link #cid} is an already
12089         * installed app that is being moved.
12090         */
12091        final boolean existing;
12092
12093        final String resolvedPath;
12094        final File resolvedFile;
12095
12096        static OriginInfo fromNothing() {
12097            return new OriginInfo(null, null, false, false);
12098        }
12099
12100        static OriginInfo fromUntrustedFile(File file) {
12101            return new OriginInfo(file, null, false, false);
12102        }
12103
12104        static OriginInfo fromExistingFile(File file) {
12105            return new OriginInfo(file, null, false, true);
12106        }
12107
12108        static OriginInfo fromStagedFile(File file) {
12109            return new OriginInfo(file, null, true, false);
12110        }
12111
12112        static OriginInfo fromStagedContainer(String cid) {
12113            return new OriginInfo(null, cid, true, false);
12114        }
12115
12116        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12117            this.file = file;
12118            this.cid = cid;
12119            this.staged = staged;
12120            this.existing = existing;
12121
12122            if (cid != null) {
12123                resolvedPath = PackageHelper.getSdDir(cid);
12124                resolvedFile = new File(resolvedPath);
12125            } else if (file != null) {
12126                resolvedPath = file.getAbsolutePath();
12127                resolvedFile = file;
12128            } else {
12129                resolvedPath = null;
12130                resolvedFile = null;
12131            }
12132        }
12133    }
12134
12135    static class MoveInfo {
12136        final int moveId;
12137        final String fromUuid;
12138        final String toUuid;
12139        final String packageName;
12140        final String dataAppName;
12141        final int appId;
12142        final String seinfo;
12143        final int targetSdkVersion;
12144
12145        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12146                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12147            this.moveId = moveId;
12148            this.fromUuid = fromUuid;
12149            this.toUuid = toUuid;
12150            this.packageName = packageName;
12151            this.dataAppName = dataAppName;
12152            this.appId = appId;
12153            this.seinfo = seinfo;
12154            this.targetSdkVersion = targetSdkVersion;
12155        }
12156    }
12157
12158    static class VerificationInfo {
12159        /** A constant used to indicate that a uid value is not present. */
12160        public static final int NO_UID = -1;
12161
12162        /** URI referencing where the package was downloaded from. */
12163        final Uri originatingUri;
12164
12165        /** HTTP referrer URI associated with the originatingURI. */
12166        final Uri referrer;
12167
12168        /** UID of the application that the install request originated from. */
12169        final int originatingUid;
12170
12171        /** UID of application requesting the install */
12172        final int installerUid;
12173
12174        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12175            this.originatingUri = originatingUri;
12176            this.referrer = referrer;
12177            this.originatingUid = originatingUid;
12178            this.installerUid = installerUid;
12179        }
12180    }
12181
12182    class InstallParams extends HandlerParams {
12183        final OriginInfo origin;
12184        final MoveInfo move;
12185        final IPackageInstallObserver2 observer;
12186        int installFlags;
12187        final String installerPackageName;
12188        final String volumeUuid;
12189        private InstallArgs mArgs;
12190        private int mRet;
12191        final String packageAbiOverride;
12192        final String[] grantedRuntimePermissions;
12193        final VerificationInfo verificationInfo;
12194        final Certificate[][] certificates;
12195
12196        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12197                int installFlags, String installerPackageName, String volumeUuid,
12198                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12199                String[] grantedPermissions, Certificate[][] certificates) {
12200            super(user);
12201            this.origin = origin;
12202            this.move = move;
12203            this.observer = observer;
12204            this.installFlags = installFlags;
12205            this.installerPackageName = installerPackageName;
12206            this.volumeUuid = volumeUuid;
12207            this.verificationInfo = verificationInfo;
12208            this.packageAbiOverride = packageAbiOverride;
12209            this.grantedRuntimePermissions = grantedPermissions;
12210            this.certificates = certificates;
12211        }
12212
12213        @Override
12214        public String toString() {
12215            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12216                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12217        }
12218
12219        private int installLocationPolicy(PackageInfoLite pkgLite) {
12220            String packageName = pkgLite.packageName;
12221            int installLocation = pkgLite.installLocation;
12222            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12223            // reader
12224            synchronized (mPackages) {
12225                // Currently installed package which the new package is attempting to replace or
12226                // null if no such package is installed.
12227                PackageParser.Package installedPkg = mPackages.get(packageName);
12228                // Package which currently owns the data which the new package will own if installed.
12229                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12230                // will be null whereas dataOwnerPkg will contain information about the package
12231                // which was uninstalled while keeping its data.
12232                PackageParser.Package dataOwnerPkg = installedPkg;
12233                if (dataOwnerPkg  == null) {
12234                    PackageSetting ps = mSettings.mPackages.get(packageName);
12235                    if (ps != null) {
12236                        dataOwnerPkg = ps.pkg;
12237                    }
12238                }
12239
12240                if (dataOwnerPkg != null) {
12241                    // If installed, the package will get access to data left on the device by its
12242                    // predecessor. As a security measure, this is permited only if this is not a
12243                    // version downgrade or if the predecessor package is marked as debuggable and
12244                    // a downgrade is explicitly requested.
12245                    //
12246                    // On debuggable platform builds, downgrades are permitted even for
12247                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12248                    // not offer security guarantees and thus it's OK to disable some security
12249                    // mechanisms to make debugging/testing easier on those builds. However, even on
12250                    // debuggable builds downgrades of packages are permitted only if requested via
12251                    // installFlags. This is because we aim to keep the behavior of debuggable
12252                    // platform builds as close as possible to the behavior of non-debuggable
12253                    // platform builds.
12254                    final boolean downgradeRequested =
12255                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12256                    final boolean packageDebuggable =
12257                                (dataOwnerPkg.applicationInfo.flags
12258                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12259                    final boolean downgradePermitted =
12260                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12261                    if (!downgradePermitted) {
12262                        try {
12263                            checkDowngrade(dataOwnerPkg, pkgLite);
12264                        } catch (PackageManagerException e) {
12265                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12266                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12267                        }
12268                    }
12269                }
12270
12271                if (installedPkg != null) {
12272                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12273                        // Check for updated system application.
12274                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12275                            if (onSd) {
12276                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12277                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12278                            }
12279                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12280                        } else {
12281                            if (onSd) {
12282                                // Install flag overrides everything.
12283                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12284                            }
12285                            // If current upgrade specifies particular preference
12286                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12287                                // Application explicitly specified internal.
12288                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12289                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12290                                // App explictly prefers external. Let policy decide
12291                            } else {
12292                                // Prefer previous location
12293                                if (isExternal(installedPkg)) {
12294                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12295                                }
12296                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12297                            }
12298                        }
12299                    } else {
12300                        // Invalid install. Return error code
12301                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12302                    }
12303                }
12304            }
12305            // All the special cases have been taken care of.
12306            // Return result based on recommended install location.
12307            if (onSd) {
12308                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12309            }
12310            return pkgLite.recommendedInstallLocation;
12311        }
12312
12313        /*
12314         * Invoke remote method to get package information and install
12315         * location values. Override install location based on default
12316         * policy if needed and then create install arguments based
12317         * on the install location.
12318         */
12319        public void handleStartCopy() throws RemoteException {
12320            int ret = PackageManager.INSTALL_SUCCEEDED;
12321
12322            // If we're already staged, we've firmly committed to an install location
12323            if (origin.staged) {
12324                if (origin.file != null) {
12325                    installFlags |= PackageManager.INSTALL_INTERNAL;
12326                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12327                } else if (origin.cid != null) {
12328                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12329                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12330                } else {
12331                    throw new IllegalStateException("Invalid stage location");
12332                }
12333            }
12334
12335            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12336            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12337            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12338            PackageInfoLite pkgLite = null;
12339
12340            if (onInt && onSd) {
12341                // Check if both bits are set.
12342                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12343                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12344            } else if (onSd && ephemeral) {
12345                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12346                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12347            } else {
12348                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12349                        packageAbiOverride);
12350
12351                if (DEBUG_EPHEMERAL && ephemeral) {
12352                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12353                }
12354
12355                /*
12356                 * If we have too little free space, try to free cache
12357                 * before giving up.
12358                 */
12359                if (!origin.staged && pkgLite.recommendedInstallLocation
12360                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12361                    // TODO: focus freeing disk space on the target device
12362                    final StorageManager storage = StorageManager.from(mContext);
12363                    final long lowThreshold = storage.getStorageLowBytes(
12364                            Environment.getDataDirectory());
12365
12366                    final long sizeBytes = mContainerService.calculateInstalledSize(
12367                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12368
12369                    try {
12370                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12371                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12372                                installFlags, packageAbiOverride);
12373                    } catch (InstallerException e) {
12374                        Slog.w(TAG, "Failed to free cache", e);
12375                    }
12376
12377                    /*
12378                     * The cache free must have deleted the file we
12379                     * downloaded to install.
12380                     *
12381                     * TODO: fix the "freeCache" call to not delete
12382                     *       the file we care about.
12383                     */
12384                    if (pkgLite.recommendedInstallLocation
12385                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12386                        pkgLite.recommendedInstallLocation
12387                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12388                    }
12389                }
12390            }
12391
12392            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12393                int loc = pkgLite.recommendedInstallLocation;
12394                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12395                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12396                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12397                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12398                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12399                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12400                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12401                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12402                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12403                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12404                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12405                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12406                } else {
12407                    // Override with defaults if needed.
12408                    loc = installLocationPolicy(pkgLite);
12409                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12410                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12411                    } else if (!onSd && !onInt) {
12412                        // Override install location with flags
12413                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12414                            // Set the flag to install on external media.
12415                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12416                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12417                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12418                            if (DEBUG_EPHEMERAL) {
12419                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12420                            }
12421                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12422                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12423                                    |PackageManager.INSTALL_INTERNAL);
12424                        } else {
12425                            // Make sure the flag for installing on external
12426                            // media is unset
12427                            installFlags |= PackageManager.INSTALL_INTERNAL;
12428                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12429                        }
12430                    }
12431                }
12432            }
12433
12434            final InstallArgs args = createInstallArgs(this);
12435            mArgs = args;
12436
12437            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12438                // TODO: http://b/22976637
12439                // Apps installed for "all" users use the device owner to verify the app
12440                UserHandle verifierUser = getUser();
12441                if (verifierUser == UserHandle.ALL) {
12442                    verifierUser = UserHandle.SYSTEM;
12443                }
12444
12445                /*
12446                 * Determine if we have any installed package verifiers. If we
12447                 * do, then we'll defer to them to verify the packages.
12448                 */
12449                final int requiredUid = mRequiredVerifierPackage == null ? -1
12450                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12451                                verifierUser.getIdentifier());
12452                if (!origin.existing && requiredUid != -1
12453                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12454                    final Intent verification = new Intent(
12455                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12456                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12457                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12458                            PACKAGE_MIME_TYPE);
12459                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12460
12461                    // Query all live verifiers based on current user state
12462                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12463                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12464
12465                    if (DEBUG_VERIFY) {
12466                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12467                                + verification.toString() + " with " + pkgLite.verifiers.length
12468                                + " optional verifiers");
12469                    }
12470
12471                    final int verificationId = mPendingVerificationToken++;
12472
12473                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12474
12475                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12476                            installerPackageName);
12477
12478                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12479                            installFlags);
12480
12481                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12482                            pkgLite.packageName);
12483
12484                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12485                            pkgLite.versionCode);
12486
12487                    if (verificationInfo != null) {
12488                        if (verificationInfo.originatingUri != null) {
12489                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12490                                    verificationInfo.originatingUri);
12491                        }
12492                        if (verificationInfo.referrer != null) {
12493                            verification.putExtra(Intent.EXTRA_REFERRER,
12494                                    verificationInfo.referrer);
12495                        }
12496                        if (verificationInfo.originatingUid >= 0) {
12497                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12498                                    verificationInfo.originatingUid);
12499                        }
12500                        if (verificationInfo.installerUid >= 0) {
12501                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12502                                    verificationInfo.installerUid);
12503                        }
12504                    }
12505
12506                    final PackageVerificationState verificationState = new PackageVerificationState(
12507                            requiredUid, args);
12508
12509                    mPendingVerification.append(verificationId, verificationState);
12510
12511                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12512                            receivers, verificationState);
12513
12514                    /*
12515                     * If any sufficient verifiers were listed in the package
12516                     * manifest, attempt to ask them.
12517                     */
12518                    if (sufficientVerifiers != null) {
12519                        final int N = sufficientVerifiers.size();
12520                        if (N == 0) {
12521                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12522                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12523                        } else {
12524                            for (int i = 0; i < N; i++) {
12525                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12526
12527                                final Intent sufficientIntent = new Intent(verification);
12528                                sufficientIntent.setComponent(verifierComponent);
12529                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12530                            }
12531                        }
12532                    }
12533
12534                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12535                            mRequiredVerifierPackage, receivers);
12536                    if (ret == PackageManager.INSTALL_SUCCEEDED
12537                            && mRequiredVerifierPackage != null) {
12538                        Trace.asyncTraceBegin(
12539                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12540                        /*
12541                         * Send the intent to the required verification agent,
12542                         * but only start the verification timeout after the
12543                         * target BroadcastReceivers have run.
12544                         */
12545                        verification.setComponent(requiredVerifierComponent);
12546                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12547                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12548                                new BroadcastReceiver() {
12549                                    @Override
12550                                    public void onReceive(Context context, Intent intent) {
12551                                        final Message msg = mHandler
12552                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12553                                        msg.arg1 = verificationId;
12554                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12555                                    }
12556                                }, null, 0, null, null);
12557
12558                        /*
12559                         * We don't want the copy to proceed until verification
12560                         * succeeds, so null out this field.
12561                         */
12562                        mArgs = null;
12563                    }
12564                } else {
12565                    /*
12566                     * No package verification is enabled, so immediately start
12567                     * the remote call to initiate copy using temporary file.
12568                     */
12569                    ret = args.copyApk(mContainerService, true);
12570                }
12571            }
12572
12573            mRet = ret;
12574        }
12575
12576        @Override
12577        void handleReturnCode() {
12578            // If mArgs is null, then MCS couldn't be reached. When it
12579            // reconnects, it will try again to install. At that point, this
12580            // will succeed.
12581            if (mArgs != null) {
12582                processPendingInstall(mArgs, mRet);
12583            }
12584        }
12585
12586        @Override
12587        void handleServiceError() {
12588            mArgs = createInstallArgs(this);
12589            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12590        }
12591
12592        public boolean isForwardLocked() {
12593            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12594        }
12595    }
12596
12597    /**
12598     * Used during creation of InstallArgs
12599     *
12600     * @param installFlags package installation flags
12601     * @return true if should be installed on external storage
12602     */
12603    private static boolean installOnExternalAsec(int installFlags) {
12604        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12605            return false;
12606        }
12607        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12608            return true;
12609        }
12610        return false;
12611    }
12612
12613    /**
12614     * Used during creation of InstallArgs
12615     *
12616     * @param installFlags package installation flags
12617     * @return true if should be installed as forward locked
12618     */
12619    private static boolean installForwardLocked(int installFlags) {
12620        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12621    }
12622
12623    private InstallArgs createInstallArgs(InstallParams params) {
12624        if (params.move != null) {
12625            return new MoveInstallArgs(params);
12626        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12627            return new AsecInstallArgs(params);
12628        } else {
12629            return new FileInstallArgs(params);
12630        }
12631    }
12632
12633    /**
12634     * Create args that describe an existing installed package. Typically used
12635     * when cleaning up old installs, or used as a move source.
12636     */
12637    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12638            String resourcePath, String[] instructionSets) {
12639        final boolean isInAsec;
12640        if (installOnExternalAsec(installFlags)) {
12641            /* Apps on SD card are always in ASEC containers. */
12642            isInAsec = true;
12643        } else if (installForwardLocked(installFlags)
12644                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12645            /*
12646             * Forward-locked apps are only in ASEC containers if they're the
12647             * new style
12648             */
12649            isInAsec = true;
12650        } else {
12651            isInAsec = false;
12652        }
12653
12654        if (isInAsec) {
12655            return new AsecInstallArgs(codePath, instructionSets,
12656                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12657        } else {
12658            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12659        }
12660    }
12661
12662    static abstract class InstallArgs {
12663        /** @see InstallParams#origin */
12664        final OriginInfo origin;
12665        /** @see InstallParams#move */
12666        final MoveInfo move;
12667
12668        final IPackageInstallObserver2 observer;
12669        // Always refers to PackageManager flags only
12670        final int installFlags;
12671        final String installerPackageName;
12672        final String volumeUuid;
12673        final UserHandle user;
12674        final String abiOverride;
12675        final String[] installGrantPermissions;
12676        /** If non-null, drop an async trace when the install completes */
12677        final String traceMethod;
12678        final int traceCookie;
12679        final Certificate[][] certificates;
12680
12681        // The list of instruction sets supported by this app. This is currently
12682        // only used during the rmdex() phase to clean up resources. We can get rid of this
12683        // if we move dex files under the common app path.
12684        /* nullable */ String[] instructionSets;
12685
12686        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12687                int installFlags, String installerPackageName, String volumeUuid,
12688                UserHandle user, String[] instructionSets,
12689                String abiOverride, String[] installGrantPermissions,
12690                String traceMethod, int traceCookie, Certificate[][] certificates) {
12691            this.origin = origin;
12692            this.move = move;
12693            this.installFlags = installFlags;
12694            this.observer = observer;
12695            this.installerPackageName = installerPackageName;
12696            this.volumeUuid = volumeUuid;
12697            this.user = user;
12698            this.instructionSets = instructionSets;
12699            this.abiOverride = abiOverride;
12700            this.installGrantPermissions = installGrantPermissions;
12701            this.traceMethod = traceMethod;
12702            this.traceCookie = traceCookie;
12703            this.certificates = certificates;
12704        }
12705
12706        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12707        abstract int doPreInstall(int status);
12708
12709        /**
12710         * Rename package into final resting place. All paths on the given
12711         * scanned package should be updated to reflect the rename.
12712         */
12713        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12714        abstract int doPostInstall(int status, int uid);
12715
12716        /** @see PackageSettingBase#codePathString */
12717        abstract String getCodePath();
12718        /** @see PackageSettingBase#resourcePathString */
12719        abstract String getResourcePath();
12720
12721        // Need installer lock especially for dex file removal.
12722        abstract void cleanUpResourcesLI();
12723        abstract boolean doPostDeleteLI(boolean delete);
12724
12725        /**
12726         * Called before the source arguments are copied. This is used mostly
12727         * for MoveParams when it needs to read the source file to put it in the
12728         * destination.
12729         */
12730        int doPreCopy() {
12731            return PackageManager.INSTALL_SUCCEEDED;
12732        }
12733
12734        /**
12735         * Called after the source arguments are copied. This is used mostly for
12736         * MoveParams when it needs to read the source file to put it in the
12737         * destination.
12738         */
12739        int doPostCopy(int uid) {
12740            return PackageManager.INSTALL_SUCCEEDED;
12741        }
12742
12743        protected boolean isFwdLocked() {
12744            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12745        }
12746
12747        protected boolean isExternalAsec() {
12748            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12749        }
12750
12751        protected boolean isEphemeral() {
12752            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12753        }
12754
12755        UserHandle getUser() {
12756            return user;
12757        }
12758    }
12759
12760    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12761        if (!allCodePaths.isEmpty()) {
12762            if (instructionSets == null) {
12763                throw new IllegalStateException("instructionSet == null");
12764            }
12765            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12766            for (String codePath : allCodePaths) {
12767                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12768                    try {
12769                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12770                    } catch (InstallerException ignored) {
12771                    }
12772                }
12773            }
12774        }
12775    }
12776
12777    /**
12778     * Logic to handle installation of non-ASEC applications, including copying
12779     * and renaming logic.
12780     */
12781    class FileInstallArgs extends InstallArgs {
12782        private File codeFile;
12783        private File resourceFile;
12784
12785        // Example topology:
12786        // /data/app/com.example/base.apk
12787        // /data/app/com.example/split_foo.apk
12788        // /data/app/com.example/lib/arm/libfoo.so
12789        // /data/app/com.example/lib/arm64/libfoo.so
12790        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12791
12792        /** New install */
12793        FileInstallArgs(InstallParams params) {
12794            super(params.origin, params.move, params.observer, params.installFlags,
12795                    params.installerPackageName, params.volumeUuid,
12796                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12797                    params.grantedRuntimePermissions,
12798                    params.traceMethod, params.traceCookie, params.certificates);
12799            if (isFwdLocked()) {
12800                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12801            }
12802        }
12803
12804        /** Existing install */
12805        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12806            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12807                    null, null, null, 0, null /*certificates*/);
12808            this.codeFile = (codePath != null) ? new File(codePath) : null;
12809            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12810        }
12811
12812        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12814            try {
12815                return doCopyApk(imcs, temp);
12816            } finally {
12817                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12818            }
12819        }
12820
12821        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12822            if (origin.staged) {
12823                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12824                codeFile = origin.file;
12825                resourceFile = origin.file;
12826                return PackageManager.INSTALL_SUCCEEDED;
12827            }
12828
12829            try {
12830                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12831                final File tempDir =
12832                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12833                codeFile = tempDir;
12834                resourceFile = tempDir;
12835            } catch (IOException e) {
12836                Slog.w(TAG, "Failed to create copy file: " + e);
12837                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12838            }
12839
12840            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12841                @Override
12842                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12843                    if (!FileUtils.isValidExtFilename(name)) {
12844                        throw new IllegalArgumentException("Invalid filename: " + name);
12845                    }
12846                    try {
12847                        final File file = new File(codeFile, name);
12848                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12849                                O_RDWR | O_CREAT, 0644);
12850                        Os.chmod(file.getAbsolutePath(), 0644);
12851                        return new ParcelFileDescriptor(fd);
12852                    } catch (ErrnoException e) {
12853                        throw new RemoteException("Failed to open: " + e.getMessage());
12854                    }
12855                }
12856            };
12857
12858            int ret = PackageManager.INSTALL_SUCCEEDED;
12859            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12860            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12861                Slog.e(TAG, "Failed to copy package");
12862                return ret;
12863            }
12864
12865            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12866            NativeLibraryHelper.Handle handle = null;
12867            try {
12868                handle = NativeLibraryHelper.Handle.create(codeFile);
12869                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12870                        abiOverride);
12871            } catch (IOException e) {
12872                Slog.e(TAG, "Copying native libraries failed", e);
12873                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12874            } finally {
12875                IoUtils.closeQuietly(handle);
12876            }
12877
12878            return ret;
12879        }
12880
12881        int doPreInstall(int status) {
12882            if (status != PackageManager.INSTALL_SUCCEEDED) {
12883                cleanUp();
12884            }
12885            return status;
12886        }
12887
12888        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12889            if (status != PackageManager.INSTALL_SUCCEEDED) {
12890                cleanUp();
12891                return false;
12892            }
12893
12894            final File targetDir = codeFile.getParentFile();
12895            final File beforeCodeFile = codeFile;
12896            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12897
12898            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12899            try {
12900                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12901            } catch (ErrnoException e) {
12902                Slog.w(TAG, "Failed to rename", e);
12903                return false;
12904            }
12905
12906            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12907                Slog.w(TAG, "Failed to restorecon");
12908                return false;
12909            }
12910
12911            // Reflect the rename internally
12912            codeFile = afterCodeFile;
12913            resourceFile = afterCodeFile;
12914
12915            // Reflect the rename in scanned details
12916            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12917            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12918                    afterCodeFile, pkg.baseCodePath));
12919            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12920                    afterCodeFile, pkg.splitCodePaths));
12921
12922            // Reflect the rename in app info
12923            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12924            pkg.setApplicationInfoCodePath(pkg.codePath);
12925            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12926            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12927            pkg.setApplicationInfoResourcePath(pkg.codePath);
12928            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12929            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12930
12931            return true;
12932        }
12933
12934        int doPostInstall(int status, int uid) {
12935            if (status != PackageManager.INSTALL_SUCCEEDED) {
12936                cleanUp();
12937            }
12938            return status;
12939        }
12940
12941        @Override
12942        String getCodePath() {
12943            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12944        }
12945
12946        @Override
12947        String getResourcePath() {
12948            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12949        }
12950
12951        private boolean cleanUp() {
12952            if (codeFile == null || !codeFile.exists()) {
12953                return false;
12954            }
12955
12956            removeCodePathLI(codeFile);
12957
12958            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12959                resourceFile.delete();
12960            }
12961
12962            return true;
12963        }
12964
12965        void cleanUpResourcesLI() {
12966            // Try enumerating all code paths before deleting
12967            List<String> allCodePaths = Collections.EMPTY_LIST;
12968            if (codeFile != null && codeFile.exists()) {
12969                try {
12970                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12971                    allCodePaths = pkg.getAllCodePaths();
12972                } catch (PackageParserException e) {
12973                    // Ignored; we tried our best
12974                }
12975            }
12976
12977            cleanUp();
12978            removeDexFiles(allCodePaths, instructionSets);
12979        }
12980
12981        boolean doPostDeleteLI(boolean delete) {
12982            // XXX err, shouldn't we respect the delete flag?
12983            cleanUpResourcesLI();
12984            return true;
12985        }
12986    }
12987
12988    private boolean isAsecExternal(String cid) {
12989        final String asecPath = PackageHelper.getSdFilesystem(cid);
12990        return !asecPath.startsWith(mAsecInternalPath);
12991    }
12992
12993    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12994            PackageManagerException {
12995        if (copyRet < 0) {
12996            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12997                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12998                throw new PackageManagerException(copyRet, message);
12999            }
13000        }
13001    }
13002
13003    /**
13004     * Extract the MountService "container ID" from the full code path of an
13005     * .apk.
13006     */
13007    static String cidFromCodePath(String fullCodePath) {
13008        int eidx = fullCodePath.lastIndexOf("/");
13009        String subStr1 = fullCodePath.substring(0, eidx);
13010        int sidx = subStr1.lastIndexOf("/");
13011        return subStr1.substring(sidx+1, eidx);
13012    }
13013
13014    /**
13015     * Logic to handle installation of ASEC applications, including copying and
13016     * renaming logic.
13017     */
13018    class AsecInstallArgs extends InstallArgs {
13019        static final String RES_FILE_NAME = "pkg.apk";
13020        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13021
13022        String cid;
13023        String packagePath;
13024        String resourcePath;
13025
13026        /** New install */
13027        AsecInstallArgs(InstallParams params) {
13028            super(params.origin, params.move, params.observer, params.installFlags,
13029                    params.installerPackageName, params.volumeUuid,
13030                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13031                    params.grantedRuntimePermissions,
13032                    params.traceMethod, params.traceCookie, params.certificates);
13033        }
13034
13035        /** Existing install */
13036        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13037                        boolean isExternal, boolean isForwardLocked) {
13038            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13039              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13040                    instructionSets, null, null, null, 0, null /*certificates*/);
13041            // Hackily pretend we're still looking at a full code path
13042            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13043                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13044            }
13045
13046            // Extract cid from fullCodePath
13047            int eidx = fullCodePath.lastIndexOf("/");
13048            String subStr1 = fullCodePath.substring(0, eidx);
13049            int sidx = subStr1.lastIndexOf("/");
13050            cid = subStr1.substring(sidx+1, eidx);
13051            setMountPath(subStr1);
13052        }
13053
13054        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13055            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13056              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13057                    instructionSets, null, null, null, 0, null /*certificates*/);
13058            this.cid = cid;
13059            setMountPath(PackageHelper.getSdDir(cid));
13060        }
13061
13062        void createCopyFile() {
13063            cid = mInstallerService.allocateExternalStageCidLegacy();
13064        }
13065
13066        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13067            if (origin.staged && origin.cid != null) {
13068                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13069                cid = origin.cid;
13070                setMountPath(PackageHelper.getSdDir(cid));
13071                return PackageManager.INSTALL_SUCCEEDED;
13072            }
13073
13074            if (temp) {
13075                createCopyFile();
13076            } else {
13077                /*
13078                 * Pre-emptively destroy the container since it's destroyed if
13079                 * copying fails due to it existing anyway.
13080                 */
13081                PackageHelper.destroySdDir(cid);
13082            }
13083
13084            final String newMountPath = imcs.copyPackageToContainer(
13085                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13086                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13087
13088            if (newMountPath != null) {
13089                setMountPath(newMountPath);
13090                return PackageManager.INSTALL_SUCCEEDED;
13091            } else {
13092                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13093            }
13094        }
13095
13096        @Override
13097        String getCodePath() {
13098            return packagePath;
13099        }
13100
13101        @Override
13102        String getResourcePath() {
13103            return resourcePath;
13104        }
13105
13106        int doPreInstall(int status) {
13107            if (status != PackageManager.INSTALL_SUCCEEDED) {
13108                // Destroy container
13109                PackageHelper.destroySdDir(cid);
13110            } else {
13111                boolean mounted = PackageHelper.isContainerMounted(cid);
13112                if (!mounted) {
13113                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13114                            Process.SYSTEM_UID);
13115                    if (newMountPath != null) {
13116                        setMountPath(newMountPath);
13117                    } else {
13118                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13119                    }
13120                }
13121            }
13122            return status;
13123        }
13124
13125        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13126            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13127            String newMountPath = null;
13128            if (PackageHelper.isContainerMounted(cid)) {
13129                // Unmount the container
13130                if (!PackageHelper.unMountSdDir(cid)) {
13131                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13132                    return false;
13133                }
13134            }
13135            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13136                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13137                        " which might be stale. Will try to clean up.");
13138                // Clean up the stale container and proceed to recreate.
13139                if (!PackageHelper.destroySdDir(newCacheId)) {
13140                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13141                    return false;
13142                }
13143                // Successfully cleaned up stale container. Try to rename again.
13144                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13145                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13146                            + " inspite of cleaning it up.");
13147                    return false;
13148                }
13149            }
13150            if (!PackageHelper.isContainerMounted(newCacheId)) {
13151                Slog.w(TAG, "Mounting container " + newCacheId);
13152                newMountPath = PackageHelper.mountSdDir(newCacheId,
13153                        getEncryptKey(), Process.SYSTEM_UID);
13154            } else {
13155                newMountPath = PackageHelper.getSdDir(newCacheId);
13156            }
13157            if (newMountPath == null) {
13158                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13159                return false;
13160            }
13161            Log.i(TAG, "Succesfully renamed " + cid +
13162                    " to " + newCacheId +
13163                    " at new path: " + newMountPath);
13164            cid = newCacheId;
13165
13166            final File beforeCodeFile = new File(packagePath);
13167            setMountPath(newMountPath);
13168            final File afterCodeFile = new File(packagePath);
13169
13170            // Reflect the rename in scanned details
13171            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13172            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13173                    afterCodeFile, pkg.baseCodePath));
13174            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13175                    afterCodeFile, pkg.splitCodePaths));
13176
13177            // Reflect the rename in app info
13178            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13179            pkg.setApplicationInfoCodePath(pkg.codePath);
13180            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13181            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13182            pkg.setApplicationInfoResourcePath(pkg.codePath);
13183            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13184            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13185
13186            return true;
13187        }
13188
13189        private void setMountPath(String mountPath) {
13190            final File mountFile = new File(mountPath);
13191
13192            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13193            if (monolithicFile.exists()) {
13194                packagePath = monolithicFile.getAbsolutePath();
13195                if (isFwdLocked()) {
13196                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13197                } else {
13198                    resourcePath = packagePath;
13199                }
13200            } else {
13201                packagePath = mountFile.getAbsolutePath();
13202                resourcePath = packagePath;
13203            }
13204        }
13205
13206        int doPostInstall(int status, int uid) {
13207            if (status != PackageManager.INSTALL_SUCCEEDED) {
13208                cleanUp();
13209            } else {
13210                final int groupOwner;
13211                final String protectedFile;
13212                if (isFwdLocked()) {
13213                    groupOwner = UserHandle.getSharedAppGid(uid);
13214                    protectedFile = RES_FILE_NAME;
13215                } else {
13216                    groupOwner = -1;
13217                    protectedFile = null;
13218                }
13219
13220                if (uid < Process.FIRST_APPLICATION_UID
13221                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13222                    Slog.e(TAG, "Failed to finalize " + cid);
13223                    PackageHelper.destroySdDir(cid);
13224                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13225                }
13226
13227                boolean mounted = PackageHelper.isContainerMounted(cid);
13228                if (!mounted) {
13229                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13230                }
13231            }
13232            return status;
13233        }
13234
13235        private void cleanUp() {
13236            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13237
13238            // Destroy secure container
13239            PackageHelper.destroySdDir(cid);
13240        }
13241
13242        private List<String> getAllCodePaths() {
13243            final File codeFile = new File(getCodePath());
13244            if (codeFile != null && codeFile.exists()) {
13245                try {
13246                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13247                    return pkg.getAllCodePaths();
13248                } catch (PackageParserException e) {
13249                    // Ignored; we tried our best
13250                }
13251            }
13252            return Collections.EMPTY_LIST;
13253        }
13254
13255        void cleanUpResourcesLI() {
13256            // Enumerate all code paths before deleting
13257            cleanUpResourcesLI(getAllCodePaths());
13258        }
13259
13260        private void cleanUpResourcesLI(List<String> allCodePaths) {
13261            cleanUp();
13262            removeDexFiles(allCodePaths, instructionSets);
13263        }
13264
13265        String getPackageName() {
13266            return getAsecPackageName(cid);
13267        }
13268
13269        boolean doPostDeleteLI(boolean delete) {
13270            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13271            final List<String> allCodePaths = getAllCodePaths();
13272            boolean mounted = PackageHelper.isContainerMounted(cid);
13273            if (mounted) {
13274                // Unmount first
13275                if (PackageHelper.unMountSdDir(cid)) {
13276                    mounted = false;
13277                }
13278            }
13279            if (!mounted && delete) {
13280                cleanUpResourcesLI(allCodePaths);
13281            }
13282            return !mounted;
13283        }
13284
13285        @Override
13286        int doPreCopy() {
13287            if (isFwdLocked()) {
13288                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13289                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13290                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13291                }
13292            }
13293
13294            return PackageManager.INSTALL_SUCCEEDED;
13295        }
13296
13297        @Override
13298        int doPostCopy(int uid) {
13299            if (isFwdLocked()) {
13300                if (uid < Process.FIRST_APPLICATION_UID
13301                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13302                                RES_FILE_NAME)) {
13303                    Slog.e(TAG, "Failed to finalize " + cid);
13304                    PackageHelper.destroySdDir(cid);
13305                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13306                }
13307            }
13308
13309            return PackageManager.INSTALL_SUCCEEDED;
13310        }
13311    }
13312
13313    /**
13314     * Logic to handle movement of existing installed applications.
13315     */
13316    class MoveInstallArgs extends InstallArgs {
13317        private File codeFile;
13318        private File resourceFile;
13319
13320        /** New install */
13321        MoveInstallArgs(InstallParams params) {
13322            super(params.origin, params.move, params.observer, params.installFlags,
13323                    params.installerPackageName, params.volumeUuid,
13324                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13325                    params.grantedRuntimePermissions,
13326                    params.traceMethod, params.traceCookie, params.certificates);
13327        }
13328
13329        int copyApk(IMediaContainerService imcs, boolean temp) {
13330            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13331                    + move.fromUuid + " to " + move.toUuid);
13332            synchronized (mInstaller) {
13333                try {
13334                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13335                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13336                } catch (InstallerException e) {
13337                    Slog.w(TAG, "Failed to move app", e);
13338                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13339                }
13340            }
13341
13342            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13343            resourceFile = codeFile;
13344            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13345
13346            return PackageManager.INSTALL_SUCCEEDED;
13347        }
13348
13349        int doPreInstall(int status) {
13350            if (status != PackageManager.INSTALL_SUCCEEDED) {
13351                cleanUp(move.toUuid);
13352            }
13353            return status;
13354        }
13355
13356        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13357            if (status != PackageManager.INSTALL_SUCCEEDED) {
13358                cleanUp(move.toUuid);
13359                return false;
13360            }
13361
13362            // Reflect the move in app info
13363            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13364            pkg.setApplicationInfoCodePath(pkg.codePath);
13365            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13366            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13367            pkg.setApplicationInfoResourcePath(pkg.codePath);
13368            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13369            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13370
13371            return true;
13372        }
13373
13374        int doPostInstall(int status, int uid) {
13375            if (status == PackageManager.INSTALL_SUCCEEDED) {
13376                cleanUp(move.fromUuid);
13377            } else {
13378                cleanUp(move.toUuid);
13379            }
13380            return status;
13381        }
13382
13383        @Override
13384        String getCodePath() {
13385            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13386        }
13387
13388        @Override
13389        String getResourcePath() {
13390            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13391        }
13392
13393        private boolean cleanUp(String volumeUuid) {
13394            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13395                    move.dataAppName);
13396            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13397            synchronized (mInstallLock) {
13398                // Clean up both app data and code
13399                // All package moves are frozen until finished
13400                try {
13401                    mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL,
13402                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13403                } catch (InstallerException e) {
13404                    Slog.w(TAG, String.valueOf(e));
13405                }
13406                removeCodePathLI(codeFile);
13407            }
13408            return true;
13409        }
13410
13411        void cleanUpResourcesLI() {
13412            throw new UnsupportedOperationException();
13413        }
13414
13415        boolean doPostDeleteLI(boolean delete) {
13416            throw new UnsupportedOperationException();
13417        }
13418    }
13419
13420    static String getAsecPackageName(String packageCid) {
13421        int idx = packageCid.lastIndexOf("-");
13422        if (idx == -1) {
13423            return packageCid;
13424        }
13425        return packageCid.substring(0, idx);
13426    }
13427
13428    // Utility method used to create code paths based on package name and available index.
13429    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13430        String idxStr = "";
13431        int idx = 1;
13432        // Fall back to default value of idx=1 if prefix is not
13433        // part of oldCodePath
13434        if (oldCodePath != null) {
13435            String subStr = oldCodePath;
13436            // Drop the suffix right away
13437            if (suffix != null && subStr.endsWith(suffix)) {
13438                subStr = subStr.substring(0, subStr.length() - suffix.length());
13439            }
13440            // If oldCodePath already contains prefix find out the
13441            // ending index to either increment or decrement.
13442            int sidx = subStr.lastIndexOf(prefix);
13443            if (sidx != -1) {
13444                subStr = subStr.substring(sidx + prefix.length());
13445                if (subStr != null) {
13446                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13447                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13448                    }
13449                    try {
13450                        idx = Integer.parseInt(subStr);
13451                        if (idx <= 1) {
13452                            idx++;
13453                        } else {
13454                            idx--;
13455                        }
13456                    } catch(NumberFormatException e) {
13457                    }
13458                }
13459            }
13460        }
13461        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13462        return prefix + idxStr;
13463    }
13464
13465    private File getNextCodePath(File targetDir, String packageName) {
13466        int suffix = 1;
13467        File result;
13468        do {
13469            result = new File(targetDir, packageName + "-" + suffix);
13470            suffix++;
13471        } while (result.exists());
13472        return result;
13473    }
13474
13475    // Utility method that returns the relative package path with respect
13476    // to the installation directory. Like say for /data/data/com.test-1.apk
13477    // string com.test-1 is returned.
13478    static String deriveCodePathName(String codePath) {
13479        if (codePath == null) {
13480            return null;
13481        }
13482        final File codeFile = new File(codePath);
13483        final String name = codeFile.getName();
13484        if (codeFile.isDirectory()) {
13485            return name;
13486        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13487            final int lastDot = name.lastIndexOf('.');
13488            return name.substring(0, lastDot);
13489        } else {
13490            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13491            return null;
13492        }
13493    }
13494
13495    static class PackageInstalledInfo {
13496        String name;
13497        int uid;
13498        // The set of users that originally had this package installed.
13499        int[] origUsers;
13500        // The set of users that now have this package installed.
13501        int[] newUsers;
13502        PackageParser.Package pkg;
13503        int returnCode;
13504        String returnMsg;
13505        PackageRemovedInfo removedInfo;
13506        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13507
13508        public void setError(int code, String msg) {
13509            setReturnCode(code);
13510            setReturnMessage(msg);
13511            Slog.w(TAG, msg);
13512        }
13513
13514        public void setError(String msg, PackageParserException e) {
13515            setReturnCode(e.error);
13516            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13517            Slog.w(TAG, msg, e);
13518        }
13519
13520        public void setError(String msg, PackageManagerException e) {
13521            returnCode = e.error;
13522            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13523            Slog.w(TAG, msg, e);
13524        }
13525
13526        public void setReturnCode(int returnCode) {
13527            this.returnCode = returnCode;
13528            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13529            for (int i = 0; i < childCount; i++) {
13530                addedChildPackages.valueAt(i).returnCode = returnCode;
13531            }
13532        }
13533
13534        private void setReturnMessage(String returnMsg) {
13535            this.returnMsg = returnMsg;
13536            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13537            for (int i = 0; i < childCount; i++) {
13538                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13539            }
13540        }
13541
13542        // In some error cases we want to convey more info back to the observer
13543        String origPackage;
13544        String origPermission;
13545    }
13546
13547    /*
13548     * Install a non-existing package.
13549     */
13550    private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags,
13551            UserHandle user, String installerPackageName, String volumeUuid,
13552            PackageInstalledInfo res) {
13553        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13554
13555        // Remember this for later, in case we need to rollback this install
13556        String pkgName = pkg.packageName;
13557
13558        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13559
13560        synchronized(mPackages) {
13561            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13562                // A package with the same name is already installed, though
13563                // it has been renamed to an older name.  The package we
13564                // are trying to install should be installed as an update to
13565                // the existing one, but that has not been requested, so bail.
13566                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13567                        + " without first uninstalling package running as "
13568                        + mSettings.mRenamedPackages.get(pkgName));
13569                return;
13570            }
13571            if (mPackages.containsKey(pkgName)) {
13572                // Don't allow installation over an existing package with the same name.
13573                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13574                        + " without first uninstalling.");
13575                return;
13576            }
13577        }
13578
13579        try {
13580            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13581                    System.currentTimeMillis(), user);
13582
13583            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13584
13585            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13586                prepareAppDataAfterInstallLIF(newPackage);
13587
13588            } else {
13589                // Remove package from internal structures, but keep around any
13590                // data that might have already existed
13591                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13592                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13593            }
13594        } catch (PackageManagerException e) {
13595            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13596        }
13597
13598        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13599    }
13600
13601    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13602        // Can't rotate keys during boot or if sharedUser.
13603        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13604                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13605            return false;
13606        }
13607        // app is using upgradeKeySets; make sure all are valid
13608        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13609        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13610        for (int i = 0; i < upgradeKeySets.length; i++) {
13611            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13612                Slog.wtf(TAG, "Package "
13613                         + (oldPs.name != null ? oldPs.name : "<null>")
13614                         + " contains upgrade-key-set reference to unknown key-set: "
13615                         + upgradeKeySets[i]
13616                         + " reverting to signatures check.");
13617                return false;
13618            }
13619        }
13620        return true;
13621    }
13622
13623    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13624        // Upgrade keysets are being used.  Determine if new package has a superset of the
13625        // required keys.
13626        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13627        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13628        for (int i = 0; i < upgradeKeySets.length; i++) {
13629            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13630            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13631                return true;
13632            }
13633        }
13634        return false;
13635    }
13636
13637    private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags,
13638            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13639        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13640
13641        final PackageParser.Package oldPackage;
13642        final String pkgName = pkg.packageName;
13643        final int[] allUsers;
13644
13645        // First find the old package info and check signatures
13646        synchronized(mPackages) {
13647            oldPackage = mPackages.get(pkgName);
13648            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13649            if (isEphemeral && !oldIsEphemeral) {
13650                // can't downgrade from full to ephemeral
13651                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13652                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13653                return;
13654            }
13655            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13656            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13657            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13658                if (!checkUpgradeKeySetLP(ps, pkg)) {
13659                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13660                            "New package not signed by keys specified by upgrade-keysets: "
13661                                    + pkgName);
13662                    return;
13663                }
13664            } else {
13665                // default to original signature matching
13666                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13667                        != PackageManager.SIGNATURE_MATCH) {
13668                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13669                            "New package has a different signature: " + pkgName);
13670                    return;
13671                }
13672            }
13673
13674            // Check for shared user id changes
13675            String invalidPackageName =
13676                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13677            if (invalidPackageName != null) {
13678                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13679                        "Package " + invalidPackageName + " tried to change user "
13680                                + oldPackage.mSharedUserId);
13681                return;
13682            }
13683
13684            // In case of rollback, remember per-user/profile install state
13685            allUsers = sUserManager.getUserIds();
13686        }
13687
13688        // Update what is removed
13689        res.removedInfo = new PackageRemovedInfo();
13690        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13691        res.removedInfo.removedPackage = oldPackage.packageName;
13692        res.removedInfo.isUpdate = true;
13693        final int childCount = (oldPackage.childPackages != null)
13694                ? oldPackage.childPackages.size() : 0;
13695        for (int i = 0; i < childCount; i++) {
13696            boolean childPackageUpdated = false;
13697            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13698            if (res.addedChildPackages != null) {
13699                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13700                if (childRes != null) {
13701                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13702                    childRes.removedInfo.removedPackage = childPkg.packageName;
13703                    childRes.removedInfo.isUpdate = true;
13704                    childPackageUpdated = true;
13705                }
13706            }
13707            if (!childPackageUpdated) {
13708                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13709                childRemovedRes.removedPackage = childPkg.packageName;
13710                childRemovedRes.isUpdate = false;
13711                childRemovedRes.dataRemoved = true;
13712                synchronized (mPackages) {
13713                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13714                    if (childPs != null) {
13715                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13716                    }
13717                }
13718                if (res.removedInfo.removedChildPackages == null) {
13719                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13720                }
13721                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13722            }
13723        }
13724
13725        boolean sysPkg = (isSystemApp(oldPackage));
13726        if (sysPkg) {
13727            replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
13728                    user, allUsers, installerPackageName, res);
13729        } else {
13730            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
13731                    user, allUsers, installerPackageName, res);
13732        }
13733    }
13734
13735    public List<String> getPreviousCodePaths(String packageName) {
13736        final PackageSetting ps = mSettings.mPackages.get(packageName);
13737        final List<String> result = new ArrayList<String>();
13738        if (ps != null && ps.oldCodePaths != null) {
13739            result.addAll(ps.oldCodePaths);
13740        }
13741        return result;
13742    }
13743
13744    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13745            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13746            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13747        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13748                + deletedPackage);
13749
13750        String pkgName = deletedPackage.packageName;
13751        boolean deletedPkg = true;
13752        boolean addedPkg = false;
13753        boolean updatedSettings = false;
13754        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13755        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13756                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13757
13758        final long origUpdateTime = (pkg.mExtras != null)
13759                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13760
13761        // First delete the existing package while retaining the data directory
13762        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13763                res.removedInfo, true, pkg)) {
13764            // If the existing package wasn't successfully deleted
13765            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13766            deletedPkg = false;
13767        } else {
13768            // Successfully deleted the old package; proceed with replace.
13769
13770            // If deleted package lived in a container, give users a chance to
13771            // relinquish resources before killing.
13772            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13773                if (DEBUG_INSTALL) {
13774                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13775                }
13776                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13777                final ArrayList<String> pkgList = new ArrayList<String>(1);
13778                pkgList.add(deletedPackage.applicationInfo.packageName);
13779                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13780            }
13781
13782            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13783                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13784            clearAppProfilesLIF(pkg);
13785
13786            try {
13787                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13788                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13789                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13790
13791                // Update the in-memory copy of the previous code paths.
13792                PackageSetting ps = mSettings.mPackages.get(pkgName);
13793                if (!killApp) {
13794                    if (ps.oldCodePaths == null) {
13795                        ps.oldCodePaths = new ArraySet<>();
13796                    }
13797                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13798                    if (deletedPackage.splitCodePaths != null) {
13799                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13800                    }
13801                } else {
13802                    ps.oldCodePaths = null;
13803                }
13804                if (ps.childPackageNames != null) {
13805                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13806                        final String childPkgName = ps.childPackageNames.get(i);
13807                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13808                        childPs.oldCodePaths = ps.oldCodePaths;
13809                    }
13810                }
13811                prepareAppDataAfterInstallLIF(newPackage);
13812                addedPkg = true;
13813            } catch (PackageManagerException e) {
13814                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13815            }
13816        }
13817
13818        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13819            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13820
13821            // Revert all internal state mutations and added folders for the failed install
13822            if (addedPkg) {
13823                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13824                        res.removedInfo, true, null);
13825            }
13826
13827            // Restore the old package
13828            if (deletedPkg) {
13829                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13830                File restoreFile = new File(deletedPackage.codePath);
13831                // Parse old package
13832                boolean oldExternal = isExternal(deletedPackage);
13833                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13834                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13835                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13836                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13837                try {
13838                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13839                            null);
13840                } catch (PackageManagerException e) {
13841                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13842                            + e.getMessage());
13843                    return;
13844                }
13845
13846                synchronized (mPackages) {
13847                    // Ensure the installer package name up to date
13848                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13849
13850                    // Update permissions for restored package
13851                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13852
13853                    mSettings.writeLPr();
13854                }
13855
13856                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13857            }
13858        } else {
13859            synchronized (mPackages) {
13860                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13861                if (ps != null) {
13862                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13863                    if (res.removedInfo.removedChildPackages != null) {
13864                        final int childCount = res.removedInfo.removedChildPackages.size();
13865                        // Iterate in reverse as we may modify the collection
13866                        for (int i = childCount - 1; i >= 0; i--) {
13867                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13868                            if (res.addedChildPackages.containsKey(childPackageName)) {
13869                                res.removedInfo.removedChildPackages.removeAt(i);
13870                            } else {
13871                                PackageRemovedInfo childInfo = res.removedInfo
13872                                        .removedChildPackages.valueAt(i);
13873                                childInfo.removedForAllUsers = mPackages.get(
13874                                        childInfo.removedPackage) == null;
13875                            }
13876                        }
13877                    }
13878                }
13879            }
13880        }
13881    }
13882
13883    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
13884            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13885            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13886        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13887                + ", old=" + deletedPackage);
13888
13889        final boolean disabledSystem;
13890
13891        // Set the system/privileged flags as needed
13892        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13893        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13894                != 0) {
13895            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13896        }
13897
13898        // Remove existing system package
13899        removePackageLI(deletedPackage, true);
13900
13901        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13902        if (!disabledSystem) {
13903            // We didn't need to disable the .apk as a current system package,
13904            // which means we are replacing another update that is already
13905            // installed.  We need to make sure to delete the older one's .apk.
13906            res.removedInfo.args = createInstallArgsForExisting(0,
13907                    deletedPackage.applicationInfo.getCodePath(),
13908                    deletedPackage.applicationInfo.getResourcePath(),
13909                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13910        } else {
13911            res.removedInfo.args = null;
13912        }
13913
13914        // Successfully disabled the old package. Now proceed with re-installation
13915        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13916                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13917        clearAppProfilesLIF(pkg);
13918
13919        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13920        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13921                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13922
13923        PackageParser.Package newPackage = null;
13924        try {
13925            // Add the package to the internal data structures
13926            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13927
13928            // Set the update and install times
13929            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13930            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13931                    System.currentTimeMillis());
13932
13933            // Update the package dynamic state if succeeded
13934            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13935                // Now that the install succeeded make sure we remove data
13936                // directories for any child package the update removed.
13937                final int deletedChildCount = (deletedPackage.childPackages != null)
13938                        ? deletedPackage.childPackages.size() : 0;
13939                final int newChildCount = (newPackage.childPackages != null)
13940                        ? newPackage.childPackages.size() : 0;
13941                for (int i = 0; i < deletedChildCount; i++) {
13942                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13943                    boolean childPackageDeleted = true;
13944                    for (int j = 0; j < newChildCount; j++) {
13945                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13946                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13947                            childPackageDeleted = false;
13948                            break;
13949                        }
13950                    }
13951                    if (childPackageDeleted) {
13952                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13953                                deletedChildPkg.packageName);
13954                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13955                            PackageRemovedInfo removedChildRes = res.removedInfo
13956                                    .removedChildPackages.get(deletedChildPkg.packageName);
13957                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
13958                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13959                        }
13960                    }
13961                }
13962
13963                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13964                prepareAppDataAfterInstallLIF(newPackage);
13965            }
13966        } catch (PackageManagerException e) {
13967            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13968            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13969        }
13970
13971        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13972            // Re installation failed. Restore old information
13973            // Remove new pkg information
13974            if (newPackage != null) {
13975                removeInstalledPackageLI(newPackage, true);
13976            }
13977            // Add back the old system package
13978            try {
13979                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13980            } catch (PackageManagerException e) {
13981                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13982            }
13983
13984            synchronized (mPackages) {
13985                if (disabledSystem) {
13986                    enableSystemPackageLPw(deletedPackage);
13987                }
13988
13989                // Ensure the installer package name up to date
13990                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13991
13992                // Update permissions for restored package
13993                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13994
13995                mSettings.writeLPr();
13996            }
13997
13998            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13999                    + " after failed upgrade");
14000        }
14001    }
14002
14003    /**
14004     * Checks whether the parent or any of the child packages have a change shared
14005     * user. For a package to be a valid update the shred users of the parent and
14006     * the children should match. We may later support changing child shared users.
14007     * @param oldPkg The updated package.
14008     * @param newPkg The update package.
14009     * @return The shared user that change between the versions.
14010     */
14011    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14012            PackageParser.Package newPkg) {
14013        // Check parent shared user
14014        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14015            return newPkg.packageName;
14016        }
14017        // Check child shared users
14018        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14019        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14020        for (int i = 0; i < newChildCount; i++) {
14021            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14022            // If this child was present, did it have the same shared user?
14023            for (int j = 0; j < oldChildCount; j++) {
14024                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14025                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14026                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14027                    return newChildPkg.packageName;
14028                }
14029            }
14030        }
14031        return null;
14032    }
14033
14034    private void removeNativeBinariesLI(PackageSetting ps) {
14035        // Remove the lib path for the parent package
14036        if (ps != null) {
14037            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14038            // Remove the lib path for the child packages
14039            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14040            for (int i = 0; i < childCount; i++) {
14041                PackageSetting childPs = null;
14042                synchronized (mPackages) {
14043                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14044                }
14045                if (childPs != null) {
14046                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14047                            .legacyNativeLibraryPathString);
14048                }
14049            }
14050        }
14051    }
14052
14053    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14054        // Enable the parent package
14055        mSettings.enableSystemPackageLPw(pkg.packageName);
14056        // Enable the child packages
14057        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14058        for (int i = 0; i < childCount; i++) {
14059            PackageParser.Package childPkg = pkg.childPackages.get(i);
14060            mSettings.enableSystemPackageLPw(childPkg.packageName);
14061        }
14062    }
14063
14064    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14065            PackageParser.Package newPkg) {
14066        // Disable the parent package (parent always replaced)
14067        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14068        // Disable the child packages
14069        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14070        for (int i = 0; i < childCount; i++) {
14071            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14072            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14073            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14074        }
14075        return disabled;
14076    }
14077
14078    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14079            String installerPackageName) {
14080        // Enable the parent package
14081        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14082        // Enable the child packages
14083        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14084        for (int i = 0; i < childCount; i++) {
14085            PackageParser.Package childPkg = pkg.childPackages.get(i);
14086            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14087        }
14088    }
14089
14090    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14091        // Collect all used permissions in the UID
14092        ArraySet<String> usedPermissions = new ArraySet<>();
14093        final int packageCount = su.packages.size();
14094        for (int i = 0; i < packageCount; i++) {
14095            PackageSetting ps = su.packages.valueAt(i);
14096            if (ps.pkg == null) {
14097                continue;
14098            }
14099            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14100            for (int j = 0; j < requestedPermCount; j++) {
14101                String permission = ps.pkg.requestedPermissions.get(j);
14102                BasePermission bp = mSettings.mPermissions.get(permission);
14103                if (bp != null) {
14104                    usedPermissions.add(permission);
14105                }
14106            }
14107        }
14108
14109        PermissionsState permissionsState = su.getPermissionsState();
14110        // Prune install permissions
14111        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14112        final int installPermCount = installPermStates.size();
14113        for (int i = installPermCount - 1; i >= 0;  i--) {
14114            PermissionState permissionState = installPermStates.get(i);
14115            if (!usedPermissions.contains(permissionState.getName())) {
14116                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14117                if (bp != null) {
14118                    permissionsState.revokeInstallPermission(bp);
14119                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14120                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14121                }
14122            }
14123        }
14124
14125        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14126
14127        // Prune runtime permissions
14128        for (int userId : allUserIds) {
14129            List<PermissionState> runtimePermStates = permissionsState
14130                    .getRuntimePermissionStates(userId);
14131            final int runtimePermCount = runtimePermStates.size();
14132            for (int i = runtimePermCount - 1; i >= 0; i--) {
14133                PermissionState permissionState = runtimePermStates.get(i);
14134                if (!usedPermissions.contains(permissionState.getName())) {
14135                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14136                    if (bp != null) {
14137                        permissionsState.revokeRuntimePermission(bp, userId);
14138                        permissionsState.updatePermissionFlags(bp, userId,
14139                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14140                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14141                                runtimePermissionChangedUserIds, userId);
14142                    }
14143                }
14144            }
14145        }
14146
14147        return runtimePermissionChangedUserIds;
14148    }
14149
14150    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14151            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14152        // Update the parent package setting
14153        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14154                res, user);
14155        // Update the child packages setting
14156        final int childCount = (newPackage.childPackages != null)
14157                ? newPackage.childPackages.size() : 0;
14158        for (int i = 0; i < childCount; i++) {
14159            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14160            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14161            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14162                    childRes.origUsers, childRes, user);
14163        }
14164    }
14165
14166    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14167            String installerPackageName, int[] allUsers, int[] installedForUsers,
14168            PackageInstalledInfo res, UserHandle user) {
14169        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14170
14171        String pkgName = newPackage.packageName;
14172        synchronized (mPackages) {
14173            //write settings. the installStatus will be incomplete at this stage.
14174            //note that the new package setting would have already been
14175            //added to mPackages. It hasn't been persisted yet.
14176            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14177            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14178            mSettings.writeLPr();
14179            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14180        }
14181
14182        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14183        synchronized (mPackages) {
14184            updatePermissionsLPw(newPackage.packageName, newPackage,
14185                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14186                            ? UPDATE_PERMISSIONS_ALL : 0));
14187            // For system-bundled packages, we assume that installing an upgraded version
14188            // of the package implies that the user actually wants to run that new code,
14189            // so we enable the package.
14190            PackageSetting ps = mSettings.mPackages.get(pkgName);
14191            final int userId = user.getIdentifier();
14192            if (ps != null) {
14193                if (isSystemApp(newPackage)) {
14194                    if (DEBUG_INSTALL) {
14195                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14196                    }
14197                    // Enable system package for requested users
14198                    if (res.origUsers != null) {
14199                        for (int origUserId : res.origUsers) {
14200                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14201                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14202                                        origUserId, installerPackageName);
14203                            }
14204                        }
14205                    }
14206                    // Also convey the prior install/uninstall state
14207                    if (allUsers != null && installedForUsers != null) {
14208                        for (int currentUserId : allUsers) {
14209                            final boolean installed = ArrayUtils.contains(
14210                                    installedForUsers, currentUserId);
14211                            if (DEBUG_INSTALL) {
14212                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14213                            }
14214                            ps.setInstalled(installed, currentUserId);
14215                        }
14216                        // these install state changes will be persisted in the
14217                        // upcoming call to mSettings.writeLPr().
14218                    }
14219                }
14220                // It's implied that when a user requests installation, they want the app to be
14221                // installed and enabled.
14222                if (userId != UserHandle.USER_ALL) {
14223                    ps.setInstalled(true, userId);
14224                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14225                }
14226            }
14227            res.name = pkgName;
14228            res.uid = newPackage.applicationInfo.uid;
14229            res.pkg = newPackage;
14230            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14231            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14232            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14233            //to update install status
14234            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14235            mSettings.writeLPr();
14236            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14237        }
14238
14239        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14240    }
14241
14242    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14243        try {
14244            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14245            installPackageLI(args, res);
14246        } finally {
14247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14248        }
14249    }
14250
14251    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14252        final int installFlags = args.installFlags;
14253        final String installerPackageName = args.installerPackageName;
14254        final String volumeUuid = args.volumeUuid;
14255        final File tmpPackageFile = new File(args.getCodePath());
14256        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14257        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14258                || (args.volumeUuid != null));
14259        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14260        boolean replace = false;
14261        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14262        if (args.move != null) {
14263            // moving a complete application; perform an initial scan on the new install location
14264            scanFlags |= SCAN_INITIAL;
14265        }
14266        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14267            scanFlags |= SCAN_DONT_KILL_APP;
14268        }
14269
14270        // Result object to be returned
14271        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14272
14273        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14274
14275        // Sanity check
14276        if (ephemeral && (forwardLocked || onExternal)) {
14277            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14278                    + " external=" + onExternal);
14279            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14280            return;
14281        }
14282
14283        // Retrieve PackageSettings and parse package
14284        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14285                | PackageParser.PARSE_ENFORCE_CODE
14286                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14287                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14288                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
14289        PackageParser pp = new PackageParser();
14290        pp.setSeparateProcesses(mSeparateProcesses);
14291        pp.setDisplayMetrics(mMetrics);
14292
14293        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14294        final PackageParser.Package pkg;
14295        try {
14296            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14297        } catch (PackageParserException e) {
14298            res.setError("Failed parse during installPackageLI", e);
14299            return;
14300        } finally {
14301            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14302        }
14303
14304        // If we are installing a clustered package add results for the children
14305        if (pkg.childPackages != null) {
14306            synchronized (mPackages) {
14307                final int childCount = pkg.childPackages.size();
14308                for (int i = 0; i < childCount; i++) {
14309                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14310                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14311                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14312                    childRes.pkg = childPkg;
14313                    childRes.name = childPkg.packageName;
14314                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14315                    if (childPs != null) {
14316                        childRes.origUsers = childPs.queryInstalledUsers(
14317                                sUserManager.getUserIds(), true);
14318                    }
14319                    if ((mPackages.containsKey(childPkg.packageName))) {
14320                        childRes.removedInfo = new PackageRemovedInfo();
14321                        childRes.removedInfo.removedPackage = childPkg.packageName;
14322                    }
14323                    if (res.addedChildPackages == null) {
14324                        res.addedChildPackages = new ArrayMap<>();
14325                    }
14326                    res.addedChildPackages.put(childPkg.packageName, childRes);
14327                }
14328            }
14329        }
14330
14331        // If package doesn't declare API override, mark that we have an install
14332        // time CPU ABI override.
14333        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14334            pkg.cpuAbiOverride = args.abiOverride;
14335        }
14336
14337        String pkgName = res.name = pkg.packageName;
14338        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14339            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14340                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14341                return;
14342            }
14343        }
14344
14345        try {
14346            // either use what we've been given or parse directly from the APK
14347            if (args.certificates != null) {
14348                try {
14349                    PackageParser.populateCertificates(pkg, args.certificates);
14350                } catch (PackageParserException e) {
14351                    // there was something wrong with the certificates we were given;
14352                    // try to pull them from the APK
14353                    PackageParser.collectCertificates(pkg, parseFlags);
14354                }
14355            } else {
14356                PackageParser.collectCertificates(pkg, parseFlags);
14357            }
14358        } catch (PackageParserException e) {
14359            res.setError("Failed collect during installPackageLI", e);
14360            return;
14361        }
14362
14363        // Get rid of all references to package scan path via parser.
14364        pp = null;
14365        String oldCodePath = null;
14366        boolean systemApp = false;
14367        synchronized (mPackages) {
14368            // Check if installing already existing package
14369            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14370                String oldName = mSettings.mRenamedPackages.get(pkgName);
14371                if (pkg.mOriginalPackages != null
14372                        && pkg.mOriginalPackages.contains(oldName)
14373                        && mPackages.containsKey(oldName)) {
14374                    // This package is derived from an original package,
14375                    // and this device has been updating from that original
14376                    // name.  We must continue using the original name, so
14377                    // rename the new package here.
14378                    pkg.setPackageName(oldName);
14379                    pkgName = pkg.packageName;
14380                    replace = true;
14381                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14382                            + oldName + " pkgName=" + pkgName);
14383                } else if (mPackages.containsKey(pkgName)) {
14384                    // This package, under its official name, already exists
14385                    // on the device; we should replace it.
14386                    replace = true;
14387                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14388                }
14389
14390                // Child packages are installed through the parent package
14391                if (pkg.parentPackage != null) {
14392                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14393                            "Package " + pkg.packageName + " is child of package "
14394                                    + pkg.parentPackage.parentPackage + ". Child packages "
14395                                    + "can be updated only through the parent package.");
14396                    return;
14397                }
14398
14399                if (replace) {
14400                    // Prevent apps opting out from runtime permissions
14401                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14402                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14403                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14404                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14405                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14406                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14407                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14408                                        + " doesn't support runtime permissions but the old"
14409                                        + " target SDK " + oldTargetSdk + " does.");
14410                        return;
14411                    }
14412
14413                    // Prevent installing of child packages
14414                    if (oldPackage.parentPackage != null) {
14415                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14416                                "Package " + pkg.packageName + " is child of package "
14417                                        + oldPackage.parentPackage + ". Child packages "
14418                                        + "can be updated only through the parent package.");
14419                        return;
14420                    }
14421                }
14422            }
14423
14424            PackageSetting ps = mSettings.mPackages.get(pkgName);
14425            if (ps != null) {
14426                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14427
14428                // Quick sanity check that we're signed correctly if updating;
14429                // we'll check this again later when scanning, but we want to
14430                // bail early here before tripping over redefined permissions.
14431                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14432                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14433                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14434                                + pkg.packageName + " upgrade keys do not match the "
14435                                + "previously installed version");
14436                        return;
14437                    }
14438                } else {
14439                    try {
14440                        verifySignaturesLP(ps, pkg);
14441                    } catch (PackageManagerException e) {
14442                        res.setError(e.error, e.getMessage());
14443                        return;
14444                    }
14445                }
14446
14447                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14448                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14449                    systemApp = (ps.pkg.applicationInfo.flags &
14450                            ApplicationInfo.FLAG_SYSTEM) != 0;
14451                }
14452                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14453            }
14454
14455            // Check whether the newly-scanned package wants to define an already-defined perm
14456            int N = pkg.permissions.size();
14457            for (int i = N-1; i >= 0; i--) {
14458                PackageParser.Permission perm = pkg.permissions.get(i);
14459                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14460                if (bp != null) {
14461                    // If the defining package is signed with our cert, it's okay.  This
14462                    // also includes the "updating the same package" case, of course.
14463                    // "updating same package" could also involve key-rotation.
14464                    final boolean sigsOk;
14465                    if (bp.sourcePackage.equals(pkg.packageName)
14466                            && (bp.packageSetting instanceof PackageSetting)
14467                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14468                                    scanFlags))) {
14469                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14470                    } else {
14471                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14472                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14473                    }
14474                    if (!sigsOk) {
14475                        // If the owning package is the system itself, we log but allow
14476                        // install to proceed; we fail the install on all other permission
14477                        // redefinitions.
14478                        if (!bp.sourcePackage.equals("android")) {
14479                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14480                                    + pkg.packageName + " attempting to redeclare permission "
14481                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14482                            res.origPermission = perm.info.name;
14483                            res.origPackage = bp.sourcePackage;
14484                            return;
14485                        } else {
14486                            Slog.w(TAG, "Package " + pkg.packageName
14487                                    + " attempting to redeclare system permission "
14488                                    + perm.info.name + "; ignoring new declaration");
14489                            pkg.permissions.remove(i);
14490                        }
14491                    }
14492                }
14493            }
14494        }
14495
14496        if (systemApp) {
14497            if (onExternal) {
14498                // Abort update; system app can't be replaced with app on sdcard
14499                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14500                        "Cannot install updates to system apps on sdcard");
14501                return;
14502            } else if (ephemeral) {
14503                // Abort update; system app can't be replaced with an ephemeral app
14504                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14505                        "Cannot update a system app with an ephemeral app");
14506                return;
14507            }
14508        }
14509
14510        if (args.move != null) {
14511            // We did an in-place move, so dex is ready to roll
14512            scanFlags |= SCAN_NO_DEX;
14513            scanFlags |= SCAN_MOVE;
14514
14515            synchronized (mPackages) {
14516                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14517                if (ps == null) {
14518                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14519                            "Missing settings for moved package " + pkgName);
14520                }
14521
14522                // We moved the entire application as-is, so bring over the
14523                // previously derived ABI information.
14524                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14525                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14526            }
14527
14528        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14529            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14530            scanFlags |= SCAN_NO_DEX;
14531
14532            try {
14533                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14534                    args.abiOverride : pkg.cpuAbiOverride);
14535                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14536                        true /* extract libs */);
14537            } catch (PackageManagerException pme) {
14538                Slog.e(TAG, "Error deriving application ABI", pme);
14539                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14540                return;
14541            }
14542
14543            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14544            // Do not run PackageDexOptimizer through the local performDexOpt
14545            // method because `pkg` is not in `mPackages` yet.
14546            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14547                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14548            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14549            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14550                String msg = "Extracting package failed for " + pkgName;
14551                res.setError(INSTALL_FAILED_DEXOPT, msg);
14552                return;
14553            }
14554
14555            // Notify BackgroundDexOptService that the package has been changed.
14556            // If this is an update of a package which used to fail to compile,
14557            // BDOS will remove it from its blacklist.
14558            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14559        }
14560
14561        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14562            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14563            return;
14564        }
14565
14566        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14567
14568        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14569                "installPackageLI")) {
14570            if (replace) {
14571                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14572                        installerPackageName, res);
14573            } else {
14574                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14575                        args.user, installerPackageName, volumeUuid, res);
14576            }
14577        }
14578        synchronized (mPackages) {
14579            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14580            if (ps != null) {
14581                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14582            }
14583
14584            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14585            for (int i = 0; i < childCount; i++) {
14586                PackageParser.Package childPkg = pkg.childPackages.get(i);
14587                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14588                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14589                if (childPs != null) {
14590                    childRes.newUsers = childPs.queryInstalledUsers(
14591                            sUserManager.getUserIds(), true);
14592                }
14593            }
14594        }
14595    }
14596
14597    private void startIntentFilterVerifications(int userId, boolean replacing,
14598            PackageParser.Package pkg) {
14599        if (mIntentFilterVerifierComponent == null) {
14600            Slog.w(TAG, "No IntentFilter verification will not be done as "
14601                    + "there is no IntentFilterVerifier available!");
14602            return;
14603        }
14604
14605        final int verifierUid = getPackageUid(
14606                mIntentFilterVerifierComponent.getPackageName(),
14607                MATCH_DEBUG_TRIAGED_MISSING,
14608                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14609
14610        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14611        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14612        mHandler.sendMessage(msg);
14613
14614        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14615        for (int i = 0; i < childCount; i++) {
14616            PackageParser.Package childPkg = pkg.childPackages.get(i);
14617            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14618            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14619            mHandler.sendMessage(msg);
14620        }
14621    }
14622
14623    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14624            PackageParser.Package pkg) {
14625        int size = pkg.activities.size();
14626        if (size == 0) {
14627            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14628                    "No activity, so no need to verify any IntentFilter!");
14629            return;
14630        }
14631
14632        final boolean hasDomainURLs = hasDomainURLs(pkg);
14633        if (!hasDomainURLs) {
14634            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14635                    "No domain URLs, so no need to verify any IntentFilter!");
14636            return;
14637        }
14638
14639        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14640                + " if any IntentFilter from the " + size
14641                + " Activities needs verification ...");
14642
14643        int count = 0;
14644        final String packageName = pkg.packageName;
14645
14646        synchronized (mPackages) {
14647            // If this is a new install and we see that we've already run verification for this
14648            // package, we have nothing to do: it means the state was restored from backup.
14649            if (!replacing) {
14650                IntentFilterVerificationInfo ivi =
14651                        mSettings.getIntentFilterVerificationLPr(packageName);
14652                if (ivi != null) {
14653                    if (DEBUG_DOMAIN_VERIFICATION) {
14654                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14655                                + ivi.getStatusString());
14656                    }
14657                    return;
14658                }
14659            }
14660
14661            // If any filters need to be verified, then all need to be.
14662            boolean needToVerify = false;
14663            for (PackageParser.Activity a : pkg.activities) {
14664                for (ActivityIntentInfo filter : a.intents) {
14665                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14666                        if (DEBUG_DOMAIN_VERIFICATION) {
14667                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14668                        }
14669                        needToVerify = true;
14670                        break;
14671                    }
14672                }
14673            }
14674
14675            if (needToVerify) {
14676                final int verificationId = mIntentFilterVerificationToken++;
14677                for (PackageParser.Activity a : pkg.activities) {
14678                    for (ActivityIntentInfo filter : a.intents) {
14679                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14680                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14681                                    "Verification needed for IntentFilter:" + filter.toString());
14682                            mIntentFilterVerifier.addOneIntentFilterVerification(
14683                                    verifierUid, userId, verificationId, filter, packageName);
14684                            count++;
14685                        }
14686                    }
14687                }
14688            }
14689        }
14690
14691        if (count > 0) {
14692            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14693                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14694                    +  " for userId:" + userId);
14695            mIntentFilterVerifier.startVerifications(userId);
14696        } else {
14697            if (DEBUG_DOMAIN_VERIFICATION) {
14698                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14699            }
14700        }
14701    }
14702
14703    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14704        final ComponentName cn  = filter.activity.getComponentName();
14705        final String packageName = cn.getPackageName();
14706
14707        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14708                packageName);
14709        if (ivi == null) {
14710            return true;
14711        }
14712        int status = ivi.getStatus();
14713        switch (status) {
14714            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14715            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14716                return true;
14717
14718            default:
14719                // Nothing to do
14720                return false;
14721        }
14722    }
14723
14724    private static boolean isMultiArch(ApplicationInfo info) {
14725        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14726    }
14727
14728    private static boolean isExternal(PackageParser.Package pkg) {
14729        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14730    }
14731
14732    private static boolean isExternal(PackageSetting ps) {
14733        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14734    }
14735
14736    private static boolean isEphemeral(PackageParser.Package pkg) {
14737        return pkg.applicationInfo.isEphemeralApp();
14738    }
14739
14740    private static boolean isEphemeral(PackageSetting ps) {
14741        return ps.pkg != null && isEphemeral(ps.pkg);
14742    }
14743
14744    private static boolean isSystemApp(PackageParser.Package pkg) {
14745        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14746    }
14747
14748    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14749        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14750    }
14751
14752    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14753        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14754    }
14755
14756    private static boolean isSystemApp(PackageSetting ps) {
14757        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14758    }
14759
14760    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14761        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14762    }
14763
14764    private int packageFlagsToInstallFlags(PackageSetting ps) {
14765        int installFlags = 0;
14766        if (isEphemeral(ps)) {
14767            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14768        }
14769        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14770            // This existing package was an external ASEC install when we have
14771            // the external flag without a UUID
14772            installFlags |= PackageManager.INSTALL_EXTERNAL;
14773        }
14774        if (ps.isForwardLocked()) {
14775            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14776        }
14777        return installFlags;
14778    }
14779
14780    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14781        if (isExternal(pkg)) {
14782            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14783                return StorageManager.UUID_PRIMARY_PHYSICAL;
14784            } else {
14785                return pkg.volumeUuid;
14786            }
14787        } else {
14788            return StorageManager.UUID_PRIVATE_INTERNAL;
14789        }
14790    }
14791
14792    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14793        if (isExternal(pkg)) {
14794            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14795                return mSettings.getExternalVersion();
14796            } else {
14797                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14798            }
14799        } else {
14800            return mSettings.getInternalVersion();
14801        }
14802    }
14803
14804    private void deleteTempPackageFiles() {
14805        final FilenameFilter filter = new FilenameFilter() {
14806            public boolean accept(File dir, String name) {
14807                return name.startsWith("vmdl") && name.endsWith(".tmp");
14808            }
14809        };
14810        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14811            file.delete();
14812        }
14813    }
14814
14815    @Override
14816    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14817            int flags) {
14818        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14819                flags);
14820    }
14821
14822    @Override
14823    public void deletePackage(final String packageName,
14824            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
14825        mContext.enforceCallingOrSelfPermission(
14826                android.Manifest.permission.DELETE_PACKAGES, null);
14827        Preconditions.checkNotNull(packageName);
14828        Preconditions.checkNotNull(observer);
14829        final int uid = Binder.getCallingUid();
14830        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
14831        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14832        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14833            mContext.enforceCallingOrSelfPermission(
14834                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14835                    "deletePackage for user " + userId);
14836        }
14837
14838        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14839            try {
14840                observer.onPackageDeleted(packageName,
14841                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14842            } catch (RemoteException re) {
14843            }
14844            return;
14845        }
14846
14847        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14848            try {
14849                observer.onPackageDeleted(packageName,
14850                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14851            } catch (RemoteException re) {
14852            }
14853            return;
14854        }
14855
14856        if (DEBUG_REMOVE) {
14857            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14858                    + " deleteAllUsers: " + deleteAllUsers );
14859        }
14860        // Queue up an async operation since the package deletion may take a little while.
14861        mHandler.post(new Runnable() {
14862            public void run() {
14863                mHandler.removeCallbacks(this);
14864                int returnCode;
14865                if (!deleteAllUsers) {
14866                    returnCode = deletePackageX(packageName, userId, deleteFlags);
14867                } else {
14868                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14869                    // If nobody is blocking uninstall, proceed with delete for all users
14870                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14871                        returnCode = deletePackageX(packageName, userId, deleteFlags);
14872                    } else {
14873                        // Otherwise uninstall individually for users with blockUninstalls=false
14874                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
14875                        for (int userId : users) {
14876                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14877                                returnCode = deletePackageX(packageName, userId, userFlags);
14878                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14879                                    Slog.w(TAG, "Package delete failed for user " + userId
14880                                            + ", returnCode " + returnCode);
14881                                }
14882                            }
14883                        }
14884                        // The app has only been marked uninstalled for certain users.
14885                        // We still need to report that delete was blocked
14886                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14887                    }
14888                }
14889                try {
14890                    observer.onPackageDeleted(packageName, returnCode, null);
14891                } catch (RemoteException e) {
14892                    Log.i(TAG, "Observer no longer exists.");
14893                } //end catch
14894            } //end run
14895        });
14896    }
14897
14898    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14899        int[] result = EMPTY_INT_ARRAY;
14900        for (int userId : userIds) {
14901            if (getBlockUninstallForUser(packageName, userId)) {
14902                result = ArrayUtils.appendInt(result, userId);
14903            }
14904        }
14905        return result;
14906    }
14907
14908    @Override
14909    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14910        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14911    }
14912
14913    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14914        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14915                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14916        try {
14917            if (dpm != null) {
14918                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14919                        /* callingUserOnly =*/ false);
14920                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14921                        : deviceOwnerComponentName.getPackageName();
14922                // Does the package contains the device owner?
14923                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14924                // this check is probably not needed, since DO should be registered as a device
14925                // admin on some user too. (Original bug for this: b/17657954)
14926                if (packageName.equals(deviceOwnerPackageName)) {
14927                    return true;
14928                }
14929                // Does it contain a device admin for any user?
14930                int[] users;
14931                if (userId == UserHandle.USER_ALL) {
14932                    users = sUserManager.getUserIds();
14933                } else {
14934                    users = new int[]{userId};
14935                }
14936                for (int i = 0; i < users.length; ++i) {
14937                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14938                        return true;
14939                    }
14940                }
14941            }
14942        } catch (RemoteException e) {
14943        }
14944        return false;
14945    }
14946
14947    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14948        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14949    }
14950
14951    /**
14952     *  This method is an internal method that could be get invoked either
14953     *  to delete an installed package or to clean up a failed installation.
14954     *  After deleting an installed package, a broadcast is sent to notify any
14955     *  listeners that the package has been removed. For cleaning up a failed
14956     *  installation, the broadcast is not necessary since the package's
14957     *  installation wouldn't have sent the initial broadcast either
14958     *  The key steps in deleting a package are
14959     *  deleting the package information in internal structures like mPackages,
14960     *  deleting the packages base directories through installd
14961     *  updating mSettings to reflect current status
14962     *  persisting settings for later use
14963     *  sending a broadcast if necessary
14964     */
14965    private int deletePackageX(String packageName, int userId, int deleteFlags) {
14966        final PackageRemovedInfo info = new PackageRemovedInfo();
14967        final boolean res;
14968
14969        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
14970                ? UserHandle.ALL : new UserHandle(userId);
14971
14972        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14973            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14974            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14975        }
14976
14977        PackageSetting uninstalledPs = null;
14978
14979        // for the uninstall-updates case and restricted profiles, remember the per-
14980        // user handle installed state
14981        int[] allUsers;
14982        synchronized (mPackages) {
14983            uninstalledPs = mSettings.mPackages.get(packageName);
14984            if (uninstalledPs == null) {
14985                Slog.w(TAG, "Not removing non-existent package " + packageName);
14986                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14987            }
14988            allUsers = sUserManager.getUserIds();
14989            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14990        }
14991
14992        synchronized (mInstallLock) {
14993            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14994            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
14995                    "deletePackageX")) {
14996                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
14997                        deleteFlags | REMOVE_CHATTY, info, true, null);
14998            }
14999            synchronized (mPackages) {
15000                if (res) {
15001                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15002                }
15003            }
15004        }
15005
15006        if (res) {
15007            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15008            info.sendPackageRemovedBroadcasts(killApp);
15009            info.sendSystemPackageUpdatedBroadcasts();
15010            info.sendSystemPackageAppearedBroadcasts();
15011        }
15012        // Force a gc here.
15013        Runtime.getRuntime().gc();
15014        // Delete the resources here after sending the broadcast to let
15015        // other processes clean up before deleting resources.
15016        if (info.args != null) {
15017            synchronized (mInstallLock) {
15018                info.args.doPostDeleteLI(true);
15019            }
15020        }
15021
15022        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15023    }
15024
15025    class PackageRemovedInfo {
15026        String removedPackage;
15027        int uid = -1;
15028        int removedAppId = -1;
15029        int[] origUsers;
15030        int[] removedUsers = null;
15031        boolean isRemovedPackageSystemUpdate = false;
15032        boolean isUpdate;
15033        boolean dataRemoved;
15034        boolean removedForAllUsers;
15035        // Clean up resources deleted packages.
15036        InstallArgs args = null;
15037        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15038        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15039
15040        void sendPackageRemovedBroadcasts(boolean killApp) {
15041            sendPackageRemovedBroadcastInternal(killApp);
15042            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15043            for (int i = 0; i < childCount; i++) {
15044                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15045                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15046            }
15047        }
15048
15049        void sendSystemPackageUpdatedBroadcasts() {
15050            if (isRemovedPackageSystemUpdate) {
15051                sendSystemPackageUpdatedBroadcastsInternal();
15052                final int childCount = (removedChildPackages != null)
15053                        ? removedChildPackages.size() : 0;
15054                for (int i = 0; i < childCount; i++) {
15055                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15056                    if (childInfo.isRemovedPackageSystemUpdate) {
15057                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15058                    }
15059                }
15060            }
15061        }
15062
15063        void sendSystemPackageAppearedBroadcasts() {
15064            final int packageCount = (appearedChildPackages != null)
15065                    ? appearedChildPackages.size() : 0;
15066            for (int i = 0; i < packageCount; i++) {
15067                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15068                for (int userId : installedInfo.newUsers) {
15069                    sendPackageAddedForUser(installedInfo.name, true,
15070                            UserHandle.getAppId(installedInfo.uid), userId);
15071                }
15072            }
15073        }
15074
15075        private void sendSystemPackageUpdatedBroadcastsInternal() {
15076            Bundle extras = new Bundle(2);
15077            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15078            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15079            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15080                    extras, 0, null, null, null);
15081            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15082                    extras, 0, null, null, null);
15083            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15084                    null, 0, removedPackage, null, null);
15085        }
15086
15087        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15088            Bundle extras = new Bundle(2);
15089            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15090            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15091            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15092            if (isUpdate || isRemovedPackageSystemUpdate) {
15093                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15094            }
15095            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15096            if (removedPackage != null) {
15097                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15098                        extras, 0, null, null, removedUsers);
15099                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15100                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15101                            removedPackage, extras, 0, null, null, removedUsers);
15102                }
15103            }
15104            if (removedAppId >= 0) {
15105                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15106                        removedUsers);
15107            }
15108        }
15109    }
15110
15111    /*
15112     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15113     * flag is not set, the data directory is removed as well.
15114     * make sure this flag is set for partially installed apps. If not its meaningless to
15115     * delete a partially installed application.
15116     */
15117    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15118            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15119        String packageName = ps.name;
15120        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15121        // Retrieve object to delete permissions for shared user later on
15122        final PackageParser.Package deletedPkg;
15123        final PackageSetting deletedPs;
15124        // reader
15125        synchronized (mPackages) {
15126            deletedPkg = mPackages.get(packageName);
15127            deletedPs = mSettings.mPackages.get(packageName);
15128            if (outInfo != null) {
15129                outInfo.removedPackage = packageName;
15130                outInfo.removedUsers = deletedPs != null
15131                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15132                        : null;
15133            }
15134        }
15135
15136        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15137
15138        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15139            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15140                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15141            destroyAppProfilesLIF(deletedPkg);
15142            if (outInfo != null) {
15143                outInfo.dataRemoved = true;
15144            }
15145            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15146        }
15147
15148        // writer
15149        synchronized (mPackages) {
15150            if (deletedPs != null) {
15151                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15152                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15153                    clearDefaultBrowserIfNeeded(packageName);
15154                    if (outInfo != null) {
15155                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15156                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15157                    }
15158                    updatePermissionsLPw(deletedPs.name, null, 0);
15159                    if (deletedPs.sharedUser != null) {
15160                        // Remove permissions associated with package. Since runtime
15161                        // permissions are per user we have to kill the removed package
15162                        // or packages running under the shared user of the removed
15163                        // package if revoking the permissions requested only by the removed
15164                        // package is successful and this causes a change in gids.
15165                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15166                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15167                                    userId);
15168                            if (userIdToKill == UserHandle.USER_ALL
15169                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15170                                // If gids changed for this user, kill all affected packages.
15171                                mHandler.post(new Runnable() {
15172                                    @Override
15173                                    public void run() {
15174                                        // This has to happen with no lock held.
15175                                        killApplication(deletedPs.name, deletedPs.appId,
15176                                                KILL_APP_REASON_GIDS_CHANGED);
15177                                    }
15178                                });
15179                                break;
15180                            }
15181                        }
15182                    }
15183                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15184                }
15185                // make sure to preserve per-user disabled state if this removal was just
15186                // a downgrade of a system app to the factory package
15187                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15188                    if (DEBUG_REMOVE) {
15189                        Slog.d(TAG, "Propagating install state across downgrade");
15190                    }
15191                    for (int userId : allUserHandles) {
15192                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15193                        if (DEBUG_REMOVE) {
15194                            Slog.d(TAG, "    user " + userId + " => " + installed);
15195                        }
15196                        ps.setInstalled(installed, userId);
15197                    }
15198                }
15199            }
15200            // can downgrade to reader
15201            if (writeSettings) {
15202                // Save settings now
15203                mSettings.writeLPr();
15204            }
15205        }
15206        if (outInfo != null) {
15207            // A user ID was deleted here. Go through all users and remove it
15208            // from KeyStore.
15209            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15210        }
15211    }
15212
15213    static boolean locationIsPrivileged(File path) {
15214        try {
15215            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15216                    .getCanonicalPath();
15217            return path.getCanonicalPath().startsWith(privilegedAppDir);
15218        } catch (IOException e) {
15219            Slog.e(TAG, "Unable to access code path " + path);
15220        }
15221        return false;
15222    }
15223
15224    /*
15225     * Tries to delete system package.
15226     */
15227    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15228            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15229            boolean writeSettings) {
15230        if (deletedPs.parentPackageName != null) {
15231            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15232            return false;
15233        }
15234
15235        final boolean applyUserRestrictions
15236                = (allUserHandles != null) && (outInfo.origUsers != null);
15237        final PackageSetting disabledPs;
15238        // Confirm if the system package has been updated
15239        // An updated system app can be deleted. This will also have to restore
15240        // the system pkg from system partition
15241        // reader
15242        synchronized (mPackages) {
15243            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15244        }
15245
15246        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15247                + " disabledPs=" + disabledPs);
15248
15249        if (disabledPs == null) {
15250            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15251            return false;
15252        } else if (DEBUG_REMOVE) {
15253            Slog.d(TAG, "Deleting system pkg from data partition");
15254        }
15255
15256        if (DEBUG_REMOVE) {
15257            if (applyUserRestrictions) {
15258                Slog.d(TAG, "Remembering install states:");
15259                for (int userId : allUserHandles) {
15260                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15261                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15262                }
15263            }
15264        }
15265
15266        // Delete the updated package
15267        outInfo.isRemovedPackageSystemUpdate = true;
15268        if (outInfo.removedChildPackages != null) {
15269            final int childCount = (deletedPs.childPackageNames != null)
15270                    ? deletedPs.childPackageNames.size() : 0;
15271            for (int i = 0; i < childCount; i++) {
15272                String childPackageName = deletedPs.childPackageNames.get(i);
15273                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15274                        .contains(childPackageName)) {
15275                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15276                            childPackageName);
15277                    if (childInfo != null) {
15278                        childInfo.isRemovedPackageSystemUpdate = true;
15279                    }
15280                }
15281            }
15282        }
15283
15284        if (disabledPs.versionCode < deletedPs.versionCode) {
15285            // Delete data for downgrades
15286            flags &= ~PackageManager.DELETE_KEEP_DATA;
15287        } else {
15288            // Preserve data by setting flag
15289            flags |= PackageManager.DELETE_KEEP_DATA;
15290        }
15291
15292        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15293                outInfo, writeSettings, disabledPs.pkg);
15294        if (!ret) {
15295            return false;
15296        }
15297
15298        // writer
15299        synchronized (mPackages) {
15300            // Reinstate the old system package
15301            enableSystemPackageLPw(disabledPs.pkg);
15302            // Remove any native libraries from the upgraded package.
15303            removeNativeBinariesLI(deletedPs);
15304        }
15305
15306        // Install the system package
15307        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15308        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
15309        if (locationIsPrivileged(disabledPs.codePath)) {
15310            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15311        }
15312
15313        final PackageParser.Package newPkg;
15314        try {
15315            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15316        } catch (PackageManagerException e) {
15317            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15318                    + e.getMessage());
15319            return false;
15320        }
15321
15322        prepareAppDataAfterInstallLIF(newPkg);
15323
15324        // writer
15325        synchronized (mPackages) {
15326            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15327
15328            // Propagate the permissions state as we do not want to drop on the floor
15329            // runtime permissions. The update permissions method below will take
15330            // care of removing obsolete permissions and grant install permissions.
15331            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15332            updatePermissionsLPw(newPkg.packageName, newPkg,
15333                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15334
15335            if (applyUserRestrictions) {
15336                if (DEBUG_REMOVE) {
15337                    Slog.d(TAG, "Propagating install state across reinstall");
15338                }
15339                for (int userId : allUserHandles) {
15340                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15341                    if (DEBUG_REMOVE) {
15342                        Slog.d(TAG, "    user " + userId + " => " + installed);
15343                    }
15344                    ps.setInstalled(installed, userId);
15345
15346                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15347                }
15348                // Regardless of writeSettings we need to ensure that this restriction
15349                // state propagation is persisted
15350                mSettings.writeAllUsersPackageRestrictionsLPr();
15351            }
15352            // can downgrade to reader here
15353            if (writeSettings) {
15354                mSettings.writeLPr();
15355            }
15356        }
15357        return true;
15358    }
15359
15360    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15361            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15362            PackageRemovedInfo outInfo, boolean writeSettings,
15363            PackageParser.Package replacingPackage) {
15364        synchronized (mPackages) {
15365            if (outInfo != null) {
15366                outInfo.uid = ps.appId;
15367            }
15368
15369            if (outInfo != null && outInfo.removedChildPackages != null) {
15370                final int childCount = (ps.childPackageNames != null)
15371                        ? ps.childPackageNames.size() : 0;
15372                for (int i = 0; i < childCount; i++) {
15373                    String childPackageName = ps.childPackageNames.get(i);
15374                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15375                    if (childPs == null) {
15376                        return false;
15377                    }
15378                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15379                            childPackageName);
15380                    if (childInfo != null) {
15381                        childInfo.uid = childPs.appId;
15382                    }
15383                }
15384            }
15385        }
15386
15387        // Delete package data from internal structures and also remove data if flag is set
15388        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15389
15390        // Delete the child packages data
15391        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15392        for (int i = 0; i < childCount; i++) {
15393            PackageSetting childPs;
15394            synchronized (mPackages) {
15395                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15396            }
15397            if (childPs != null) {
15398                PackageRemovedInfo childOutInfo = (outInfo != null
15399                        && outInfo.removedChildPackages != null)
15400                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15401                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15402                        && (replacingPackage != null
15403                        && !replacingPackage.hasChildPackage(childPs.name))
15404                        ? flags & ~DELETE_KEEP_DATA : flags;
15405                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15406                        deleteFlags, writeSettings);
15407            }
15408        }
15409
15410        // Delete application code and resources only for parent packages
15411        if (ps.parentPackageName == null) {
15412            if (deleteCodeAndResources && (outInfo != null)) {
15413                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15414                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15415                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15416            }
15417        }
15418
15419        return true;
15420    }
15421
15422    @Override
15423    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15424            int userId) {
15425        mContext.enforceCallingOrSelfPermission(
15426                android.Manifest.permission.DELETE_PACKAGES, null);
15427        synchronized (mPackages) {
15428            PackageSetting ps = mSettings.mPackages.get(packageName);
15429            if (ps == null) {
15430                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15431                return false;
15432            }
15433            if (!ps.getInstalled(userId)) {
15434                // Can't block uninstall for an app that is not installed or enabled.
15435                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15436                return false;
15437            }
15438            ps.setBlockUninstall(blockUninstall, userId);
15439            mSettings.writePackageRestrictionsLPr(userId);
15440        }
15441        return true;
15442    }
15443
15444    @Override
15445    public boolean getBlockUninstallForUser(String packageName, int userId) {
15446        synchronized (mPackages) {
15447            PackageSetting ps = mSettings.mPackages.get(packageName);
15448            if (ps == null) {
15449                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15450                return false;
15451            }
15452            return ps.getBlockUninstall(userId);
15453        }
15454    }
15455
15456    @Override
15457    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15458        int callingUid = Binder.getCallingUid();
15459        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15460            throw new SecurityException(
15461                    "setRequiredForSystemUser can only be run by the system or root");
15462        }
15463        synchronized (mPackages) {
15464            PackageSetting ps = mSettings.mPackages.get(packageName);
15465            if (ps == null) {
15466                Log.w(TAG, "Package doesn't exist: " + packageName);
15467                return false;
15468            }
15469            if (systemUserApp) {
15470                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15471            } else {
15472                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15473            }
15474            mSettings.writeLPr();
15475        }
15476        return true;
15477    }
15478
15479    /*
15480     * This method handles package deletion in general
15481     */
15482    private boolean deletePackageLIF(String packageName, UserHandle user,
15483            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15484            PackageRemovedInfo outInfo, boolean writeSettings,
15485            PackageParser.Package replacingPackage) {
15486        if (packageName == null) {
15487            Slog.w(TAG, "Attempt to delete null packageName.");
15488            return false;
15489        }
15490
15491        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15492
15493        PackageSetting ps;
15494
15495        synchronized (mPackages) {
15496            ps = mSettings.mPackages.get(packageName);
15497            if (ps == null) {
15498                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15499                return false;
15500            }
15501
15502            if (ps.parentPackageName != null && (!isSystemApp(ps)
15503                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15504                if (DEBUG_REMOVE) {
15505                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15506                            + ((user == null) ? UserHandle.USER_ALL : user));
15507                }
15508                final int removedUserId = (user != null) ? user.getIdentifier()
15509                        : UserHandle.USER_ALL;
15510                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15511                    return false;
15512                }
15513                markPackageUninstalledForUserLPw(ps, user);
15514                scheduleWritePackageRestrictionsLocked(user);
15515                return true;
15516            }
15517        }
15518
15519        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15520                && user.getIdentifier() != UserHandle.USER_ALL)) {
15521            // The caller is asking that the package only be deleted for a single
15522            // user.  To do this, we just mark its uninstalled state and delete
15523            // its data. If this is a system app, we only allow this to happen if
15524            // they have set the special DELETE_SYSTEM_APP which requests different
15525            // semantics than normal for uninstalling system apps.
15526            markPackageUninstalledForUserLPw(ps, user);
15527
15528            if (!isSystemApp(ps)) {
15529                // Do not uninstall the APK if an app should be cached
15530                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15531                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15532                    // Other user still have this package installed, so all
15533                    // we need to do is clear this user's data and save that
15534                    // it is uninstalled.
15535                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15536                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15537                        return false;
15538                    }
15539                    scheduleWritePackageRestrictionsLocked(user);
15540                    return true;
15541                } else {
15542                    // We need to set it back to 'installed' so the uninstall
15543                    // broadcasts will be sent correctly.
15544                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15545                    ps.setInstalled(true, user.getIdentifier());
15546                }
15547            } else {
15548                // This is a system app, so we assume that the
15549                // other users still have this package installed, so all
15550                // we need to do is clear this user's data and save that
15551                // it is uninstalled.
15552                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15553                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15554                    return false;
15555                }
15556                scheduleWritePackageRestrictionsLocked(user);
15557                return true;
15558            }
15559        }
15560
15561        // If we are deleting a composite package for all users, keep track
15562        // of result for each child.
15563        if (ps.childPackageNames != null && outInfo != null) {
15564            synchronized (mPackages) {
15565                final int childCount = ps.childPackageNames.size();
15566                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15567                for (int i = 0; i < childCount; i++) {
15568                    String childPackageName = ps.childPackageNames.get(i);
15569                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15570                    childInfo.removedPackage = childPackageName;
15571                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15572                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15573                    if (childPs != null) {
15574                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15575                    }
15576                }
15577            }
15578        }
15579
15580        boolean ret = false;
15581        if (isSystemApp(ps)) {
15582            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15583            // When an updated system application is deleted we delete the existing resources
15584            // as well and fall back to existing code in system partition
15585            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15586        } else {
15587            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15588            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15589                    outInfo, writeSettings, replacingPackage);
15590        }
15591
15592        // Take a note whether we deleted the package for all users
15593        if (outInfo != null) {
15594            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15595            if (outInfo.removedChildPackages != null) {
15596                synchronized (mPackages) {
15597                    final int childCount = outInfo.removedChildPackages.size();
15598                    for (int i = 0; i < childCount; i++) {
15599                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15600                        if (childInfo != null) {
15601                            childInfo.removedForAllUsers = mPackages.get(
15602                                    childInfo.removedPackage) == null;
15603                        }
15604                    }
15605                }
15606            }
15607            // If we uninstalled an update to a system app there may be some
15608            // child packages that appeared as they are declared in the system
15609            // app but were not declared in the update.
15610            if (isSystemApp(ps)) {
15611                synchronized (mPackages) {
15612                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15613                    final int childCount = (updatedPs.childPackageNames != null)
15614                            ? updatedPs.childPackageNames.size() : 0;
15615                    for (int i = 0; i < childCount; i++) {
15616                        String childPackageName = updatedPs.childPackageNames.get(i);
15617                        if (outInfo.removedChildPackages == null
15618                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15619                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15620                            if (childPs == null) {
15621                                continue;
15622                            }
15623                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15624                            installRes.name = childPackageName;
15625                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15626                            installRes.pkg = mPackages.get(childPackageName);
15627                            installRes.uid = childPs.pkg.applicationInfo.uid;
15628                            if (outInfo.appearedChildPackages == null) {
15629                                outInfo.appearedChildPackages = new ArrayMap<>();
15630                            }
15631                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15632                        }
15633                    }
15634                }
15635            }
15636        }
15637
15638        return ret;
15639    }
15640
15641    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15642        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15643                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15644        for (int nextUserId : userIds) {
15645            if (DEBUG_REMOVE) {
15646                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15647            }
15648            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15649                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15650                    false /*hidden*/, false /*suspended*/, null, null, null,
15651                    false /*blockUninstall*/,
15652                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15653        }
15654    }
15655
15656    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15657            PackageRemovedInfo outInfo) {
15658        final PackageParser.Package pkg;
15659        synchronized (mPackages) {
15660            pkg = mPackages.get(ps.name);
15661        }
15662
15663        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15664                : new int[] {userId};
15665        for (int nextUserId : userIds) {
15666            if (DEBUG_REMOVE) {
15667                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15668                        + nextUserId);
15669            }
15670
15671            destroyAppDataLIF(pkg, userId,
15672                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15673            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15674            schedulePackageCleaning(ps.name, nextUserId, false);
15675            synchronized (mPackages) {
15676                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15677                    scheduleWritePackageRestrictionsLocked(nextUserId);
15678                }
15679                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15680            }
15681        }
15682
15683        if (outInfo != null) {
15684            outInfo.removedPackage = ps.name;
15685            outInfo.removedAppId = ps.appId;
15686            outInfo.removedUsers = userIds;
15687        }
15688
15689        return true;
15690    }
15691
15692    private final class ClearStorageConnection implements ServiceConnection {
15693        IMediaContainerService mContainerService;
15694
15695        @Override
15696        public void onServiceConnected(ComponentName name, IBinder service) {
15697            synchronized (this) {
15698                mContainerService = IMediaContainerService.Stub.asInterface(service);
15699                notifyAll();
15700            }
15701        }
15702
15703        @Override
15704        public void onServiceDisconnected(ComponentName name) {
15705        }
15706    }
15707
15708    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15709        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15710
15711        final boolean mounted;
15712        if (Environment.isExternalStorageEmulated()) {
15713            mounted = true;
15714        } else {
15715            final String status = Environment.getExternalStorageState();
15716
15717            mounted = status.equals(Environment.MEDIA_MOUNTED)
15718                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15719        }
15720
15721        if (!mounted) {
15722            return;
15723        }
15724
15725        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15726        int[] users;
15727        if (userId == UserHandle.USER_ALL) {
15728            users = sUserManager.getUserIds();
15729        } else {
15730            users = new int[] { userId };
15731        }
15732        final ClearStorageConnection conn = new ClearStorageConnection();
15733        if (mContext.bindServiceAsUser(
15734                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15735            try {
15736                for (int curUser : users) {
15737                    long timeout = SystemClock.uptimeMillis() + 5000;
15738                    synchronized (conn) {
15739                        long now = SystemClock.uptimeMillis();
15740                        while (conn.mContainerService == null && now < timeout) {
15741                            try {
15742                                conn.wait(timeout - now);
15743                            } catch (InterruptedException e) {
15744                            }
15745                        }
15746                    }
15747                    if (conn.mContainerService == null) {
15748                        return;
15749                    }
15750
15751                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15752                    clearDirectory(conn.mContainerService,
15753                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15754                    if (allData) {
15755                        clearDirectory(conn.mContainerService,
15756                                userEnv.buildExternalStorageAppDataDirs(packageName));
15757                        clearDirectory(conn.mContainerService,
15758                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15759                    }
15760                }
15761            } finally {
15762                mContext.unbindService(conn);
15763            }
15764        }
15765    }
15766
15767    @Override
15768    public void clearApplicationProfileData(String packageName) {
15769        enforceSystemOrRoot("Only the system can clear all profile data");
15770
15771        final PackageParser.Package pkg;
15772        synchronized (mPackages) {
15773            pkg = mPackages.get(packageName);
15774        }
15775
15776        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15777            synchronized (mInstallLock) {
15778                clearAppProfilesLIF(pkg);
15779            }
15780        }
15781    }
15782
15783    @Override
15784    public void clearApplicationUserData(final String packageName,
15785            final IPackageDataObserver observer, final int userId) {
15786        mContext.enforceCallingOrSelfPermission(
15787                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15788
15789        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15790                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15791
15792        final DevicePolicyManagerInternal dpmi = LocalServices
15793                .getService(DevicePolicyManagerInternal.class);
15794        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15795            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15796        }
15797        // Queue up an async operation since the package deletion may take a little while.
15798        mHandler.post(new Runnable() {
15799            public void run() {
15800                mHandler.removeCallbacks(this);
15801                final boolean succeeded;
15802                try (PackageFreezer freezer = freezePackage(packageName,
15803                        "clearApplicationUserData")) {
15804                    synchronized (mInstallLock) {
15805                        succeeded = clearApplicationUserDataLIF(packageName, userId);
15806                    }
15807                    clearExternalStorageDataSync(packageName, userId, true);
15808                }
15809                if (succeeded) {
15810                    // invoke DeviceStorageMonitor's update method to clear any notifications
15811                    DeviceStorageMonitorInternal dsm = LocalServices
15812                            .getService(DeviceStorageMonitorInternal.class);
15813                    if (dsm != null) {
15814                        dsm.checkMemory();
15815                    }
15816                }
15817                if(observer != null) {
15818                    try {
15819                        observer.onRemoveCompleted(packageName, succeeded);
15820                    } catch (RemoteException e) {
15821                        Log.i(TAG, "Observer no longer exists.");
15822                    }
15823                } //end if observer
15824            } //end run
15825        });
15826    }
15827
15828    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
15829        if (packageName == null) {
15830            Slog.w(TAG, "Attempt to delete null packageName.");
15831            return false;
15832        }
15833
15834        // Try finding details about the requested package
15835        PackageParser.Package pkg;
15836        synchronized (mPackages) {
15837            pkg = mPackages.get(packageName);
15838            if (pkg == null) {
15839                final PackageSetting ps = mSettings.mPackages.get(packageName);
15840                if (ps != null) {
15841                    pkg = ps.pkg;
15842                }
15843            }
15844
15845            if (pkg == null) {
15846                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15847                return false;
15848            }
15849
15850            PackageSetting ps = (PackageSetting) pkg.mExtras;
15851            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15852        }
15853
15854        clearAppDataLIF(pkg, userId,
15855                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15856
15857        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15858        removeKeystoreDataIfNeeded(userId, appId);
15859
15860        final UserManager um = mContext.getSystemService(UserManager.class);
15861        final int flags;
15862        if (um.isUserUnlocked(userId)) {
15863            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
15864        } else if (um.isUserRunning(userId)) {
15865            flags = StorageManager.FLAG_STORAGE_DE;
15866        } else {
15867            flags = 0;
15868        }
15869        prepareAppDataContentsLIF(pkg, userId, flags);
15870
15871        return true;
15872    }
15873
15874    /**
15875     * Reverts user permission state changes (permissions and flags) in
15876     * all packages for a given user.
15877     *
15878     * @param userId The device user for which to do a reset.
15879     */
15880    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15881        final int packageCount = mPackages.size();
15882        for (int i = 0; i < packageCount; i++) {
15883            PackageParser.Package pkg = mPackages.valueAt(i);
15884            PackageSetting ps = (PackageSetting) pkg.mExtras;
15885            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15886        }
15887    }
15888
15889    /**
15890     * Reverts user permission state changes (permissions and flags).
15891     *
15892     * @param ps The package for which to reset.
15893     * @param userId The device user for which to do a reset.
15894     */
15895    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15896            final PackageSetting ps, final int userId) {
15897        if (ps.pkg == null) {
15898            return;
15899        }
15900
15901        // These are flags that can change base on user actions.
15902        final int userSettableMask = FLAG_PERMISSION_USER_SET
15903                | FLAG_PERMISSION_USER_FIXED
15904                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15905                | FLAG_PERMISSION_REVIEW_REQUIRED;
15906
15907        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15908                | FLAG_PERMISSION_POLICY_FIXED;
15909
15910        boolean writeInstallPermissions = false;
15911        boolean writeRuntimePermissions = false;
15912
15913        final int permissionCount = ps.pkg.requestedPermissions.size();
15914        for (int i = 0; i < permissionCount; i++) {
15915            String permission = ps.pkg.requestedPermissions.get(i);
15916
15917            BasePermission bp = mSettings.mPermissions.get(permission);
15918            if (bp == null) {
15919                continue;
15920            }
15921
15922            // If shared user we just reset the state to which only this app contributed.
15923            if (ps.sharedUser != null) {
15924                boolean used = false;
15925                final int packageCount = ps.sharedUser.packages.size();
15926                for (int j = 0; j < packageCount; j++) {
15927                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15928                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15929                            && pkg.pkg.requestedPermissions.contains(permission)) {
15930                        used = true;
15931                        break;
15932                    }
15933                }
15934                if (used) {
15935                    continue;
15936                }
15937            }
15938
15939            PermissionsState permissionsState = ps.getPermissionsState();
15940
15941            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15942
15943            // Always clear the user settable flags.
15944            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15945                    bp.name) != null;
15946            // If permission review is enabled and this is a legacy app, mark the
15947            // permission as requiring a review as this is the initial state.
15948            int flags = 0;
15949            if (Build.PERMISSIONS_REVIEW_REQUIRED
15950                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15951                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15952            }
15953            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15954                if (hasInstallState) {
15955                    writeInstallPermissions = true;
15956                } else {
15957                    writeRuntimePermissions = true;
15958                }
15959            }
15960
15961            // Below is only runtime permission handling.
15962            if (!bp.isRuntime()) {
15963                continue;
15964            }
15965
15966            // Never clobber system or policy.
15967            if ((oldFlags & policyOrSystemFlags) != 0) {
15968                continue;
15969            }
15970
15971            // If this permission was granted by default, make sure it is.
15972            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15973                if (permissionsState.grantRuntimePermission(bp, userId)
15974                        != PERMISSION_OPERATION_FAILURE) {
15975                    writeRuntimePermissions = true;
15976                }
15977            // If permission review is enabled the permissions for a legacy apps
15978            // are represented as constantly granted runtime ones, so don't revoke.
15979            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15980                // Otherwise, reset the permission.
15981                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15982                switch (revokeResult) {
15983                    case PERMISSION_OPERATION_SUCCESS:
15984                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15985                        writeRuntimePermissions = true;
15986                        final int appId = ps.appId;
15987                        mHandler.post(new Runnable() {
15988                            @Override
15989                            public void run() {
15990                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
15991                            }
15992                        });
15993                    } break;
15994                }
15995            }
15996        }
15997
15998        // Synchronously write as we are taking permissions away.
15999        if (writeRuntimePermissions) {
16000            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16001        }
16002
16003        // Synchronously write as we are taking permissions away.
16004        if (writeInstallPermissions) {
16005            mSettings.writeLPr();
16006        }
16007    }
16008
16009    /**
16010     * Remove entries from the keystore daemon. Will only remove it if the
16011     * {@code appId} is valid.
16012     */
16013    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16014        if (appId < 0) {
16015            return;
16016        }
16017
16018        final KeyStore keyStore = KeyStore.getInstance();
16019        if (keyStore != null) {
16020            if (userId == UserHandle.USER_ALL) {
16021                for (final int individual : sUserManager.getUserIds()) {
16022                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16023                }
16024            } else {
16025                keyStore.clearUid(UserHandle.getUid(userId, appId));
16026            }
16027        } else {
16028            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16029        }
16030    }
16031
16032    @Override
16033    public void deleteApplicationCacheFiles(final String packageName,
16034            final IPackageDataObserver observer) {
16035        mContext.enforceCallingOrSelfPermission(
16036                android.Manifest.permission.DELETE_CACHE_FILES, null);
16037        // Queue up an async operation since the package deletion may take a little while.
16038        final int userId = UserHandle.getCallingUserId();
16039
16040        final PackageParser.Package pkg;
16041        synchronized (mPackages) {
16042            pkg = mPackages.get(packageName);
16043        }
16044
16045        mHandler.post(new Runnable() {
16046            public void run() {
16047                try (PackageFreezer freezer = freezePackage(packageName,
16048                        "deleteApplicationCacheFiles")) {
16049                    synchronized (mInstallLock) {
16050                        final int flags = StorageManager.FLAG_STORAGE_DE
16051                                | StorageManager.FLAG_STORAGE_CE;
16052                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16053                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16054                    }
16055                    clearExternalStorageDataSync(packageName, userId, false);
16056                }
16057                if (observer != null) {
16058                    try {
16059                        observer.onRemoveCompleted(packageName, true);
16060                    } catch (RemoteException e) {
16061                        Log.i(TAG, "Observer no longer exists.");
16062                    }
16063                }
16064            }
16065        });
16066    }
16067
16068    @Override
16069    public void getPackageSizeInfo(final String packageName, int userHandle,
16070            final IPackageStatsObserver observer) {
16071        mContext.enforceCallingOrSelfPermission(
16072                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16073        if (packageName == null) {
16074            throw new IllegalArgumentException("Attempt to get size of null packageName");
16075        }
16076
16077        PackageStats stats = new PackageStats(packageName, userHandle);
16078
16079        /*
16080         * Queue up an async operation since the package measurement may take a
16081         * little while.
16082         */
16083        Message msg = mHandler.obtainMessage(INIT_COPY);
16084        msg.obj = new MeasureParams(stats, observer);
16085        mHandler.sendMessage(msg);
16086    }
16087
16088    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16089        final PackageSetting ps;
16090        synchronized (mPackages) {
16091            ps = mSettings.mPackages.get(packageName);
16092            if (ps == null) {
16093                Slog.w(TAG, "Failed to find settings for " + packageName);
16094                return false;
16095            }
16096        }
16097        try {
16098            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16099                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16100                    ps.getCeDataInode(userId), ps.codePathString, stats);
16101            return true;
16102        } catch (InstallerException e) {
16103            Slog.w(TAG, String.valueOf(e));
16104            return false;
16105        }
16106    }
16107
16108    private int getUidTargetSdkVersionLockedLPr(int uid) {
16109        Object obj = mSettings.getUserIdLPr(uid);
16110        if (obj instanceof SharedUserSetting) {
16111            final SharedUserSetting sus = (SharedUserSetting) obj;
16112            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16113            final Iterator<PackageSetting> it = sus.packages.iterator();
16114            while (it.hasNext()) {
16115                final PackageSetting ps = it.next();
16116                if (ps.pkg != null) {
16117                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16118                    if (v < vers) vers = v;
16119                }
16120            }
16121            return vers;
16122        } else if (obj instanceof PackageSetting) {
16123            final PackageSetting ps = (PackageSetting) obj;
16124            if (ps.pkg != null) {
16125                return ps.pkg.applicationInfo.targetSdkVersion;
16126            }
16127        }
16128        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16129    }
16130
16131    @Override
16132    public void addPreferredActivity(IntentFilter filter, int match,
16133            ComponentName[] set, ComponentName activity, int userId) {
16134        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16135                "Adding preferred");
16136    }
16137
16138    private void addPreferredActivityInternal(IntentFilter filter, int match,
16139            ComponentName[] set, ComponentName activity, boolean always, int userId,
16140            String opname) {
16141        // writer
16142        int callingUid = Binder.getCallingUid();
16143        enforceCrossUserPermission(callingUid, userId,
16144                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16145        if (filter.countActions() == 0) {
16146            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16147            return;
16148        }
16149        synchronized (mPackages) {
16150            if (mContext.checkCallingOrSelfPermission(
16151                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16152                    != PackageManager.PERMISSION_GRANTED) {
16153                if (getUidTargetSdkVersionLockedLPr(callingUid)
16154                        < Build.VERSION_CODES.FROYO) {
16155                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16156                            + callingUid);
16157                    return;
16158                }
16159                mContext.enforceCallingOrSelfPermission(
16160                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16161            }
16162
16163            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16164            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16165                    + userId + ":");
16166            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16167            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16168            scheduleWritePackageRestrictionsLocked(userId);
16169        }
16170    }
16171
16172    @Override
16173    public void replacePreferredActivity(IntentFilter filter, int match,
16174            ComponentName[] set, ComponentName activity, int userId) {
16175        if (filter.countActions() != 1) {
16176            throw new IllegalArgumentException(
16177                    "replacePreferredActivity expects filter to have only 1 action.");
16178        }
16179        if (filter.countDataAuthorities() != 0
16180                || filter.countDataPaths() != 0
16181                || filter.countDataSchemes() > 1
16182                || filter.countDataTypes() != 0) {
16183            throw new IllegalArgumentException(
16184                    "replacePreferredActivity expects filter to have no data authorities, " +
16185                    "paths, or types; and at most one scheme.");
16186        }
16187
16188        final int callingUid = Binder.getCallingUid();
16189        enforceCrossUserPermission(callingUid, userId,
16190                true /* requireFullPermission */, false /* checkShell */,
16191                "replace preferred activity");
16192        synchronized (mPackages) {
16193            if (mContext.checkCallingOrSelfPermission(
16194                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16195                    != PackageManager.PERMISSION_GRANTED) {
16196                if (getUidTargetSdkVersionLockedLPr(callingUid)
16197                        < Build.VERSION_CODES.FROYO) {
16198                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16199                            + Binder.getCallingUid());
16200                    return;
16201                }
16202                mContext.enforceCallingOrSelfPermission(
16203                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16204            }
16205
16206            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16207            if (pir != null) {
16208                // Get all of the existing entries that exactly match this filter.
16209                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16210                if (existing != null && existing.size() == 1) {
16211                    PreferredActivity cur = existing.get(0);
16212                    if (DEBUG_PREFERRED) {
16213                        Slog.i(TAG, "Checking replace of preferred:");
16214                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16215                        if (!cur.mPref.mAlways) {
16216                            Slog.i(TAG, "  -- CUR; not mAlways!");
16217                        } else {
16218                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16219                            Slog.i(TAG, "  -- CUR: mSet="
16220                                    + Arrays.toString(cur.mPref.mSetComponents));
16221                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16222                            Slog.i(TAG, "  -- NEW: mMatch="
16223                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16224                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16225                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16226                        }
16227                    }
16228                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16229                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16230                            && cur.mPref.sameSet(set)) {
16231                        // Setting the preferred activity to what it happens to be already
16232                        if (DEBUG_PREFERRED) {
16233                            Slog.i(TAG, "Replacing with same preferred activity "
16234                                    + cur.mPref.mShortComponent + " for user "
16235                                    + userId + ":");
16236                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16237                        }
16238                        return;
16239                    }
16240                }
16241
16242                if (existing != null) {
16243                    if (DEBUG_PREFERRED) {
16244                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16245                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16246                    }
16247                    for (int i = 0; i < existing.size(); i++) {
16248                        PreferredActivity pa = existing.get(i);
16249                        if (DEBUG_PREFERRED) {
16250                            Slog.i(TAG, "Removing existing preferred activity "
16251                                    + pa.mPref.mComponent + ":");
16252                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16253                        }
16254                        pir.removeFilter(pa);
16255                    }
16256                }
16257            }
16258            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16259                    "Replacing preferred");
16260        }
16261    }
16262
16263    @Override
16264    public void clearPackagePreferredActivities(String packageName) {
16265        final int uid = Binder.getCallingUid();
16266        // writer
16267        synchronized (mPackages) {
16268            PackageParser.Package pkg = mPackages.get(packageName);
16269            if (pkg == null || pkg.applicationInfo.uid != uid) {
16270                if (mContext.checkCallingOrSelfPermission(
16271                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16272                        != PackageManager.PERMISSION_GRANTED) {
16273                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16274                            < Build.VERSION_CODES.FROYO) {
16275                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16276                                + Binder.getCallingUid());
16277                        return;
16278                    }
16279                    mContext.enforceCallingOrSelfPermission(
16280                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16281                }
16282            }
16283
16284            int user = UserHandle.getCallingUserId();
16285            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16286                scheduleWritePackageRestrictionsLocked(user);
16287            }
16288        }
16289    }
16290
16291    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16292    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16293        ArrayList<PreferredActivity> removed = null;
16294        boolean changed = false;
16295        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16296            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16297            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16298            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16299                continue;
16300            }
16301            Iterator<PreferredActivity> it = pir.filterIterator();
16302            while (it.hasNext()) {
16303                PreferredActivity pa = it.next();
16304                // Mark entry for removal only if it matches the package name
16305                // and the entry is of type "always".
16306                if (packageName == null ||
16307                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16308                                && pa.mPref.mAlways)) {
16309                    if (removed == null) {
16310                        removed = new ArrayList<PreferredActivity>();
16311                    }
16312                    removed.add(pa);
16313                }
16314            }
16315            if (removed != null) {
16316                for (int j=0; j<removed.size(); j++) {
16317                    PreferredActivity pa = removed.get(j);
16318                    pir.removeFilter(pa);
16319                }
16320                changed = true;
16321            }
16322        }
16323        return changed;
16324    }
16325
16326    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16327    private void clearIntentFilterVerificationsLPw(int userId) {
16328        final int packageCount = mPackages.size();
16329        for (int i = 0; i < packageCount; i++) {
16330            PackageParser.Package pkg = mPackages.valueAt(i);
16331            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16332        }
16333    }
16334
16335    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16336    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16337        if (userId == UserHandle.USER_ALL) {
16338            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16339                    sUserManager.getUserIds())) {
16340                for (int oneUserId : sUserManager.getUserIds()) {
16341                    scheduleWritePackageRestrictionsLocked(oneUserId);
16342                }
16343            }
16344        } else {
16345            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16346                scheduleWritePackageRestrictionsLocked(userId);
16347            }
16348        }
16349    }
16350
16351    void clearDefaultBrowserIfNeeded(String packageName) {
16352        for (int oneUserId : sUserManager.getUserIds()) {
16353            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16354            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16355            if (packageName.equals(defaultBrowserPackageName)) {
16356                setDefaultBrowserPackageName(null, oneUserId);
16357            }
16358        }
16359    }
16360
16361    @Override
16362    public void resetApplicationPreferences(int userId) {
16363        mContext.enforceCallingOrSelfPermission(
16364                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16365        // writer
16366        synchronized (mPackages) {
16367            final long identity = Binder.clearCallingIdentity();
16368            try {
16369                clearPackagePreferredActivitiesLPw(null, userId);
16370                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16371                // TODO: We have to reset the default SMS and Phone. This requires
16372                // significant refactoring to keep all default apps in the package
16373                // manager (cleaner but more work) or have the services provide
16374                // callbacks to the package manager to request a default app reset.
16375                applyFactoryDefaultBrowserLPw(userId);
16376                clearIntentFilterVerificationsLPw(userId);
16377                primeDomainVerificationsLPw(userId);
16378                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16379                scheduleWritePackageRestrictionsLocked(userId);
16380            } finally {
16381                Binder.restoreCallingIdentity(identity);
16382            }
16383        }
16384    }
16385
16386    @Override
16387    public int getPreferredActivities(List<IntentFilter> outFilters,
16388            List<ComponentName> outActivities, String packageName) {
16389
16390        int num = 0;
16391        final int userId = UserHandle.getCallingUserId();
16392        // reader
16393        synchronized (mPackages) {
16394            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16395            if (pir != null) {
16396                final Iterator<PreferredActivity> it = pir.filterIterator();
16397                while (it.hasNext()) {
16398                    final PreferredActivity pa = it.next();
16399                    if (packageName == null
16400                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16401                                    && pa.mPref.mAlways)) {
16402                        if (outFilters != null) {
16403                            outFilters.add(new IntentFilter(pa));
16404                        }
16405                        if (outActivities != null) {
16406                            outActivities.add(pa.mPref.mComponent);
16407                        }
16408                    }
16409                }
16410            }
16411        }
16412
16413        return num;
16414    }
16415
16416    @Override
16417    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16418            int userId) {
16419        int callingUid = Binder.getCallingUid();
16420        if (callingUid != Process.SYSTEM_UID) {
16421            throw new SecurityException(
16422                    "addPersistentPreferredActivity can only be run by the system");
16423        }
16424        if (filter.countActions() == 0) {
16425            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16426            return;
16427        }
16428        synchronized (mPackages) {
16429            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16430                    ":");
16431            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16432            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16433                    new PersistentPreferredActivity(filter, activity));
16434            scheduleWritePackageRestrictionsLocked(userId);
16435        }
16436    }
16437
16438    @Override
16439    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16440        int callingUid = Binder.getCallingUid();
16441        if (callingUid != Process.SYSTEM_UID) {
16442            throw new SecurityException(
16443                    "clearPackagePersistentPreferredActivities can only be run by the system");
16444        }
16445        ArrayList<PersistentPreferredActivity> removed = null;
16446        boolean changed = false;
16447        synchronized (mPackages) {
16448            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16449                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16450                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16451                        .valueAt(i);
16452                if (userId != thisUserId) {
16453                    continue;
16454                }
16455                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16456                while (it.hasNext()) {
16457                    PersistentPreferredActivity ppa = it.next();
16458                    // Mark entry for removal only if it matches the package name.
16459                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16460                        if (removed == null) {
16461                            removed = new ArrayList<PersistentPreferredActivity>();
16462                        }
16463                        removed.add(ppa);
16464                    }
16465                }
16466                if (removed != null) {
16467                    for (int j=0; j<removed.size(); j++) {
16468                        PersistentPreferredActivity ppa = removed.get(j);
16469                        ppir.removeFilter(ppa);
16470                    }
16471                    changed = true;
16472                }
16473            }
16474
16475            if (changed) {
16476                scheduleWritePackageRestrictionsLocked(userId);
16477            }
16478        }
16479    }
16480
16481    /**
16482     * Common machinery for picking apart a restored XML blob and passing
16483     * it to a caller-supplied functor to be applied to the running system.
16484     */
16485    private void restoreFromXml(XmlPullParser parser, int userId,
16486            String expectedStartTag, BlobXmlRestorer functor)
16487            throws IOException, XmlPullParserException {
16488        int type;
16489        while ((type = parser.next()) != XmlPullParser.START_TAG
16490                && type != XmlPullParser.END_DOCUMENT) {
16491        }
16492        if (type != XmlPullParser.START_TAG) {
16493            // oops didn't find a start tag?!
16494            if (DEBUG_BACKUP) {
16495                Slog.e(TAG, "Didn't find start tag during restore");
16496            }
16497            return;
16498        }
16499Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16500        // this is supposed to be TAG_PREFERRED_BACKUP
16501        if (!expectedStartTag.equals(parser.getName())) {
16502            if (DEBUG_BACKUP) {
16503                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16504            }
16505            return;
16506        }
16507
16508        // skip interfering stuff, then we're aligned with the backing implementation
16509        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16510Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16511        functor.apply(parser, userId);
16512    }
16513
16514    private interface BlobXmlRestorer {
16515        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16516    }
16517
16518    /**
16519     * Non-Binder method, support for the backup/restore mechanism: write the
16520     * full set of preferred activities in its canonical XML format.  Returns the
16521     * XML output as a byte array, or null if there is none.
16522     */
16523    @Override
16524    public byte[] getPreferredActivityBackup(int userId) {
16525        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16526            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16527        }
16528
16529        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16530        try {
16531            final XmlSerializer serializer = new FastXmlSerializer();
16532            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16533            serializer.startDocument(null, true);
16534            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16535
16536            synchronized (mPackages) {
16537                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16538            }
16539
16540            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16541            serializer.endDocument();
16542            serializer.flush();
16543        } catch (Exception e) {
16544            if (DEBUG_BACKUP) {
16545                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16546            }
16547            return null;
16548        }
16549
16550        return dataStream.toByteArray();
16551    }
16552
16553    @Override
16554    public void restorePreferredActivities(byte[] backup, int userId) {
16555        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16556            throw new SecurityException("Only the system may call restorePreferredActivities()");
16557        }
16558
16559        try {
16560            final XmlPullParser parser = Xml.newPullParser();
16561            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16562            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16563                    new BlobXmlRestorer() {
16564                        @Override
16565                        public void apply(XmlPullParser parser, int userId)
16566                                throws XmlPullParserException, IOException {
16567                            synchronized (mPackages) {
16568                                mSettings.readPreferredActivitiesLPw(parser, userId);
16569                            }
16570                        }
16571                    } );
16572        } catch (Exception e) {
16573            if (DEBUG_BACKUP) {
16574                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16575            }
16576        }
16577    }
16578
16579    /**
16580     * Non-Binder method, support for the backup/restore mechanism: write the
16581     * default browser (etc) settings in its canonical XML format.  Returns the default
16582     * browser XML representation as a byte array, or null if there is none.
16583     */
16584    @Override
16585    public byte[] getDefaultAppsBackup(int userId) {
16586        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16587            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16588        }
16589
16590        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16591        try {
16592            final XmlSerializer serializer = new FastXmlSerializer();
16593            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16594            serializer.startDocument(null, true);
16595            serializer.startTag(null, TAG_DEFAULT_APPS);
16596
16597            synchronized (mPackages) {
16598                mSettings.writeDefaultAppsLPr(serializer, userId);
16599            }
16600
16601            serializer.endTag(null, TAG_DEFAULT_APPS);
16602            serializer.endDocument();
16603            serializer.flush();
16604        } catch (Exception e) {
16605            if (DEBUG_BACKUP) {
16606                Slog.e(TAG, "Unable to write default apps for backup", e);
16607            }
16608            return null;
16609        }
16610
16611        return dataStream.toByteArray();
16612    }
16613
16614    @Override
16615    public void restoreDefaultApps(byte[] backup, int userId) {
16616        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16617            throw new SecurityException("Only the system may call restoreDefaultApps()");
16618        }
16619
16620        try {
16621            final XmlPullParser parser = Xml.newPullParser();
16622            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16623            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16624                    new BlobXmlRestorer() {
16625                        @Override
16626                        public void apply(XmlPullParser parser, int userId)
16627                                throws XmlPullParserException, IOException {
16628                            synchronized (mPackages) {
16629                                mSettings.readDefaultAppsLPw(parser, userId);
16630                            }
16631                        }
16632                    } );
16633        } catch (Exception e) {
16634            if (DEBUG_BACKUP) {
16635                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16636            }
16637        }
16638    }
16639
16640    @Override
16641    public byte[] getIntentFilterVerificationBackup(int userId) {
16642        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16643            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16644        }
16645
16646        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16647        try {
16648            final XmlSerializer serializer = new FastXmlSerializer();
16649            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16650            serializer.startDocument(null, true);
16651            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16652
16653            synchronized (mPackages) {
16654                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16655            }
16656
16657            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16658            serializer.endDocument();
16659            serializer.flush();
16660        } catch (Exception e) {
16661            if (DEBUG_BACKUP) {
16662                Slog.e(TAG, "Unable to write default apps for backup", e);
16663            }
16664            return null;
16665        }
16666
16667        return dataStream.toByteArray();
16668    }
16669
16670    @Override
16671    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16672        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16673            throw new SecurityException("Only the system may call restorePreferredActivities()");
16674        }
16675
16676        try {
16677            final XmlPullParser parser = Xml.newPullParser();
16678            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16679            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16680                    new BlobXmlRestorer() {
16681                        @Override
16682                        public void apply(XmlPullParser parser, int userId)
16683                                throws XmlPullParserException, IOException {
16684                            synchronized (mPackages) {
16685                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16686                                mSettings.writeLPr();
16687                            }
16688                        }
16689                    } );
16690        } catch (Exception e) {
16691            if (DEBUG_BACKUP) {
16692                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16693            }
16694        }
16695    }
16696
16697    @Override
16698    public byte[] getPermissionGrantBackup(int userId) {
16699        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16700            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16701        }
16702
16703        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16704        try {
16705            final XmlSerializer serializer = new FastXmlSerializer();
16706            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16707            serializer.startDocument(null, true);
16708            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16709
16710            synchronized (mPackages) {
16711                serializeRuntimePermissionGrantsLPr(serializer, userId);
16712            }
16713
16714            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16715            serializer.endDocument();
16716            serializer.flush();
16717        } catch (Exception e) {
16718            if (DEBUG_BACKUP) {
16719                Slog.e(TAG, "Unable to write default apps for backup", e);
16720            }
16721            return null;
16722        }
16723
16724        return dataStream.toByteArray();
16725    }
16726
16727    @Override
16728    public void restorePermissionGrants(byte[] backup, int userId) {
16729        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16730            throw new SecurityException("Only the system may call restorePermissionGrants()");
16731        }
16732
16733        try {
16734            final XmlPullParser parser = Xml.newPullParser();
16735            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16736            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16737                    new BlobXmlRestorer() {
16738                        @Override
16739                        public void apply(XmlPullParser parser, int userId)
16740                                throws XmlPullParserException, IOException {
16741                            synchronized (mPackages) {
16742                                processRestoredPermissionGrantsLPr(parser, userId);
16743                            }
16744                        }
16745                    } );
16746        } catch (Exception e) {
16747            if (DEBUG_BACKUP) {
16748                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16749            }
16750        }
16751    }
16752
16753    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16754            throws IOException {
16755        serializer.startTag(null, TAG_ALL_GRANTS);
16756
16757        final int N = mSettings.mPackages.size();
16758        for (int i = 0; i < N; i++) {
16759            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16760            boolean pkgGrantsKnown = false;
16761
16762            PermissionsState packagePerms = ps.getPermissionsState();
16763
16764            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16765                final int grantFlags = state.getFlags();
16766                // only look at grants that are not system/policy fixed
16767                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16768                    final boolean isGranted = state.isGranted();
16769                    // And only back up the user-twiddled state bits
16770                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16771                        final String packageName = mSettings.mPackages.keyAt(i);
16772                        if (!pkgGrantsKnown) {
16773                            serializer.startTag(null, TAG_GRANT);
16774                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16775                            pkgGrantsKnown = true;
16776                        }
16777
16778                        final boolean userSet =
16779                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16780                        final boolean userFixed =
16781                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16782                        final boolean revoke =
16783                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16784
16785                        serializer.startTag(null, TAG_PERMISSION);
16786                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16787                        if (isGranted) {
16788                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16789                        }
16790                        if (userSet) {
16791                            serializer.attribute(null, ATTR_USER_SET, "true");
16792                        }
16793                        if (userFixed) {
16794                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16795                        }
16796                        if (revoke) {
16797                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16798                        }
16799                        serializer.endTag(null, TAG_PERMISSION);
16800                    }
16801                }
16802            }
16803
16804            if (pkgGrantsKnown) {
16805                serializer.endTag(null, TAG_GRANT);
16806            }
16807        }
16808
16809        serializer.endTag(null, TAG_ALL_GRANTS);
16810    }
16811
16812    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16813            throws XmlPullParserException, IOException {
16814        String pkgName = null;
16815        int outerDepth = parser.getDepth();
16816        int type;
16817        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16818                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16819            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16820                continue;
16821            }
16822
16823            final String tagName = parser.getName();
16824            if (tagName.equals(TAG_GRANT)) {
16825                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16826                if (DEBUG_BACKUP) {
16827                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16828                }
16829            } else if (tagName.equals(TAG_PERMISSION)) {
16830
16831                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16832                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16833
16834                int newFlagSet = 0;
16835                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16836                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16837                }
16838                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16839                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16840                }
16841                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16842                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16843                }
16844                if (DEBUG_BACKUP) {
16845                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16846                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16847                }
16848                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16849                if (ps != null) {
16850                    // Already installed so we apply the grant immediately
16851                    if (DEBUG_BACKUP) {
16852                        Slog.v(TAG, "        + already installed; applying");
16853                    }
16854                    PermissionsState perms = ps.getPermissionsState();
16855                    BasePermission bp = mSettings.mPermissions.get(permName);
16856                    if (bp != null) {
16857                        if (isGranted) {
16858                            perms.grantRuntimePermission(bp, userId);
16859                        }
16860                        if (newFlagSet != 0) {
16861                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16862                        }
16863                    }
16864                } else {
16865                    // Need to wait for post-restore install to apply the grant
16866                    if (DEBUG_BACKUP) {
16867                        Slog.v(TAG, "        - not yet installed; saving for later");
16868                    }
16869                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16870                            isGranted, newFlagSet, userId);
16871                }
16872            } else {
16873                PackageManagerService.reportSettingsProblem(Log.WARN,
16874                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16875                XmlUtils.skipCurrentTag(parser);
16876            }
16877        }
16878
16879        scheduleWriteSettingsLocked();
16880        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16881    }
16882
16883    @Override
16884    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16885            int sourceUserId, int targetUserId, int flags) {
16886        mContext.enforceCallingOrSelfPermission(
16887                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16888        int callingUid = Binder.getCallingUid();
16889        enforceOwnerRights(ownerPackage, callingUid);
16890        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16891        if (intentFilter.countActions() == 0) {
16892            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16893            return;
16894        }
16895        synchronized (mPackages) {
16896            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16897                    ownerPackage, targetUserId, flags);
16898            CrossProfileIntentResolver resolver =
16899                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16900            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16901            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16902            if (existing != null) {
16903                int size = existing.size();
16904                for (int i = 0; i < size; i++) {
16905                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16906                        return;
16907                    }
16908                }
16909            }
16910            resolver.addFilter(newFilter);
16911            scheduleWritePackageRestrictionsLocked(sourceUserId);
16912        }
16913    }
16914
16915    @Override
16916    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16917        mContext.enforceCallingOrSelfPermission(
16918                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16919        int callingUid = Binder.getCallingUid();
16920        enforceOwnerRights(ownerPackage, callingUid);
16921        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16922        synchronized (mPackages) {
16923            CrossProfileIntentResolver resolver =
16924                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16925            ArraySet<CrossProfileIntentFilter> set =
16926                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16927            for (CrossProfileIntentFilter filter : set) {
16928                if (filter.getOwnerPackage().equals(ownerPackage)) {
16929                    resolver.removeFilter(filter);
16930                }
16931            }
16932            scheduleWritePackageRestrictionsLocked(sourceUserId);
16933        }
16934    }
16935
16936    // Enforcing that callingUid is owning pkg on userId
16937    private void enforceOwnerRights(String pkg, int callingUid) {
16938        // The system owns everything.
16939        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16940            return;
16941        }
16942        int callingUserId = UserHandle.getUserId(callingUid);
16943        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16944        if (pi == null) {
16945            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16946                    + callingUserId);
16947        }
16948        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16949            throw new SecurityException("Calling uid " + callingUid
16950                    + " does not own package " + pkg);
16951        }
16952    }
16953
16954    @Override
16955    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16956        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16957    }
16958
16959    private Intent getHomeIntent() {
16960        Intent intent = new Intent(Intent.ACTION_MAIN);
16961        intent.addCategory(Intent.CATEGORY_HOME);
16962        return intent;
16963    }
16964
16965    private IntentFilter getHomeFilter() {
16966        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16967        filter.addCategory(Intent.CATEGORY_HOME);
16968        filter.addCategory(Intent.CATEGORY_DEFAULT);
16969        return filter;
16970    }
16971
16972    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16973            int userId) {
16974        Intent intent  = getHomeIntent();
16975        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16976                PackageManager.GET_META_DATA, userId);
16977        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16978                true, false, false, userId);
16979
16980        allHomeCandidates.clear();
16981        if (list != null) {
16982            for (ResolveInfo ri : list) {
16983                allHomeCandidates.add(ri);
16984            }
16985        }
16986        return (preferred == null || preferred.activityInfo == null)
16987                ? null
16988                : new ComponentName(preferred.activityInfo.packageName,
16989                        preferred.activityInfo.name);
16990    }
16991
16992    @Override
16993    public void setHomeActivity(ComponentName comp, int userId) {
16994        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16995        getHomeActivitiesAsUser(homeActivities, userId);
16996
16997        boolean found = false;
16998
16999        final int size = homeActivities.size();
17000        final ComponentName[] set = new ComponentName[size];
17001        for (int i = 0; i < size; i++) {
17002            final ResolveInfo candidate = homeActivities.get(i);
17003            final ActivityInfo info = candidate.activityInfo;
17004            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17005            set[i] = activityName;
17006            if (!found && activityName.equals(comp)) {
17007                found = true;
17008            }
17009        }
17010        if (!found) {
17011            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17012                    + userId);
17013        }
17014        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17015                set, comp, userId);
17016    }
17017
17018    private @Nullable String getSetupWizardPackageName() {
17019        final Intent intent = new Intent(Intent.ACTION_MAIN);
17020        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17021
17022        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17023                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17024                        | MATCH_DISABLED_COMPONENTS,
17025                UserHandle.myUserId());
17026        if (matches.size() == 1) {
17027            return matches.get(0).getComponentInfo().packageName;
17028        } else {
17029            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17030                    + ": matches=" + matches);
17031            return null;
17032        }
17033    }
17034
17035    @Override
17036    public void setApplicationEnabledSetting(String appPackageName,
17037            int newState, int flags, int userId, String callingPackage) {
17038        if (!sUserManager.exists(userId)) return;
17039        if (callingPackage == null) {
17040            callingPackage = Integer.toString(Binder.getCallingUid());
17041        }
17042        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17043    }
17044
17045    @Override
17046    public void setComponentEnabledSetting(ComponentName componentName,
17047            int newState, int flags, int userId) {
17048        if (!sUserManager.exists(userId)) return;
17049        setEnabledSetting(componentName.getPackageName(),
17050                componentName.getClassName(), newState, flags, userId, null);
17051    }
17052
17053    private void setEnabledSetting(final String packageName, String className, int newState,
17054            final int flags, int userId, String callingPackage) {
17055        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17056              || newState == COMPONENT_ENABLED_STATE_ENABLED
17057              || newState == COMPONENT_ENABLED_STATE_DISABLED
17058              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17059              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17060            throw new IllegalArgumentException("Invalid new component state: "
17061                    + newState);
17062        }
17063        PackageSetting pkgSetting;
17064        final int uid = Binder.getCallingUid();
17065        final int permission;
17066        if (uid == Process.SYSTEM_UID) {
17067            permission = PackageManager.PERMISSION_GRANTED;
17068        } else {
17069            permission = mContext.checkCallingOrSelfPermission(
17070                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17071        }
17072        enforceCrossUserPermission(uid, userId,
17073                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17074        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17075        boolean sendNow = false;
17076        boolean isApp = (className == null);
17077        String componentName = isApp ? packageName : className;
17078        int packageUid = -1;
17079        ArrayList<String> components;
17080
17081        // writer
17082        synchronized (mPackages) {
17083            pkgSetting = mSettings.mPackages.get(packageName);
17084            if (pkgSetting == null) {
17085                if (className == null) {
17086                    throw new IllegalArgumentException("Unknown package: " + packageName);
17087                }
17088                throw new IllegalArgumentException(
17089                        "Unknown component: " + packageName + "/" + className);
17090            }
17091            // Allow root and verify that userId is not being specified by a different user
17092            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17093                throw new SecurityException(
17094                        "Permission Denial: attempt to change component state from pid="
17095                        + Binder.getCallingPid()
17096                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17097            }
17098            if (className == null) {
17099                // We're dealing with an application/package level state change
17100                if (pkgSetting.getEnabled(userId) == newState) {
17101                    // Nothing to do
17102                    return;
17103                }
17104                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17105                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17106                    // Don't care about who enables an app.
17107                    callingPackage = null;
17108                }
17109                pkgSetting.setEnabled(newState, userId, callingPackage);
17110                // pkgSetting.pkg.mSetEnabled = newState;
17111            } else {
17112                // We're dealing with a component level state change
17113                // First, verify that this is a valid class name.
17114                PackageParser.Package pkg = pkgSetting.pkg;
17115                if (pkg == null || !pkg.hasComponentClassName(className)) {
17116                    if (pkg != null &&
17117                            pkg.applicationInfo.targetSdkVersion >=
17118                                    Build.VERSION_CODES.JELLY_BEAN) {
17119                        throw new IllegalArgumentException("Component class " + className
17120                                + " does not exist in " + packageName);
17121                    } else {
17122                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17123                                + className + " does not exist in " + packageName);
17124                    }
17125                }
17126                switch (newState) {
17127                case COMPONENT_ENABLED_STATE_ENABLED:
17128                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17129                        return;
17130                    }
17131                    break;
17132                case COMPONENT_ENABLED_STATE_DISABLED:
17133                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17134                        return;
17135                    }
17136                    break;
17137                case COMPONENT_ENABLED_STATE_DEFAULT:
17138                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17139                        return;
17140                    }
17141                    break;
17142                default:
17143                    Slog.e(TAG, "Invalid new component state: " + newState);
17144                    return;
17145                }
17146            }
17147            scheduleWritePackageRestrictionsLocked(userId);
17148            components = mPendingBroadcasts.get(userId, packageName);
17149            final boolean newPackage = components == null;
17150            if (newPackage) {
17151                components = new ArrayList<String>();
17152            }
17153            if (!components.contains(componentName)) {
17154                components.add(componentName);
17155            }
17156            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17157                sendNow = true;
17158                // Purge entry from pending broadcast list if another one exists already
17159                // since we are sending one right away.
17160                mPendingBroadcasts.remove(userId, packageName);
17161            } else {
17162                if (newPackage) {
17163                    mPendingBroadcasts.put(userId, packageName, components);
17164                }
17165                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17166                    // Schedule a message
17167                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17168                }
17169            }
17170        }
17171
17172        long callingId = Binder.clearCallingIdentity();
17173        try {
17174            if (sendNow) {
17175                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17176                sendPackageChangedBroadcast(packageName,
17177                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17178            }
17179        } finally {
17180            Binder.restoreCallingIdentity(callingId);
17181        }
17182    }
17183
17184    @Override
17185    public void flushPackageRestrictionsAsUser(int userId) {
17186        if (!sUserManager.exists(userId)) {
17187            return;
17188        }
17189        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17190                false /* checkShell */, "flushPackageRestrictions");
17191        synchronized (mPackages) {
17192            mSettings.writePackageRestrictionsLPr(userId);
17193            mDirtyUsers.remove(userId);
17194            if (mDirtyUsers.isEmpty()) {
17195                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17196            }
17197        }
17198    }
17199
17200    private void sendPackageChangedBroadcast(String packageName,
17201            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17202        if (DEBUG_INSTALL)
17203            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17204                    + componentNames);
17205        Bundle extras = new Bundle(4);
17206        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17207        String nameList[] = new String[componentNames.size()];
17208        componentNames.toArray(nameList);
17209        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17210        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17211        extras.putInt(Intent.EXTRA_UID, packageUid);
17212        // If this is not reporting a change of the overall package, then only send it
17213        // to registered receivers.  We don't want to launch a swath of apps for every
17214        // little component state change.
17215        final int flags = !componentNames.contains(packageName)
17216                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17217        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17218                new int[] {UserHandle.getUserId(packageUid)});
17219    }
17220
17221    @Override
17222    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17223        if (!sUserManager.exists(userId)) return;
17224        final int uid = Binder.getCallingUid();
17225        final int permission = mContext.checkCallingOrSelfPermission(
17226                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17227        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17228        enforceCrossUserPermission(uid, userId,
17229                true /* requireFullPermission */, true /* checkShell */, "stop package");
17230        // writer
17231        synchronized (mPackages) {
17232            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17233                    allowedByPermission, uid, userId)) {
17234                scheduleWritePackageRestrictionsLocked(userId);
17235            }
17236        }
17237    }
17238
17239    @Override
17240    public String getInstallerPackageName(String packageName) {
17241        // reader
17242        synchronized (mPackages) {
17243            return mSettings.getInstallerPackageNameLPr(packageName);
17244        }
17245    }
17246
17247    @Override
17248    public int getApplicationEnabledSetting(String packageName, int userId) {
17249        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17250        int uid = Binder.getCallingUid();
17251        enforceCrossUserPermission(uid, userId,
17252                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17253        // reader
17254        synchronized (mPackages) {
17255            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17256        }
17257    }
17258
17259    @Override
17260    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17261        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17262        int uid = Binder.getCallingUid();
17263        enforceCrossUserPermission(uid, userId,
17264                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17265        // reader
17266        synchronized (mPackages) {
17267            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17268        }
17269    }
17270
17271    @Override
17272    public void enterSafeMode() {
17273        enforceSystemOrRoot("Only the system can request entering safe mode");
17274
17275        if (!mSystemReady) {
17276            mSafeMode = true;
17277        }
17278    }
17279
17280    @Override
17281    public void systemReady() {
17282        mSystemReady = true;
17283
17284        // Read the compatibilty setting when the system is ready.
17285        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17286                mContext.getContentResolver(),
17287                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17288        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17289        if (DEBUG_SETTINGS) {
17290            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17291        }
17292
17293        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17294
17295        synchronized (mPackages) {
17296            // Verify that all of the preferred activity components actually
17297            // exist.  It is possible for applications to be updated and at
17298            // that point remove a previously declared activity component that
17299            // had been set as a preferred activity.  We try to clean this up
17300            // the next time we encounter that preferred activity, but it is
17301            // possible for the user flow to never be able to return to that
17302            // situation so here we do a sanity check to make sure we haven't
17303            // left any junk around.
17304            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17305            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17306                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17307                removed.clear();
17308                for (PreferredActivity pa : pir.filterSet()) {
17309                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17310                        removed.add(pa);
17311                    }
17312                }
17313                if (removed.size() > 0) {
17314                    for (int r=0; r<removed.size(); r++) {
17315                        PreferredActivity pa = removed.get(r);
17316                        Slog.w(TAG, "Removing dangling preferred activity: "
17317                                + pa.mPref.mComponent);
17318                        pir.removeFilter(pa);
17319                    }
17320                    mSettings.writePackageRestrictionsLPr(
17321                            mSettings.mPreferredActivities.keyAt(i));
17322                }
17323            }
17324
17325            for (int userId : UserManagerService.getInstance().getUserIds()) {
17326                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17327                    grantPermissionsUserIds = ArrayUtils.appendInt(
17328                            grantPermissionsUserIds, userId);
17329                }
17330            }
17331        }
17332        sUserManager.systemReady();
17333
17334        // If we upgraded grant all default permissions before kicking off.
17335        for (int userId : grantPermissionsUserIds) {
17336            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17337        }
17338
17339        // Kick off any messages waiting for system ready
17340        if (mPostSystemReadyMessages != null) {
17341            for (Message msg : mPostSystemReadyMessages) {
17342                msg.sendToTarget();
17343            }
17344            mPostSystemReadyMessages = null;
17345        }
17346
17347        // Watch for external volumes that come and go over time
17348        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17349        storage.registerListener(mStorageListener);
17350
17351        mInstallerService.systemReady();
17352        mPackageDexOptimizer.systemReady();
17353
17354        MountServiceInternal mountServiceInternal = LocalServices.getService(
17355                MountServiceInternal.class);
17356        mountServiceInternal.addExternalStoragePolicy(
17357                new MountServiceInternal.ExternalStorageMountPolicy() {
17358            @Override
17359            public int getMountMode(int uid, String packageName) {
17360                if (Process.isIsolated(uid)) {
17361                    return Zygote.MOUNT_EXTERNAL_NONE;
17362                }
17363                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17364                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17365                }
17366                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17367                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17368                }
17369                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17370                    return Zygote.MOUNT_EXTERNAL_READ;
17371                }
17372                return Zygote.MOUNT_EXTERNAL_WRITE;
17373            }
17374
17375            @Override
17376            public boolean hasExternalStorage(int uid, String packageName) {
17377                return true;
17378            }
17379        });
17380    }
17381
17382    @Override
17383    public boolean isSafeMode() {
17384        return mSafeMode;
17385    }
17386
17387    @Override
17388    public boolean hasSystemUidErrors() {
17389        return mHasSystemUidErrors;
17390    }
17391
17392    static String arrayToString(int[] array) {
17393        StringBuffer buf = new StringBuffer(128);
17394        buf.append('[');
17395        if (array != null) {
17396            for (int i=0; i<array.length; i++) {
17397                if (i > 0) buf.append(", ");
17398                buf.append(array[i]);
17399            }
17400        }
17401        buf.append(']');
17402        return buf.toString();
17403    }
17404
17405    static class DumpState {
17406        public static final int DUMP_LIBS = 1 << 0;
17407        public static final int DUMP_FEATURES = 1 << 1;
17408        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17409        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17410        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17411        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17412        public static final int DUMP_PERMISSIONS = 1 << 6;
17413        public static final int DUMP_PACKAGES = 1 << 7;
17414        public static final int DUMP_SHARED_USERS = 1 << 8;
17415        public static final int DUMP_MESSAGES = 1 << 9;
17416        public static final int DUMP_PROVIDERS = 1 << 10;
17417        public static final int DUMP_VERIFIERS = 1 << 11;
17418        public static final int DUMP_PREFERRED = 1 << 12;
17419        public static final int DUMP_PREFERRED_XML = 1 << 13;
17420        public static final int DUMP_KEYSETS = 1 << 14;
17421        public static final int DUMP_VERSION = 1 << 15;
17422        public static final int DUMP_INSTALLS = 1 << 16;
17423        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17424        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17425        public static final int DUMP_FROZEN = 1 << 19;
17426
17427        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17428
17429        private int mTypes;
17430
17431        private int mOptions;
17432
17433        private boolean mTitlePrinted;
17434
17435        private SharedUserSetting mSharedUser;
17436
17437        public boolean isDumping(int type) {
17438            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17439                return true;
17440            }
17441
17442            return (mTypes & type) != 0;
17443        }
17444
17445        public void setDump(int type) {
17446            mTypes |= type;
17447        }
17448
17449        public boolean isOptionEnabled(int option) {
17450            return (mOptions & option) != 0;
17451        }
17452
17453        public void setOptionEnabled(int option) {
17454            mOptions |= option;
17455        }
17456
17457        public boolean onTitlePrinted() {
17458            final boolean printed = mTitlePrinted;
17459            mTitlePrinted = true;
17460            return printed;
17461        }
17462
17463        public boolean getTitlePrinted() {
17464            return mTitlePrinted;
17465        }
17466
17467        public void setTitlePrinted(boolean enabled) {
17468            mTitlePrinted = enabled;
17469        }
17470
17471        public SharedUserSetting getSharedUser() {
17472            return mSharedUser;
17473        }
17474
17475        public void setSharedUser(SharedUserSetting user) {
17476            mSharedUser = user;
17477        }
17478    }
17479
17480    @Override
17481    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17482            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17483        (new PackageManagerShellCommand(this)).exec(
17484                this, in, out, err, args, resultReceiver);
17485    }
17486
17487    @Override
17488    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17489        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17490                != PackageManager.PERMISSION_GRANTED) {
17491            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17492                    + Binder.getCallingPid()
17493                    + ", uid=" + Binder.getCallingUid()
17494                    + " without permission "
17495                    + android.Manifest.permission.DUMP);
17496            return;
17497        }
17498
17499        DumpState dumpState = new DumpState();
17500        boolean fullPreferred = false;
17501        boolean checkin = false;
17502
17503        String packageName = null;
17504        ArraySet<String> permissionNames = null;
17505
17506        int opti = 0;
17507        while (opti < args.length) {
17508            String opt = args[opti];
17509            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17510                break;
17511            }
17512            opti++;
17513
17514            if ("-a".equals(opt)) {
17515                // Right now we only know how to print all.
17516            } else if ("-h".equals(opt)) {
17517                pw.println("Package manager dump options:");
17518                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17519                pw.println("    --checkin: dump for a checkin");
17520                pw.println("    -f: print details of intent filters");
17521                pw.println("    -h: print this help");
17522                pw.println("  cmd may be one of:");
17523                pw.println("    l[ibraries]: list known shared libraries");
17524                pw.println("    f[eatures]: list device features");
17525                pw.println("    k[eysets]: print known keysets");
17526                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17527                pw.println("    perm[issions]: dump permissions");
17528                pw.println("    permission [name ...]: dump declaration and use of given permission");
17529                pw.println("    pref[erred]: print preferred package settings");
17530                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17531                pw.println("    prov[iders]: dump content providers");
17532                pw.println("    p[ackages]: dump installed packages");
17533                pw.println("    s[hared-users]: dump shared user IDs");
17534                pw.println("    m[essages]: print collected runtime messages");
17535                pw.println("    v[erifiers]: print package verifier info");
17536                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17537                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17538                pw.println("    version: print database version info");
17539                pw.println("    write: write current settings now");
17540                pw.println("    installs: details about install sessions");
17541                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17542                pw.println("    <package.name>: info about given package");
17543                return;
17544            } else if ("--checkin".equals(opt)) {
17545                checkin = true;
17546            } else if ("-f".equals(opt)) {
17547                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17548            } else {
17549                pw.println("Unknown argument: " + opt + "; use -h for help");
17550            }
17551        }
17552
17553        // Is the caller requesting to dump a particular piece of data?
17554        if (opti < args.length) {
17555            String cmd = args[opti];
17556            opti++;
17557            // Is this a package name?
17558            if ("android".equals(cmd) || cmd.contains(".")) {
17559                packageName = cmd;
17560                // When dumping a single package, we always dump all of its
17561                // filter information since the amount of data will be reasonable.
17562                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17563            } else if ("check-permission".equals(cmd)) {
17564                if (opti >= args.length) {
17565                    pw.println("Error: check-permission missing permission argument");
17566                    return;
17567                }
17568                String perm = args[opti];
17569                opti++;
17570                if (opti >= args.length) {
17571                    pw.println("Error: check-permission missing package argument");
17572                    return;
17573                }
17574                String pkg = args[opti];
17575                opti++;
17576                int user = UserHandle.getUserId(Binder.getCallingUid());
17577                if (opti < args.length) {
17578                    try {
17579                        user = Integer.parseInt(args[opti]);
17580                    } catch (NumberFormatException e) {
17581                        pw.println("Error: check-permission user argument is not a number: "
17582                                + args[opti]);
17583                        return;
17584                    }
17585                }
17586                pw.println(checkPermission(perm, pkg, user));
17587                return;
17588            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17589                dumpState.setDump(DumpState.DUMP_LIBS);
17590            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17591                dumpState.setDump(DumpState.DUMP_FEATURES);
17592            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17593                if (opti >= args.length) {
17594                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17595                            | DumpState.DUMP_SERVICE_RESOLVERS
17596                            | DumpState.DUMP_RECEIVER_RESOLVERS
17597                            | DumpState.DUMP_CONTENT_RESOLVERS);
17598                } else {
17599                    while (opti < args.length) {
17600                        String name = args[opti];
17601                        if ("a".equals(name) || "activity".equals(name)) {
17602                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17603                        } else if ("s".equals(name) || "service".equals(name)) {
17604                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17605                        } else if ("r".equals(name) || "receiver".equals(name)) {
17606                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17607                        } else if ("c".equals(name) || "content".equals(name)) {
17608                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17609                        } else {
17610                            pw.println("Error: unknown resolver table type: " + name);
17611                            return;
17612                        }
17613                        opti++;
17614                    }
17615                }
17616            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17617                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17618            } else if ("permission".equals(cmd)) {
17619                if (opti >= args.length) {
17620                    pw.println("Error: permission requires permission name");
17621                    return;
17622                }
17623                permissionNames = new ArraySet<>();
17624                while (opti < args.length) {
17625                    permissionNames.add(args[opti]);
17626                    opti++;
17627                }
17628                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17629                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17630            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17631                dumpState.setDump(DumpState.DUMP_PREFERRED);
17632            } else if ("preferred-xml".equals(cmd)) {
17633                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17634                if (opti < args.length && "--full".equals(args[opti])) {
17635                    fullPreferred = true;
17636                    opti++;
17637                }
17638            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17639                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17640            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17641                dumpState.setDump(DumpState.DUMP_PACKAGES);
17642            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17643                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17644            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17645                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17646            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17647                dumpState.setDump(DumpState.DUMP_MESSAGES);
17648            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17649                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17650            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17651                    || "intent-filter-verifiers".equals(cmd)) {
17652                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17653            } else if ("version".equals(cmd)) {
17654                dumpState.setDump(DumpState.DUMP_VERSION);
17655            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17656                dumpState.setDump(DumpState.DUMP_KEYSETS);
17657            } else if ("installs".equals(cmd)) {
17658                dumpState.setDump(DumpState.DUMP_INSTALLS);
17659            } else if ("frozen".equals(cmd)) {
17660                dumpState.setDump(DumpState.DUMP_FROZEN);
17661            } else if ("write".equals(cmd)) {
17662                synchronized (mPackages) {
17663                    mSettings.writeLPr();
17664                    pw.println("Settings written.");
17665                    return;
17666                }
17667            }
17668        }
17669
17670        if (checkin) {
17671            pw.println("vers,1");
17672        }
17673
17674        // reader
17675        synchronized (mPackages) {
17676            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17677                if (!checkin) {
17678                    if (dumpState.onTitlePrinted())
17679                        pw.println();
17680                    pw.println("Database versions:");
17681                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17682                }
17683            }
17684
17685            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17686                if (!checkin) {
17687                    if (dumpState.onTitlePrinted())
17688                        pw.println();
17689                    pw.println("Verifiers:");
17690                    pw.print("  Required: ");
17691                    pw.print(mRequiredVerifierPackage);
17692                    pw.print(" (uid=");
17693                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17694                            UserHandle.USER_SYSTEM));
17695                    pw.println(")");
17696                } else if (mRequiredVerifierPackage != null) {
17697                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17698                    pw.print(",");
17699                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17700                            UserHandle.USER_SYSTEM));
17701                }
17702            }
17703
17704            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17705                    packageName == null) {
17706                if (mIntentFilterVerifierComponent != null) {
17707                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17708                    if (!checkin) {
17709                        if (dumpState.onTitlePrinted())
17710                            pw.println();
17711                        pw.println("Intent Filter Verifier:");
17712                        pw.print("  Using: ");
17713                        pw.print(verifierPackageName);
17714                        pw.print(" (uid=");
17715                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17716                                UserHandle.USER_SYSTEM));
17717                        pw.println(")");
17718                    } else if (verifierPackageName != null) {
17719                        pw.print("ifv,"); pw.print(verifierPackageName);
17720                        pw.print(",");
17721                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17722                                UserHandle.USER_SYSTEM));
17723                    }
17724                } else {
17725                    pw.println();
17726                    pw.println("No Intent Filter Verifier available!");
17727                }
17728            }
17729
17730            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17731                boolean printedHeader = false;
17732                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17733                while (it.hasNext()) {
17734                    String name = it.next();
17735                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17736                    if (!checkin) {
17737                        if (!printedHeader) {
17738                            if (dumpState.onTitlePrinted())
17739                                pw.println();
17740                            pw.println("Libraries:");
17741                            printedHeader = true;
17742                        }
17743                        pw.print("  ");
17744                    } else {
17745                        pw.print("lib,");
17746                    }
17747                    pw.print(name);
17748                    if (!checkin) {
17749                        pw.print(" -> ");
17750                    }
17751                    if (ent.path != null) {
17752                        if (!checkin) {
17753                            pw.print("(jar) ");
17754                            pw.print(ent.path);
17755                        } else {
17756                            pw.print(",jar,");
17757                            pw.print(ent.path);
17758                        }
17759                    } else {
17760                        if (!checkin) {
17761                            pw.print("(apk) ");
17762                            pw.print(ent.apk);
17763                        } else {
17764                            pw.print(",apk,");
17765                            pw.print(ent.apk);
17766                        }
17767                    }
17768                    pw.println();
17769                }
17770            }
17771
17772            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17773                if (dumpState.onTitlePrinted())
17774                    pw.println();
17775                if (!checkin) {
17776                    pw.println("Features:");
17777                }
17778
17779                for (FeatureInfo feat : mAvailableFeatures.values()) {
17780                    if (checkin) {
17781                        pw.print("feat,");
17782                        pw.print(feat.name);
17783                        pw.print(",");
17784                        pw.println(feat.version);
17785                    } else {
17786                        pw.print("  ");
17787                        pw.print(feat.name);
17788                        if (feat.version > 0) {
17789                            pw.print(" version=");
17790                            pw.print(feat.version);
17791                        }
17792                        pw.println();
17793                    }
17794                }
17795            }
17796
17797            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17798                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17799                        : "Activity Resolver Table:", "  ", packageName,
17800                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17801                    dumpState.setTitlePrinted(true);
17802                }
17803            }
17804            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17805                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17806                        : "Receiver Resolver Table:", "  ", packageName,
17807                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17808                    dumpState.setTitlePrinted(true);
17809                }
17810            }
17811            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17812                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17813                        : "Service Resolver Table:", "  ", packageName,
17814                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17815                    dumpState.setTitlePrinted(true);
17816                }
17817            }
17818            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17819                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17820                        : "Provider Resolver Table:", "  ", packageName,
17821                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17822                    dumpState.setTitlePrinted(true);
17823                }
17824            }
17825
17826            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17827                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17828                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17829                    int user = mSettings.mPreferredActivities.keyAt(i);
17830                    if (pir.dump(pw,
17831                            dumpState.getTitlePrinted()
17832                                ? "\nPreferred Activities User " + user + ":"
17833                                : "Preferred Activities User " + user + ":", "  ",
17834                            packageName, true, false)) {
17835                        dumpState.setTitlePrinted(true);
17836                    }
17837                }
17838            }
17839
17840            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17841                pw.flush();
17842                FileOutputStream fout = new FileOutputStream(fd);
17843                BufferedOutputStream str = new BufferedOutputStream(fout);
17844                XmlSerializer serializer = new FastXmlSerializer();
17845                try {
17846                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17847                    serializer.startDocument(null, true);
17848                    serializer.setFeature(
17849                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17850                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17851                    serializer.endDocument();
17852                    serializer.flush();
17853                } catch (IllegalArgumentException e) {
17854                    pw.println("Failed writing: " + e);
17855                } catch (IllegalStateException e) {
17856                    pw.println("Failed writing: " + e);
17857                } catch (IOException e) {
17858                    pw.println("Failed writing: " + e);
17859                }
17860            }
17861
17862            if (!checkin
17863                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17864                    && packageName == null) {
17865                pw.println();
17866                int count = mSettings.mPackages.size();
17867                if (count == 0) {
17868                    pw.println("No applications!");
17869                    pw.println();
17870                } else {
17871                    final String prefix = "  ";
17872                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17873                    if (allPackageSettings.size() == 0) {
17874                        pw.println("No domain preferred apps!");
17875                        pw.println();
17876                    } else {
17877                        pw.println("App verification status:");
17878                        pw.println();
17879                        count = 0;
17880                        for (PackageSetting ps : allPackageSettings) {
17881                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17882                            if (ivi == null || ivi.getPackageName() == null) continue;
17883                            pw.println(prefix + "Package: " + ivi.getPackageName());
17884                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17885                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17886                            pw.println();
17887                            count++;
17888                        }
17889                        if (count == 0) {
17890                            pw.println(prefix + "No app verification established.");
17891                            pw.println();
17892                        }
17893                        for (int userId : sUserManager.getUserIds()) {
17894                            pw.println("App linkages for user " + userId + ":");
17895                            pw.println();
17896                            count = 0;
17897                            for (PackageSetting ps : allPackageSettings) {
17898                                final long status = ps.getDomainVerificationStatusForUser(userId);
17899                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17900                                    continue;
17901                                }
17902                                pw.println(prefix + "Package: " + ps.name);
17903                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17904                                String statusStr = IntentFilterVerificationInfo.
17905                                        getStatusStringFromValue(status);
17906                                pw.println(prefix + "Status:  " + statusStr);
17907                                pw.println();
17908                                count++;
17909                            }
17910                            if (count == 0) {
17911                                pw.println(prefix + "No configured app linkages.");
17912                                pw.println();
17913                            }
17914                        }
17915                    }
17916                }
17917            }
17918
17919            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17920                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17921                if (packageName == null && permissionNames == null) {
17922                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17923                        if (iperm == 0) {
17924                            if (dumpState.onTitlePrinted())
17925                                pw.println();
17926                            pw.println("AppOp Permissions:");
17927                        }
17928                        pw.print("  AppOp Permission ");
17929                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17930                        pw.println(":");
17931                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17932                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17933                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17934                        }
17935                    }
17936                }
17937            }
17938
17939            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17940                boolean printedSomething = false;
17941                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17942                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17943                        continue;
17944                    }
17945                    if (!printedSomething) {
17946                        if (dumpState.onTitlePrinted())
17947                            pw.println();
17948                        pw.println("Registered ContentProviders:");
17949                        printedSomething = true;
17950                    }
17951                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17952                    pw.print("    "); pw.println(p.toString());
17953                }
17954                printedSomething = false;
17955                for (Map.Entry<String, PackageParser.Provider> entry :
17956                        mProvidersByAuthority.entrySet()) {
17957                    PackageParser.Provider p = entry.getValue();
17958                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17959                        continue;
17960                    }
17961                    if (!printedSomething) {
17962                        if (dumpState.onTitlePrinted())
17963                            pw.println();
17964                        pw.println("ContentProvider Authorities:");
17965                        printedSomething = true;
17966                    }
17967                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17968                    pw.print("    "); pw.println(p.toString());
17969                    if (p.info != null && p.info.applicationInfo != null) {
17970                        final String appInfo = p.info.applicationInfo.toString();
17971                        pw.print("      applicationInfo="); pw.println(appInfo);
17972                    }
17973                }
17974            }
17975
17976            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17977                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17978            }
17979
17980            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17981                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17982            }
17983
17984            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17985                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17986            }
17987
17988            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17989                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17990            }
17991
17992            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17993                // XXX should handle packageName != null by dumping only install data that
17994                // the given package is involved with.
17995                if (dumpState.onTitlePrinted()) pw.println();
17996                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17997            }
17998
17999            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18000                // XXX should handle packageName != null by dumping only install data that
18001                // the given package is involved with.
18002                if (dumpState.onTitlePrinted()) pw.println();
18003
18004                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18005                ipw.println();
18006                ipw.println("Frozen packages:");
18007                ipw.increaseIndent();
18008                if (mFrozenPackages.size() == 0) {
18009                    ipw.println("(none)");
18010                } else {
18011                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18012                        ipw.println(mFrozenPackages.valueAt(i));
18013                    }
18014                }
18015                ipw.decreaseIndent();
18016            }
18017
18018            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18019                if (dumpState.onTitlePrinted()) pw.println();
18020                mSettings.dumpReadMessagesLPr(pw, dumpState);
18021
18022                pw.println();
18023                pw.println("Package warning messages:");
18024                BufferedReader in = null;
18025                String line = null;
18026                try {
18027                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18028                    while ((line = in.readLine()) != null) {
18029                        if (line.contains("ignored: updated version")) continue;
18030                        pw.println(line);
18031                    }
18032                } catch (IOException ignored) {
18033                } finally {
18034                    IoUtils.closeQuietly(in);
18035                }
18036            }
18037
18038            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18039                BufferedReader in = null;
18040                String line = null;
18041                try {
18042                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18043                    while ((line = in.readLine()) != null) {
18044                        if (line.contains("ignored: updated version")) continue;
18045                        pw.print("msg,");
18046                        pw.println(line);
18047                    }
18048                } catch (IOException ignored) {
18049                } finally {
18050                    IoUtils.closeQuietly(in);
18051                }
18052            }
18053        }
18054    }
18055
18056    private String dumpDomainString(String packageName) {
18057        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18058                .getList();
18059        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18060
18061        ArraySet<String> result = new ArraySet<>();
18062        if (iviList.size() > 0) {
18063            for (IntentFilterVerificationInfo ivi : iviList) {
18064                for (String host : ivi.getDomains()) {
18065                    result.add(host);
18066                }
18067            }
18068        }
18069        if (filters != null && filters.size() > 0) {
18070            for (IntentFilter filter : filters) {
18071                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18072                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18073                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18074                    result.addAll(filter.getHostsList());
18075                }
18076            }
18077        }
18078
18079        StringBuilder sb = new StringBuilder(result.size() * 16);
18080        for (String domain : result) {
18081            if (sb.length() > 0) sb.append(" ");
18082            sb.append(domain);
18083        }
18084        return sb.toString();
18085    }
18086
18087    // ------- apps on sdcard specific code -------
18088    static final boolean DEBUG_SD_INSTALL = false;
18089
18090    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18091
18092    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18093
18094    private boolean mMediaMounted = false;
18095
18096    static String getEncryptKey() {
18097        try {
18098            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18099                    SD_ENCRYPTION_KEYSTORE_NAME);
18100            if (sdEncKey == null) {
18101                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18102                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18103                if (sdEncKey == null) {
18104                    Slog.e(TAG, "Failed to create encryption keys");
18105                    return null;
18106                }
18107            }
18108            return sdEncKey;
18109        } catch (NoSuchAlgorithmException nsae) {
18110            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18111            return null;
18112        } catch (IOException ioe) {
18113            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18114            return null;
18115        }
18116    }
18117
18118    /*
18119     * Update media status on PackageManager.
18120     */
18121    @Override
18122    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18123        int callingUid = Binder.getCallingUid();
18124        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18125            throw new SecurityException("Media status can only be updated by the system");
18126        }
18127        // reader; this apparently protects mMediaMounted, but should probably
18128        // be a different lock in that case.
18129        synchronized (mPackages) {
18130            Log.i(TAG, "Updating external media status from "
18131                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18132                    + (mediaStatus ? "mounted" : "unmounted"));
18133            if (DEBUG_SD_INSTALL)
18134                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18135                        + ", mMediaMounted=" + mMediaMounted);
18136            if (mediaStatus == mMediaMounted) {
18137                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18138                        : 0, -1);
18139                mHandler.sendMessage(msg);
18140                return;
18141            }
18142            mMediaMounted = mediaStatus;
18143        }
18144        // Queue up an async operation since the package installation may take a
18145        // little while.
18146        mHandler.post(new Runnable() {
18147            public void run() {
18148                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18149            }
18150        });
18151    }
18152
18153    /**
18154     * Called by MountService when the initial ASECs to scan are available.
18155     * Should block until all the ASEC containers are finished being scanned.
18156     */
18157    public void scanAvailableAsecs() {
18158        updateExternalMediaStatusInner(true, false, false);
18159    }
18160
18161    /*
18162     * Collect information of applications on external media, map them against
18163     * existing containers and update information based on current mount status.
18164     * Please note that we always have to report status if reportStatus has been
18165     * set to true especially when unloading packages.
18166     */
18167    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18168            boolean externalStorage) {
18169        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18170        int[] uidArr = EmptyArray.INT;
18171
18172        final String[] list = PackageHelper.getSecureContainerList();
18173        if (ArrayUtils.isEmpty(list)) {
18174            Log.i(TAG, "No secure containers found");
18175        } else {
18176            // Process list of secure containers and categorize them
18177            // as active or stale based on their package internal state.
18178
18179            // reader
18180            synchronized (mPackages) {
18181                for (String cid : list) {
18182                    // Leave stages untouched for now; installer service owns them
18183                    if (PackageInstallerService.isStageName(cid)) continue;
18184
18185                    if (DEBUG_SD_INSTALL)
18186                        Log.i(TAG, "Processing container " + cid);
18187                    String pkgName = getAsecPackageName(cid);
18188                    if (pkgName == null) {
18189                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18190                        continue;
18191                    }
18192                    if (DEBUG_SD_INSTALL)
18193                        Log.i(TAG, "Looking for pkg : " + pkgName);
18194
18195                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18196                    if (ps == null) {
18197                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18198                        continue;
18199                    }
18200
18201                    /*
18202                     * Skip packages that are not external if we're unmounting
18203                     * external storage.
18204                     */
18205                    if (externalStorage && !isMounted && !isExternal(ps)) {
18206                        continue;
18207                    }
18208
18209                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18210                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18211                    // The package status is changed only if the code path
18212                    // matches between settings and the container id.
18213                    if (ps.codePathString != null
18214                            && ps.codePathString.startsWith(args.getCodePath())) {
18215                        if (DEBUG_SD_INSTALL) {
18216                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18217                                    + " at code path: " + ps.codePathString);
18218                        }
18219
18220                        // We do have a valid package installed on sdcard
18221                        processCids.put(args, ps.codePathString);
18222                        final int uid = ps.appId;
18223                        if (uid != -1) {
18224                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18225                        }
18226                    } else {
18227                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18228                                + ps.codePathString);
18229                    }
18230                }
18231            }
18232
18233            Arrays.sort(uidArr);
18234        }
18235
18236        // Process packages with valid entries.
18237        if (isMounted) {
18238            if (DEBUG_SD_INSTALL)
18239                Log.i(TAG, "Loading packages");
18240            loadMediaPackages(processCids, uidArr, externalStorage);
18241            startCleaningPackages();
18242            mInstallerService.onSecureContainersAvailable();
18243        } else {
18244            if (DEBUG_SD_INSTALL)
18245                Log.i(TAG, "Unloading packages");
18246            unloadMediaPackages(processCids, uidArr, reportStatus);
18247        }
18248    }
18249
18250    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18251            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18252        final int size = infos.size();
18253        final String[] packageNames = new String[size];
18254        final int[] packageUids = new int[size];
18255        for (int i = 0; i < size; i++) {
18256            final ApplicationInfo info = infos.get(i);
18257            packageNames[i] = info.packageName;
18258            packageUids[i] = info.uid;
18259        }
18260        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18261                finishedReceiver);
18262    }
18263
18264    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18265            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18266        sendResourcesChangedBroadcast(mediaStatus, replacing,
18267                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18268    }
18269
18270    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18271            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18272        int size = pkgList.length;
18273        if (size > 0) {
18274            // Send broadcasts here
18275            Bundle extras = new Bundle();
18276            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18277            if (uidArr != null) {
18278                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18279            }
18280            if (replacing) {
18281                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18282            }
18283            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18284                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18285            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18286        }
18287    }
18288
18289   /*
18290     * Look at potentially valid container ids from processCids If package
18291     * information doesn't match the one on record or package scanning fails,
18292     * the cid is added to list of removeCids. We currently don't delete stale
18293     * containers.
18294     */
18295    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18296            boolean externalStorage) {
18297        ArrayList<String> pkgList = new ArrayList<String>();
18298        Set<AsecInstallArgs> keys = processCids.keySet();
18299
18300        for (AsecInstallArgs args : keys) {
18301            String codePath = processCids.get(args);
18302            if (DEBUG_SD_INSTALL)
18303                Log.i(TAG, "Loading container : " + args.cid);
18304            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18305            try {
18306                // Make sure there are no container errors first.
18307                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18308                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18309                            + " when installing from sdcard");
18310                    continue;
18311                }
18312                // Check code path here.
18313                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18314                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18315                            + " does not match one in settings " + codePath);
18316                    continue;
18317                }
18318                // Parse package
18319                int parseFlags = mDefParseFlags;
18320                if (args.isExternalAsec()) {
18321                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18322                }
18323                if (args.isFwdLocked()) {
18324                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18325                }
18326
18327                synchronized (mInstallLock) {
18328                    PackageParser.Package pkg = null;
18329                    try {
18330                        // Sadly we don't know the package name yet to freeze it
18331                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18332                                SCAN_IGNORE_FROZEN, 0, null);
18333                    } catch (PackageManagerException e) {
18334                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18335                    }
18336                    // Scan the package
18337                    if (pkg != null) {
18338                        /*
18339                         * TODO why is the lock being held? doPostInstall is
18340                         * called in other places without the lock. This needs
18341                         * to be straightened out.
18342                         */
18343                        // writer
18344                        synchronized (mPackages) {
18345                            retCode = PackageManager.INSTALL_SUCCEEDED;
18346                            pkgList.add(pkg.packageName);
18347                            // Post process args
18348                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18349                                    pkg.applicationInfo.uid);
18350                        }
18351                    } else {
18352                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18353                    }
18354                }
18355
18356            } finally {
18357                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18358                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18359                }
18360            }
18361        }
18362        // writer
18363        synchronized (mPackages) {
18364            // If the platform SDK has changed since the last time we booted,
18365            // we need to re-grant app permission to catch any new ones that
18366            // appear. This is really a hack, and means that apps can in some
18367            // cases get permissions that the user didn't initially explicitly
18368            // allow... it would be nice to have some better way to handle
18369            // this situation.
18370            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18371                    : mSettings.getInternalVersion();
18372            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18373                    : StorageManager.UUID_PRIVATE_INTERNAL;
18374
18375            int updateFlags = UPDATE_PERMISSIONS_ALL;
18376            if (ver.sdkVersion != mSdkVersion) {
18377                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18378                        + mSdkVersion + "; regranting permissions for external");
18379                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18380            }
18381            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18382
18383            // Yay, everything is now upgraded
18384            ver.forceCurrent();
18385
18386            // can downgrade to reader
18387            // Persist settings
18388            mSettings.writeLPr();
18389        }
18390        // Send a broadcast to let everyone know we are done processing
18391        if (pkgList.size() > 0) {
18392            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18393        }
18394    }
18395
18396   /*
18397     * Utility method to unload a list of specified containers
18398     */
18399    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18400        // Just unmount all valid containers.
18401        for (AsecInstallArgs arg : cidArgs) {
18402            synchronized (mInstallLock) {
18403                arg.doPostDeleteLI(false);
18404           }
18405       }
18406   }
18407
18408    /*
18409     * Unload packages mounted on external media. This involves deleting package
18410     * data from internal structures, sending broadcasts about disabled packages,
18411     * gc'ing to free up references, unmounting all secure containers
18412     * corresponding to packages on external media, and posting a
18413     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18414     * that we always have to post this message if status has been requested no
18415     * matter what.
18416     */
18417    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18418            final boolean reportStatus) {
18419        if (DEBUG_SD_INSTALL)
18420            Log.i(TAG, "unloading media packages");
18421        ArrayList<String> pkgList = new ArrayList<String>();
18422        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18423        final Set<AsecInstallArgs> keys = processCids.keySet();
18424        for (AsecInstallArgs args : keys) {
18425            String pkgName = args.getPackageName();
18426            if (DEBUG_SD_INSTALL)
18427                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18428            // Delete package internally
18429            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18430            synchronized (mInstallLock) {
18431                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18432                final boolean res;
18433                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18434                        "unloadMediaPackages")) {
18435                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18436                            null);
18437                }
18438                if (res) {
18439                    pkgList.add(pkgName);
18440                } else {
18441                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18442                    failedList.add(args);
18443                }
18444            }
18445        }
18446
18447        // reader
18448        synchronized (mPackages) {
18449            // We didn't update the settings after removing each package;
18450            // write them now for all packages.
18451            mSettings.writeLPr();
18452        }
18453
18454        // We have to absolutely send UPDATED_MEDIA_STATUS only
18455        // after confirming that all the receivers processed the ordered
18456        // broadcast when packages get disabled, force a gc to clean things up.
18457        // and unload all the containers.
18458        if (pkgList.size() > 0) {
18459            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18460                    new IIntentReceiver.Stub() {
18461                public void performReceive(Intent intent, int resultCode, String data,
18462                        Bundle extras, boolean ordered, boolean sticky,
18463                        int sendingUser) throws RemoteException {
18464                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18465                            reportStatus ? 1 : 0, 1, keys);
18466                    mHandler.sendMessage(msg);
18467                }
18468            });
18469        } else {
18470            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18471                    keys);
18472            mHandler.sendMessage(msg);
18473        }
18474    }
18475
18476    private void loadPrivatePackages(final VolumeInfo vol) {
18477        mHandler.post(new Runnable() {
18478            @Override
18479            public void run() {
18480                loadPrivatePackagesInner(vol);
18481            }
18482        });
18483    }
18484
18485    private void loadPrivatePackagesInner(VolumeInfo vol) {
18486        final String volumeUuid = vol.fsUuid;
18487        if (TextUtils.isEmpty(volumeUuid)) {
18488            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18489            return;
18490        }
18491
18492        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18493        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18494        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18495
18496        final VersionInfo ver;
18497        final List<PackageSetting> packages;
18498        synchronized (mPackages) {
18499            ver = mSettings.findOrCreateVersion(volumeUuid);
18500            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18501        }
18502
18503        for (PackageSetting ps : packages) {
18504            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18505            synchronized (mInstallLock) {
18506                final PackageParser.Package pkg;
18507                try {
18508                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18509                    loaded.add(pkg.applicationInfo);
18510
18511                } catch (PackageManagerException e) {
18512                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18513                }
18514
18515                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18516                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18517                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18518                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18519                }
18520            }
18521        }
18522
18523        // Reconcile app data for all started/unlocked users
18524        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18525        final UserManager um = mContext.getSystemService(UserManager.class);
18526        for (UserInfo user : um.getUsers()) {
18527            final int flags;
18528            if (um.isUserUnlocked(user.id)) {
18529                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18530            } else if (um.isUserRunning(user.id)) {
18531                flags = StorageManager.FLAG_STORAGE_DE;
18532            } else {
18533                continue;
18534            }
18535
18536            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18537            synchronized (mInstallLock) {
18538                reconcileAppsDataLI(volumeUuid, user.id, flags);
18539            }
18540        }
18541
18542        synchronized (mPackages) {
18543            int updateFlags = UPDATE_PERMISSIONS_ALL;
18544            if (ver.sdkVersion != mSdkVersion) {
18545                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18546                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18547                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18548            }
18549            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18550
18551            // Yay, everything is now upgraded
18552            ver.forceCurrent();
18553
18554            mSettings.writeLPr();
18555        }
18556
18557        for (PackageFreezer freezer : freezers) {
18558            freezer.close();
18559        }
18560
18561        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18562        sendResourcesChangedBroadcast(true, false, loaded, null);
18563    }
18564
18565    private void unloadPrivatePackages(final VolumeInfo vol) {
18566        mHandler.post(new Runnable() {
18567            @Override
18568            public void run() {
18569                unloadPrivatePackagesInner(vol);
18570            }
18571        });
18572    }
18573
18574    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18575        final String volumeUuid = vol.fsUuid;
18576        if (TextUtils.isEmpty(volumeUuid)) {
18577            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18578            return;
18579        }
18580
18581        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18582        synchronized (mInstallLock) {
18583        synchronized (mPackages) {
18584            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18585            for (PackageSetting ps : packages) {
18586                if (ps.pkg == null) continue;
18587
18588                final ApplicationInfo info = ps.pkg.applicationInfo;
18589                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18590                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18591
18592                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18593                        "unloadPrivatePackagesInner")) {
18594                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18595                            false, null)) {
18596                        unloaded.add(info);
18597                    } else {
18598                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18599                    }
18600                }
18601            }
18602
18603            mSettings.writeLPr();
18604        }
18605        }
18606
18607        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18608        sendResourcesChangedBroadcast(false, false, unloaded, null);
18609    }
18610
18611    /**
18612     * Examine all users present on given mounted volume, and destroy data
18613     * belonging to users that are no longer valid, or whose user ID has been
18614     * recycled.
18615     */
18616    private void reconcileUsers(String volumeUuid) {
18617        // TODO: also reconcile DE directories
18618        final File[] files = FileUtils
18619                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18620        for (File file : files) {
18621            if (!file.isDirectory()) continue;
18622
18623            final int userId;
18624            final UserInfo info;
18625            try {
18626                userId = Integer.parseInt(file.getName());
18627                info = sUserManager.getUserInfo(userId);
18628            } catch (NumberFormatException e) {
18629                Slog.w(TAG, "Invalid user directory " + file);
18630                continue;
18631            }
18632
18633            boolean destroyUser = false;
18634            if (info == null) {
18635                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18636                        + " because no matching user was found");
18637                destroyUser = true;
18638            } else {
18639                try {
18640                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18641                } catch (IOException e) {
18642                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18643                            + " because we failed to enforce serial number: " + e);
18644                    destroyUser = true;
18645                }
18646            }
18647
18648            if (destroyUser) {
18649                synchronized (mInstallLock) {
18650                    try {
18651                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18652                    } catch (InstallerException e) {
18653                        Slog.w(TAG, "Failed to clean up user dirs", e);
18654                    }
18655                }
18656            }
18657        }
18658    }
18659
18660    private void assertPackageKnown(String volumeUuid, String packageName)
18661            throws PackageManagerException {
18662        synchronized (mPackages) {
18663            final PackageSetting ps = mSettings.mPackages.get(packageName);
18664            if (ps == null) {
18665                throw new PackageManagerException("Package " + packageName + " is unknown");
18666            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18667                throw new PackageManagerException(
18668                        "Package " + packageName + " found on unknown volume " + volumeUuid
18669                                + "; expected volume " + ps.volumeUuid);
18670            }
18671        }
18672    }
18673
18674    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18675            throws PackageManagerException {
18676        synchronized (mPackages) {
18677            final PackageSetting ps = mSettings.mPackages.get(packageName);
18678            if (ps == null) {
18679                throw new PackageManagerException("Package " + packageName + " is unknown");
18680            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18681                throw new PackageManagerException(
18682                        "Package " + packageName + " found on unknown volume " + volumeUuid
18683                                + "; expected volume " + ps.volumeUuid);
18684            } else if (!ps.getInstalled(userId)) {
18685                throw new PackageManagerException(
18686                        "Package " + packageName + " not installed for user " + userId);
18687            }
18688        }
18689    }
18690
18691    /**
18692     * Examine all apps present on given mounted volume, and destroy apps that
18693     * aren't expected, either due to uninstallation or reinstallation on
18694     * another volume.
18695     */
18696    private void reconcileApps(String volumeUuid) {
18697        final File[] files = FileUtils
18698                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18699        for (File file : files) {
18700            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18701                    && !PackageInstallerService.isStageName(file.getName());
18702            if (!isPackage) {
18703                // Ignore entries which are not packages
18704                continue;
18705            }
18706
18707            try {
18708                final PackageLite pkg = PackageParser.parsePackageLite(file,
18709                        PackageParser.PARSE_MUST_BE_APK);
18710                assertPackageKnown(volumeUuid, pkg.packageName);
18711
18712            } catch (PackageParserException | PackageManagerException e) {
18713                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18714                synchronized (mInstallLock) {
18715                    removeCodePathLI(file);
18716                }
18717            }
18718        }
18719    }
18720
18721    /**
18722     * Reconcile all app data for the given user.
18723     * <p>
18724     * Verifies that directories exist and that ownership and labeling is
18725     * correct for all installed apps on all mounted volumes.
18726     */
18727    void reconcileAppsData(int userId, int flags) {
18728        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18729        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18730            final String volumeUuid = vol.getFsUuid();
18731            synchronized (mInstallLock) {
18732                reconcileAppsDataLI(volumeUuid, userId, flags);
18733            }
18734        }
18735    }
18736
18737    /**
18738     * Reconcile all app data on given mounted volume.
18739     * <p>
18740     * Destroys app data that isn't expected, either due to uninstallation or
18741     * reinstallation on another volume.
18742     * <p>
18743     * Verifies that directories exist and that ownership and labeling is
18744     * correct for all installed apps.
18745     */
18746    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
18747        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18748                + Integer.toHexString(flags));
18749
18750        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18751        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18752
18753        boolean restoreconNeeded = false;
18754
18755        // First look for stale data that doesn't belong, and check if things
18756        // have changed since we did our last restorecon
18757        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18758            if (!isUserKeyUnlocked(userId)) {
18759                throw new RuntimeException(
18760                        "Yikes, someone asked us to reconcile CE storage while " + userId
18761                                + " was still locked; this would have caused massive data loss!");
18762            }
18763
18764            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18765
18766            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18767            for (File file : files) {
18768                final String packageName = file.getName();
18769                try {
18770                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18771                } catch (PackageManagerException e) {
18772                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18773                    try {
18774                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
18775                                StorageManager.FLAG_STORAGE_CE, 0);
18776                    } catch (InstallerException e2) {
18777                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
18778                    }
18779                }
18780            }
18781        }
18782        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18783            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18784
18785            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18786            for (File file : files) {
18787                final String packageName = file.getName();
18788                try {
18789                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18790                } catch (PackageManagerException e) {
18791                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18792                    try {
18793                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
18794                                StorageManager.FLAG_STORAGE_DE, 0);
18795                    } catch (InstallerException e2) {
18796                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
18797                    }
18798                }
18799            }
18800        }
18801
18802        // Ensure that data directories are ready to roll for all packages
18803        // installed for this volume and user
18804        final List<PackageSetting> packages;
18805        synchronized (mPackages) {
18806            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18807        }
18808        int preparedCount = 0;
18809        for (PackageSetting ps : packages) {
18810            final String packageName = ps.name;
18811            if (ps.pkg == null) {
18812                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18813                // TODO: might be due to legacy ASEC apps; we should circle back
18814                // and reconcile again once they're scanned
18815                continue;
18816            }
18817
18818            if (ps.getInstalled(userId)) {
18819                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
18820
18821                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
18822                    // We may have just shuffled around app data directories, so
18823                    // prepare them one more time
18824                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
18825                }
18826
18827                preparedCount++;
18828            }
18829        }
18830
18831        if (restoreconNeeded) {
18832            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18833                SELinuxMMAC.setRestoreconDone(ceDir);
18834            }
18835            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18836                SELinuxMMAC.setRestoreconDone(deDir);
18837            }
18838        }
18839
18840        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18841                + " packages; restoreconNeeded was " + restoreconNeeded);
18842    }
18843
18844    /**
18845     * Prepare app data for the given app just after it was installed or
18846     * upgraded. This method carefully only touches users that it's installed
18847     * for, and it forces a restorecon to handle any seinfo changes.
18848     * <p>
18849     * Verifies that directories exist and that ownership and labeling is
18850     * correct for all installed apps. If there is an ownership mismatch, it
18851     * will try recovering system apps by wiping data; third-party app data is
18852     * left intact.
18853     * <p>
18854     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18855     */
18856    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
18857        final PackageSetting ps;
18858        synchronized (mPackages) {
18859            ps = mSettings.mPackages.get(pkg.packageName);
18860            mSettings.writeKernelMappingLPr(ps);
18861        }
18862
18863        final UserManager um = mContext.getSystemService(UserManager.class);
18864        for (UserInfo user : um.getUsers()) {
18865            final int flags;
18866            if (um.isUserUnlocked(user.id)) {
18867                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18868            } else if (um.isUserRunning(user.id)) {
18869                flags = StorageManager.FLAG_STORAGE_DE;
18870            } else {
18871                continue;
18872            }
18873
18874            if (ps.getInstalled(user.id)) {
18875                // Whenever an app changes, force a restorecon of its data
18876                // TODO: when user data is locked, mark that we're still dirty
18877                prepareAppDataLIF(pkg, user.id, flags, true);
18878            }
18879        }
18880    }
18881
18882    /**
18883     * Prepare app data for the given app.
18884     * <p>
18885     * Verifies that directories exist and that ownership and labeling is
18886     * correct for all installed apps. If there is an ownership mismatch, this
18887     * will try recovering system apps by wiping data; third-party app data is
18888     * left intact.
18889     */
18890    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
18891            boolean restoreconNeeded) {
18892        if (pkg == null) {
18893            Slog.wtf(TAG, "Package was null!", new Throwable());
18894            return;
18895        }
18896        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
18897        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18898        for (int i = 0; i < childCount; i++) {
18899            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
18900        }
18901    }
18902
18903    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
18904            boolean restoreconNeeded) {
18905        if (DEBUG_APP_DATA) {
18906            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18907                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18908        }
18909
18910        final String volumeUuid = pkg.volumeUuid;
18911        final String packageName = pkg.packageName;
18912        final ApplicationInfo app = pkg.applicationInfo;
18913        final int appId = UserHandle.getAppId(app.uid);
18914
18915        Preconditions.checkNotNull(app.seinfo);
18916
18917        try {
18918            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18919                    appId, app.seinfo, app.targetSdkVersion);
18920        } catch (InstallerException e) {
18921            if (app.isSystemApp()) {
18922                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18923                        + ", but trying to recover: " + e);
18924                destroyAppDataLeafLIF(pkg, userId, flags);
18925                try {
18926                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18927                            appId, app.seinfo, app.targetSdkVersion);
18928                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18929                } catch (InstallerException e2) {
18930                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
18931                }
18932            } else {
18933                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18934            }
18935        }
18936
18937        if (restoreconNeeded) {
18938            try {
18939                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
18940                        app.seinfo);
18941            } catch (InstallerException e) {
18942                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
18943            }
18944        }
18945
18946        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18947            try {
18948                // CE storage is unlocked right now, so read out the inode and
18949                // remember for use later when it's locked
18950                // TODO: mark this structure as dirty so we persist it!
18951                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
18952                        StorageManager.FLAG_STORAGE_CE);
18953                synchronized (mPackages) {
18954                    final PackageSetting ps = mSettings.mPackages.get(packageName);
18955                    if (ps != null) {
18956                        ps.setCeDataInode(ceDataInode, userId);
18957                    }
18958                }
18959            } catch (InstallerException e) {
18960                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
18961            }
18962        }
18963
18964        prepareAppDataContentsLeafLIF(pkg, userId, flags);
18965    }
18966
18967    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
18968        if (pkg == null) {
18969            Slog.wtf(TAG, "Package was null!", new Throwable());
18970            return;
18971        }
18972        prepareAppDataContentsLeafLIF(pkg, userId, flags);
18973        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18974        for (int i = 0; i < childCount; i++) {
18975            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
18976        }
18977    }
18978
18979    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
18980        final String volumeUuid = pkg.volumeUuid;
18981        final String packageName = pkg.packageName;
18982        final ApplicationInfo app = pkg.applicationInfo;
18983
18984        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18985            // Create a native library symlink only if we have native libraries
18986            // and if the native libraries are 32 bit libraries. We do not provide
18987            // this symlink for 64 bit libraries.
18988            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18989                final String nativeLibPath = app.nativeLibraryDir;
18990                try {
18991                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18992                            nativeLibPath, userId);
18993                } catch (InstallerException e) {
18994                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18995                }
18996            }
18997        }
18998    }
18999
19000    /**
19001     * For system apps on non-FBE devices, this method migrates any existing
19002     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19003     * requested by the app.
19004     */
19005    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19006        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19007                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19008            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19009                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19010            try {
19011                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19012                        storageTarget);
19013            } catch (InstallerException e) {
19014                logCriticalInfo(Log.WARN,
19015                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19016            }
19017            return true;
19018        } else {
19019            return false;
19020        }
19021    }
19022
19023    public PackageFreezer freezePackage(String packageName, String killReason) {
19024        return new PackageFreezer(packageName, killReason);
19025    }
19026
19027    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19028            String killReason) {
19029        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19030            return new PackageFreezer();
19031        } else {
19032            return freezePackage(packageName, killReason);
19033        }
19034    }
19035
19036    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19037            String killReason) {
19038        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19039            return new PackageFreezer();
19040        } else {
19041            return freezePackage(packageName, killReason);
19042        }
19043    }
19044
19045    /**
19046     * Class that freezes and kills the given package upon creation, and
19047     * unfreezes it upon closing. This is typically used when doing surgery on
19048     * app code/data to prevent the app from running while you're working.
19049     */
19050    private class PackageFreezer implements AutoCloseable {
19051        private final String mPackageName;
19052        private final PackageFreezer[] mChildren;
19053
19054        private final boolean mWeFroze;
19055
19056        private final AtomicBoolean mClosed = new AtomicBoolean();
19057        private final CloseGuard mCloseGuard = CloseGuard.get();
19058
19059        /**
19060         * Create and return a stub freezer that doesn't actually do anything,
19061         * typically used when someone requested
19062         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19063         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19064         */
19065        public PackageFreezer() {
19066            mPackageName = null;
19067            mChildren = null;
19068            mWeFroze = false;
19069            mCloseGuard.open("close");
19070        }
19071
19072        public PackageFreezer(String packageName, String killReason) {
19073            synchronized (mPackages) {
19074                mPackageName = packageName;
19075                mWeFroze = mFrozenPackages.add(mPackageName);
19076
19077                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19078                if (ps != null) {
19079                    killApplication(ps.name, ps.appId, killReason);
19080                }
19081
19082                final PackageParser.Package p = mPackages.get(packageName);
19083                if (p != null && p.childPackages != null) {
19084                    final int N = p.childPackages.size();
19085                    mChildren = new PackageFreezer[N];
19086                    for (int i = 0; i < N; i++) {
19087                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19088                                killReason);
19089                    }
19090                } else {
19091                    mChildren = null;
19092                }
19093            }
19094            mCloseGuard.open("close");
19095        }
19096
19097        @Override
19098        protected void finalize() throws Throwable {
19099            try {
19100                mCloseGuard.warnIfOpen();
19101                close();
19102            } finally {
19103                super.finalize();
19104            }
19105        }
19106
19107        @Override
19108        public void close() {
19109            mCloseGuard.close();
19110            if (mClosed.compareAndSet(false, true)) {
19111                synchronized (mPackages) {
19112                    if (mWeFroze) {
19113                        mFrozenPackages.remove(mPackageName);
19114                    }
19115
19116                    if (mChildren != null) {
19117                        for (PackageFreezer freezer : mChildren) {
19118                            freezer.close();
19119                        }
19120                    }
19121                }
19122            }
19123        }
19124    }
19125
19126    /**
19127     * Verify that given package is currently frozen.
19128     */
19129    private void checkPackageFrozen(String packageName) {
19130        synchronized (mPackages) {
19131            if (!mFrozenPackages.contains(packageName)) {
19132                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19133            }
19134        }
19135    }
19136
19137    @Override
19138    public int movePackage(final String packageName, final String volumeUuid) {
19139        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19140
19141        final int moveId = mNextMoveId.getAndIncrement();
19142        mHandler.post(new Runnable() {
19143            @Override
19144            public void run() {
19145                try {
19146                    movePackageInternal(packageName, volumeUuid, moveId);
19147                } catch (PackageManagerException e) {
19148                    Slog.w(TAG, "Failed to move " + packageName, e);
19149                    mMoveCallbacks.notifyStatusChanged(moveId,
19150                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19151                }
19152            }
19153        });
19154        return moveId;
19155    }
19156
19157    private void movePackageInternal(final String packageName, final String volumeUuid,
19158            final int moveId) throws PackageManagerException {
19159        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19160        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19161        final PackageManager pm = mContext.getPackageManager();
19162
19163        final boolean currentAsec;
19164        final String currentVolumeUuid;
19165        final File codeFile;
19166        final String installerPackageName;
19167        final String packageAbiOverride;
19168        final int appId;
19169        final String seinfo;
19170        final String label;
19171        final int targetSdkVersion;
19172        final PackageFreezer freezer;
19173
19174        // reader
19175        synchronized (mPackages) {
19176            final PackageParser.Package pkg = mPackages.get(packageName);
19177            final PackageSetting ps = mSettings.mPackages.get(packageName);
19178            if (pkg == null || ps == null) {
19179                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19180            }
19181
19182            if (pkg.applicationInfo.isSystemApp()) {
19183                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19184                        "Cannot move system application");
19185            }
19186
19187            if (pkg.applicationInfo.isExternalAsec()) {
19188                currentAsec = true;
19189                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19190            } else if (pkg.applicationInfo.isForwardLocked()) {
19191                currentAsec = true;
19192                currentVolumeUuid = "forward_locked";
19193            } else {
19194                currentAsec = false;
19195                currentVolumeUuid = ps.volumeUuid;
19196
19197                final File probe = new File(pkg.codePath);
19198                final File probeOat = new File(probe, "oat");
19199                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19200                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19201                            "Move only supported for modern cluster style installs");
19202                }
19203            }
19204
19205            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19206                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19207                        "Package already moved to " + volumeUuid);
19208            }
19209            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19210                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19211                        "Device admin cannot be moved");
19212            }
19213
19214            if (mFrozenPackages.contains(packageName)) {
19215                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19216                        "Failed to move already frozen package");
19217            }
19218
19219            codeFile = new File(pkg.codePath);
19220            installerPackageName = ps.installerPackageName;
19221            packageAbiOverride = ps.cpuAbiOverrideString;
19222            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19223            seinfo = pkg.applicationInfo.seinfo;
19224            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19225            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19226            freezer = new PackageFreezer(packageName, "movePackageInternal");
19227        }
19228
19229        final Bundle extras = new Bundle();
19230        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19231        extras.putString(Intent.EXTRA_TITLE, label);
19232        mMoveCallbacks.notifyCreated(moveId, extras);
19233
19234        int installFlags;
19235        final boolean moveCompleteApp;
19236        final File measurePath;
19237
19238        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19239            installFlags = INSTALL_INTERNAL;
19240            moveCompleteApp = !currentAsec;
19241            measurePath = Environment.getDataAppDirectory(volumeUuid);
19242        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19243            installFlags = INSTALL_EXTERNAL;
19244            moveCompleteApp = false;
19245            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19246        } else {
19247            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19248            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19249                    || !volume.isMountedWritable()) {
19250                freezer.close();
19251                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19252                        "Move location not mounted private volume");
19253            }
19254
19255            Preconditions.checkState(!currentAsec);
19256
19257            installFlags = INSTALL_INTERNAL;
19258            moveCompleteApp = true;
19259            measurePath = Environment.getDataAppDirectory(volumeUuid);
19260        }
19261
19262        final PackageStats stats = new PackageStats(null, -1);
19263        synchronized (mInstaller) {
19264            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19265                freezer.close();
19266                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19267                        "Failed to measure package size");
19268            }
19269        }
19270
19271        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19272                + stats.dataSize);
19273
19274        final long startFreeBytes = measurePath.getFreeSpace();
19275        final long sizeBytes;
19276        if (moveCompleteApp) {
19277            sizeBytes = stats.codeSize + stats.dataSize;
19278        } else {
19279            sizeBytes = stats.codeSize;
19280        }
19281
19282        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19283            freezer.close();
19284            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19285                    "Not enough free space to move");
19286        }
19287
19288        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19289
19290        final CountDownLatch installedLatch = new CountDownLatch(1);
19291        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19292            @Override
19293            public void onUserActionRequired(Intent intent) throws RemoteException {
19294                throw new IllegalStateException();
19295            }
19296
19297            @Override
19298            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19299                    Bundle extras) throws RemoteException {
19300                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19301                        + PackageManager.installStatusToString(returnCode, msg));
19302
19303                installedLatch.countDown();
19304                freezer.close();
19305
19306                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19307                switch (status) {
19308                    case PackageInstaller.STATUS_SUCCESS:
19309                        mMoveCallbacks.notifyStatusChanged(moveId,
19310                                PackageManager.MOVE_SUCCEEDED);
19311                        break;
19312                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19313                        mMoveCallbacks.notifyStatusChanged(moveId,
19314                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19315                        break;
19316                    default:
19317                        mMoveCallbacks.notifyStatusChanged(moveId,
19318                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19319                        break;
19320                }
19321            }
19322        };
19323
19324        final MoveInfo move;
19325        if (moveCompleteApp) {
19326            // Kick off a thread to report progress estimates
19327            new Thread() {
19328                @Override
19329                public void run() {
19330                    while (true) {
19331                        try {
19332                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19333                                break;
19334                            }
19335                        } catch (InterruptedException ignored) {
19336                        }
19337
19338                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19339                        final int progress = 10 + (int) MathUtils.constrain(
19340                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19341                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19342                    }
19343                }
19344            }.start();
19345
19346            final String dataAppName = codeFile.getName();
19347            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19348                    dataAppName, appId, seinfo, targetSdkVersion);
19349        } else {
19350            move = null;
19351        }
19352
19353        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19354
19355        final Message msg = mHandler.obtainMessage(INIT_COPY);
19356        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19357        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19358                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19359                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19360        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19361        msg.obj = params;
19362
19363        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19364                System.identityHashCode(msg.obj));
19365        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19366                System.identityHashCode(msg.obj));
19367
19368        mHandler.sendMessage(msg);
19369    }
19370
19371    @Override
19372    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19373        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19374
19375        final int realMoveId = mNextMoveId.getAndIncrement();
19376        final Bundle extras = new Bundle();
19377        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19378        mMoveCallbacks.notifyCreated(realMoveId, extras);
19379
19380        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19381            @Override
19382            public void onCreated(int moveId, Bundle extras) {
19383                // Ignored
19384            }
19385
19386            @Override
19387            public void onStatusChanged(int moveId, int status, long estMillis) {
19388                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19389            }
19390        };
19391
19392        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19393        storage.setPrimaryStorageUuid(volumeUuid, callback);
19394        return realMoveId;
19395    }
19396
19397    @Override
19398    public int getMoveStatus(int moveId) {
19399        mContext.enforceCallingOrSelfPermission(
19400                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19401        return mMoveCallbacks.mLastStatus.get(moveId);
19402    }
19403
19404    @Override
19405    public void registerMoveCallback(IPackageMoveObserver callback) {
19406        mContext.enforceCallingOrSelfPermission(
19407                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19408        mMoveCallbacks.register(callback);
19409    }
19410
19411    @Override
19412    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19413        mContext.enforceCallingOrSelfPermission(
19414                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19415        mMoveCallbacks.unregister(callback);
19416    }
19417
19418    @Override
19419    public boolean setInstallLocation(int loc) {
19420        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19421                null);
19422        if (getInstallLocation() == loc) {
19423            return true;
19424        }
19425        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19426                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19427            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19428                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19429            return true;
19430        }
19431        return false;
19432   }
19433
19434    @Override
19435    public int getInstallLocation() {
19436        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19437                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19438                PackageHelper.APP_INSTALL_AUTO);
19439    }
19440
19441    /** Called by UserManagerService */
19442    void cleanUpUser(UserManagerService userManager, int userHandle) {
19443        synchronized (mPackages) {
19444            mDirtyUsers.remove(userHandle);
19445            mUserNeedsBadging.delete(userHandle);
19446            mSettings.removeUserLPw(userHandle);
19447            mPendingBroadcasts.remove(userHandle);
19448            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19449        }
19450        synchronized (mInstallLock) {
19451            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19452            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19453                final String volumeUuid = vol.getFsUuid();
19454                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
19455                try {
19456                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
19457                } catch (InstallerException e) {
19458                    Slog.w(TAG, "Failed to remove user data", e);
19459                }
19460            }
19461            synchronized (mPackages) {
19462                removeUnusedPackagesLILPw(userManager, userHandle);
19463            }
19464        }
19465    }
19466
19467    /**
19468     * We're removing userHandle and would like to remove any downloaded packages
19469     * that are no longer in use by any other user.
19470     * @param userHandle the user being removed
19471     */
19472    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
19473        final boolean DEBUG_CLEAN_APKS = false;
19474        int [] users = userManager.getUserIds();
19475        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19476        while (psit.hasNext()) {
19477            PackageSetting ps = psit.next();
19478            if (ps.pkg == null) {
19479                continue;
19480            }
19481            final String packageName = ps.pkg.packageName;
19482            // Skip over if system app
19483            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19484                continue;
19485            }
19486            if (DEBUG_CLEAN_APKS) {
19487                Slog.i(TAG, "Checking package " + packageName);
19488            }
19489            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19490            if (keep) {
19491                if (DEBUG_CLEAN_APKS) {
19492                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19493                }
19494            } else {
19495                for (int i = 0; i < users.length; i++) {
19496                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19497                        keep = true;
19498                        if (DEBUG_CLEAN_APKS) {
19499                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19500                                    + users[i]);
19501                        }
19502                        break;
19503                    }
19504                }
19505            }
19506            if (!keep) {
19507                if (DEBUG_CLEAN_APKS) {
19508                    Slog.i(TAG, "  Removing package " + packageName);
19509                }
19510                mHandler.post(new Runnable() {
19511                    public void run() {
19512                        deletePackageX(packageName, userHandle, 0);
19513                    } //end run
19514                });
19515            }
19516        }
19517    }
19518
19519    /** Called by UserManagerService */
19520    void createNewUser(int userHandle) {
19521        synchronized (mInstallLock) {
19522            try {
19523                mInstaller.createUserConfig(userHandle);
19524            } catch (InstallerException e) {
19525                Slog.w(TAG, "Failed to create user config", e);
19526            }
19527            mSettings.createNewUserLI(this, mInstaller, userHandle);
19528        }
19529        synchronized (mPackages) {
19530            applyFactoryDefaultBrowserLPw(userHandle);
19531            primeDomainVerificationsLPw(userHandle);
19532        }
19533    }
19534
19535    void newUserCreated(final int userHandle) {
19536        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19537        // If permission review for legacy apps is required, we represent
19538        // dagerous permissions for such apps as always granted runtime
19539        // permissions to keep per user flag state whether review is needed.
19540        // Hence, if a new user is added we have to propagate dangerous
19541        // permission grants for these legacy apps.
19542        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19543            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19544                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19545        }
19546    }
19547
19548    @Override
19549    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19550        mContext.enforceCallingOrSelfPermission(
19551                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19552                "Only package verification agents can read the verifier device identity");
19553
19554        synchronized (mPackages) {
19555            return mSettings.getVerifierDeviceIdentityLPw();
19556        }
19557    }
19558
19559    @Override
19560    public void setPermissionEnforced(String permission, boolean enforced) {
19561        // TODO: Now that we no longer change GID for storage, this should to away.
19562        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19563                "setPermissionEnforced");
19564        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19565            synchronized (mPackages) {
19566                if (mSettings.mReadExternalStorageEnforced == null
19567                        || mSettings.mReadExternalStorageEnforced != enforced) {
19568                    mSettings.mReadExternalStorageEnforced = enforced;
19569                    mSettings.writeLPr();
19570                }
19571            }
19572            // kill any non-foreground processes so we restart them and
19573            // grant/revoke the GID.
19574            final IActivityManager am = ActivityManagerNative.getDefault();
19575            if (am != null) {
19576                final long token = Binder.clearCallingIdentity();
19577                try {
19578                    am.killProcessesBelowForeground("setPermissionEnforcement");
19579                } catch (RemoteException e) {
19580                } finally {
19581                    Binder.restoreCallingIdentity(token);
19582                }
19583            }
19584        } else {
19585            throw new IllegalArgumentException("No selective enforcement for " + permission);
19586        }
19587    }
19588
19589    @Override
19590    @Deprecated
19591    public boolean isPermissionEnforced(String permission) {
19592        return true;
19593    }
19594
19595    @Override
19596    public boolean isStorageLow() {
19597        final long token = Binder.clearCallingIdentity();
19598        try {
19599            final DeviceStorageMonitorInternal
19600                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19601            if (dsm != null) {
19602                return dsm.isMemoryLow();
19603            } else {
19604                return false;
19605            }
19606        } finally {
19607            Binder.restoreCallingIdentity(token);
19608        }
19609    }
19610
19611    @Override
19612    public IPackageInstaller getPackageInstaller() {
19613        return mInstallerService;
19614    }
19615
19616    private boolean userNeedsBadging(int userId) {
19617        int index = mUserNeedsBadging.indexOfKey(userId);
19618        if (index < 0) {
19619            final UserInfo userInfo;
19620            final long token = Binder.clearCallingIdentity();
19621            try {
19622                userInfo = sUserManager.getUserInfo(userId);
19623            } finally {
19624                Binder.restoreCallingIdentity(token);
19625            }
19626            final boolean b;
19627            if (userInfo != null && userInfo.isManagedProfile()) {
19628                b = true;
19629            } else {
19630                b = false;
19631            }
19632            mUserNeedsBadging.put(userId, b);
19633            return b;
19634        }
19635        return mUserNeedsBadging.valueAt(index);
19636    }
19637
19638    @Override
19639    public KeySet getKeySetByAlias(String packageName, String alias) {
19640        if (packageName == null || alias == null) {
19641            return null;
19642        }
19643        synchronized(mPackages) {
19644            final PackageParser.Package pkg = mPackages.get(packageName);
19645            if (pkg == null) {
19646                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19647                throw new IllegalArgumentException("Unknown package: " + packageName);
19648            }
19649            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19650            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19651        }
19652    }
19653
19654    @Override
19655    public KeySet getSigningKeySet(String packageName) {
19656        if (packageName == null) {
19657            return null;
19658        }
19659        synchronized(mPackages) {
19660            final PackageParser.Package pkg = mPackages.get(packageName);
19661            if (pkg == null) {
19662                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19663                throw new IllegalArgumentException("Unknown package: " + packageName);
19664            }
19665            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19666                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19667                throw new SecurityException("May not access signing KeySet of other apps.");
19668            }
19669            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19670            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19671        }
19672    }
19673
19674    @Override
19675    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19676        if (packageName == null || ks == null) {
19677            return false;
19678        }
19679        synchronized(mPackages) {
19680            final PackageParser.Package pkg = mPackages.get(packageName);
19681            if (pkg == null) {
19682                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19683                throw new IllegalArgumentException("Unknown package: " + packageName);
19684            }
19685            IBinder ksh = ks.getToken();
19686            if (ksh instanceof KeySetHandle) {
19687                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19688                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19689            }
19690            return false;
19691        }
19692    }
19693
19694    @Override
19695    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19696        if (packageName == null || ks == null) {
19697            return false;
19698        }
19699        synchronized(mPackages) {
19700            final PackageParser.Package pkg = mPackages.get(packageName);
19701            if (pkg == null) {
19702                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19703                throw new IllegalArgumentException("Unknown package: " + packageName);
19704            }
19705            IBinder ksh = ks.getToken();
19706            if (ksh instanceof KeySetHandle) {
19707                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19708                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19709            }
19710            return false;
19711        }
19712    }
19713
19714    private void deletePackageIfUnusedLPr(final String packageName) {
19715        PackageSetting ps = mSettings.mPackages.get(packageName);
19716        if (ps == null) {
19717            return;
19718        }
19719        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19720            // TODO Implement atomic delete if package is unused
19721            // It is currently possible that the package will be deleted even if it is installed
19722            // after this method returns.
19723            mHandler.post(new Runnable() {
19724                public void run() {
19725                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19726                }
19727            });
19728        }
19729    }
19730
19731    /**
19732     * Check and throw if the given before/after packages would be considered a
19733     * downgrade.
19734     */
19735    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19736            throws PackageManagerException {
19737        if (after.versionCode < before.mVersionCode) {
19738            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19739                    "Update version code " + after.versionCode + " is older than current "
19740                    + before.mVersionCode);
19741        } else if (after.versionCode == before.mVersionCode) {
19742            if (after.baseRevisionCode < before.baseRevisionCode) {
19743                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19744                        "Update base revision code " + after.baseRevisionCode
19745                        + " is older than current " + before.baseRevisionCode);
19746            }
19747
19748            if (!ArrayUtils.isEmpty(after.splitNames)) {
19749                for (int i = 0; i < after.splitNames.length; i++) {
19750                    final String splitName = after.splitNames[i];
19751                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19752                    if (j != -1) {
19753                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19754                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19755                                    "Update split " + splitName + " revision code "
19756                                    + after.splitRevisionCodes[i] + " is older than current "
19757                                    + before.splitRevisionCodes[j]);
19758                        }
19759                    }
19760                }
19761            }
19762        }
19763    }
19764
19765    private static class MoveCallbacks extends Handler {
19766        private static final int MSG_CREATED = 1;
19767        private static final int MSG_STATUS_CHANGED = 2;
19768
19769        private final RemoteCallbackList<IPackageMoveObserver>
19770                mCallbacks = new RemoteCallbackList<>();
19771
19772        private final SparseIntArray mLastStatus = new SparseIntArray();
19773
19774        public MoveCallbacks(Looper looper) {
19775            super(looper);
19776        }
19777
19778        public void register(IPackageMoveObserver callback) {
19779            mCallbacks.register(callback);
19780        }
19781
19782        public void unregister(IPackageMoveObserver callback) {
19783            mCallbacks.unregister(callback);
19784        }
19785
19786        @Override
19787        public void handleMessage(Message msg) {
19788            final SomeArgs args = (SomeArgs) msg.obj;
19789            final int n = mCallbacks.beginBroadcast();
19790            for (int i = 0; i < n; i++) {
19791                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19792                try {
19793                    invokeCallback(callback, msg.what, args);
19794                } catch (RemoteException ignored) {
19795                }
19796            }
19797            mCallbacks.finishBroadcast();
19798            args.recycle();
19799        }
19800
19801        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19802                throws RemoteException {
19803            switch (what) {
19804                case MSG_CREATED: {
19805                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19806                    break;
19807                }
19808                case MSG_STATUS_CHANGED: {
19809                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19810                    break;
19811                }
19812            }
19813        }
19814
19815        private void notifyCreated(int moveId, Bundle extras) {
19816            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19817
19818            final SomeArgs args = SomeArgs.obtain();
19819            args.argi1 = moveId;
19820            args.arg2 = extras;
19821            obtainMessage(MSG_CREATED, args).sendToTarget();
19822        }
19823
19824        private void notifyStatusChanged(int moveId, int status) {
19825            notifyStatusChanged(moveId, status, -1);
19826        }
19827
19828        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19829            Slog.v(TAG, "Move " + moveId + " status " + status);
19830
19831            final SomeArgs args = SomeArgs.obtain();
19832            args.argi1 = moveId;
19833            args.argi2 = status;
19834            args.arg3 = estMillis;
19835            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19836
19837            synchronized (mLastStatus) {
19838                mLastStatus.put(moveId, status);
19839            }
19840        }
19841    }
19842
19843    private final static class OnPermissionChangeListeners extends Handler {
19844        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19845
19846        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19847                new RemoteCallbackList<>();
19848
19849        public OnPermissionChangeListeners(Looper looper) {
19850            super(looper);
19851        }
19852
19853        @Override
19854        public void handleMessage(Message msg) {
19855            switch (msg.what) {
19856                case MSG_ON_PERMISSIONS_CHANGED: {
19857                    final int uid = msg.arg1;
19858                    handleOnPermissionsChanged(uid);
19859                } break;
19860            }
19861        }
19862
19863        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19864            mPermissionListeners.register(listener);
19865
19866        }
19867
19868        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19869            mPermissionListeners.unregister(listener);
19870        }
19871
19872        public void onPermissionsChanged(int uid) {
19873            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19874                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19875            }
19876        }
19877
19878        private void handleOnPermissionsChanged(int uid) {
19879            final int count = mPermissionListeners.beginBroadcast();
19880            try {
19881                for (int i = 0; i < count; i++) {
19882                    IOnPermissionsChangeListener callback = mPermissionListeners
19883                            .getBroadcastItem(i);
19884                    try {
19885                        callback.onPermissionsChanged(uid);
19886                    } catch (RemoteException e) {
19887                        Log.e(TAG, "Permission listener is dead", e);
19888                    }
19889                }
19890            } finally {
19891                mPermissionListeners.finishBroadcast();
19892            }
19893        }
19894    }
19895
19896    private class PackageManagerInternalImpl extends PackageManagerInternal {
19897        @Override
19898        public void setLocationPackagesProvider(PackagesProvider provider) {
19899            synchronized (mPackages) {
19900                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19901            }
19902        }
19903
19904        @Override
19905        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19906            synchronized (mPackages) {
19907                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19908            }
19909        }
19910
19911        @Override
19912        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19913            synchronized (mPackages) {
19914                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19915            }
19916        }
19917
19918        @Override
19919        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19920            synchronized (mPackages) {
19921                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19922            }
19923        }
19924
19925        @Override
19926        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19927            synchronized (mPackages) {
19928                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19929            }
19930        }
19931
19932        @Override
19933        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19934            synchronized (mPackages) {
19935                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19936            }
19937        }
19938
19939        @Override
19940        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19941            synchronized (mPackages) {
19942                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19943                        packageName, userId);
19944            }
19945        }
19946
19947        @Override
19948        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19949            synchronized (mPackages) {
19950                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19951                        packageName, userId);
19952            }
19953        }
19954
19955        @Override
19956        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19957            synchronized (mPackages) {
19958                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19959                        packageName, userId);
19960            }
19961        }
19962
19963        @Override
19964        public void setKeepUninstalledPackages(final List<String> packageList) {
19965            Preconditions.checkNotNull(packageList);
19966            List<String> removedFromList = null;
19967            synchronized (mPackages) {
19968                if (mKeepUninstalledPackages != null) {
19969                    final int packagesCount = mKeepUninstalledPackages.size();
19970                    for (int i = 0; i < packagesCount; i++) {
19971                        String oldPackage = mKeepUninstalledPackages.get(i);
19972                        if (packageList != null && packageList.contains(oldPackage)) {
19973                            continue;
19974                        }
19975                        if (removedFromList == null) {
19976                            removedFromList = new ArrayList<>();
19977                        }
19978                        removedFromList.add(oldPackage);
19979                    }
19980                }
19981                mKeepUninstalledPackages = new ArrayList<>(packageList);
19982                if (removedFromList != null) {
19983                    final int removedCount = removedFromList.size();
19984                    for (int i = 0; i < removedCount; i++) {
19985                        deletePackageIfUnusedLPr(removedFromList.get(i));
19986                    }
19987                }
19988            }
19989        }
19990
19991        @Override
19992        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19993            synchronized (mPackages) {
19994                // If we do not support permission review, done.
19995                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19996                    return false;
19997                }
19998
19999                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20000                if (packageSetting == null) {
20001                    return false;
20002                }
20003
20004                // Permission review applies only to apps not supporting the new permission model.
20005                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20006                    return false;
20007                }
20008
20009                // Legacy apps have the permission and get user consent on launch.
20010                PermissionsState permissionsState = packageSetting.getPermissionsState();
20011                return permissionsState.isPermissionReviewRequired(userId);
20012            }
20013        }
20014
20015        @Override
20016        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20017            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20018        }
20019
20020        @Override
20021        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20022                int userId) {
20023            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20024        }
20025    }
20026
20027    @Override
20028    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20029        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20030        synchronized (mPackages) {
20031            final long identity = Binder.clearCallingIdentity();
20032            try {
20033                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20034                        packageNames, userId);
20035            } finally {
20036                Binder.restoreCallingIdentity(identity);
20037            }
20038        }
20039    }
20040
20041    private static void enforceSystemOrPhoneCaller(String tag) {
20042        int callingUid = Binder.getCallingUid();
20043        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20044            throw new SecurityException(
20045                    "Cannot call " + tag + " from UID " + callingUid);
20046        }
20047    }
20048
20049    boolean isHistoricalPackageUsageAvailable() {
20050        return mPackageUsage.isHistoricalPackageUsageAvailable();
20051    }
20052
20053    /**
20054     * Return a <b>copy</b> of the collection of packages known to the package manager.
20055     * @return A copy of the values of mPackages.
20056     */
20057    Collection<PackageParser.Package> getPackages() {
20058        synchronized (mPackages) {
20059            return new ArrayList<>(mPackages.values());
20060        }
20061    }
20062
20063    /**
20064     * Logs process start information (including base APK hash) to the security log.
20065     * @hide
20066     */
20067    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20068            String apkFile, int pid) {
20069        if (!SecurityLog.isLoggingEnabled()) {
20070            return;
20071        }
20072        Bundle data = new Bundle();
20073        data.putLong("startTimestamp", System.currentTimeMillis());
20074        data.putString("processName", processName);
20075        data.putInt("uid", uid);
20076        data.putString("seinfo", seinfo);
20077        data.putString("apkFile", apkFile);
20078        data.putInt("pid", pid);
20079        Message msg = mProcessLoggingHandler.obtainMessage(
20080                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20081        msg.setData(data);
20082        mProcessLoggingHandler.sendMessage(msg);
20083    }
20084}
20085