PackageManagerService.java revision a2241834a54dc91e2eef858741f1a56a743c27b2
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.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
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.EphemeralDigest;
129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
130import android.content.pm.FeatureInfo;
131import android.content.pm.IOnPermissionsChangeListener;
132import android.content.pm.IPackageDataObserver;
133import android.content.pm.IPackageDeleteObserver;
134import android.content.pm.IPackageDeleteObserver2;
135import android.content.pm.IPackageInstallObserver2;
136import android.content.pm.IPackageInstaller;
137import android.content.pm.IPackageManager;
138import android.content.pm.IPackageMoveObserver;
139import android.content.pm.IPackageStatsObserver;
140import android.content.pm.InstrumentationInfo;
141import android.content.pm.IntentFilterVerificationInfo;
142import android.content.pm.KeySet;
143import android.content.pm.PackageCleanItem;
144import android.content.pm.PackageInfo;
145import android.content.pm.PackageInfoLite;
146import android.content.pm.PackageInstaller;
147import android.content.pm.PackageManager;
148import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
149import android.content.pm.PackageManagerInternal;
150import android.content.pm.PackageParser;
151import android.content.pm.PackageParser.ActivityIntentInfo;
152import android.content.pm.PackageParser.PackageLite;
153import android.content.pm.PackageParser.PackageParserException;
154import android.content.pm.PackageStats;
155import android.content.pm.PackageUserState;
156import android.content.pm.ParceledListSlice;
157import android.content.pm.PermissionGroupInfo;
158import android.content.pm.PermissionInfo;
159import android.content.pm.ProviderInfo;
160import android.content.pm.ResolveInfo;
161import android.content.pm.ServiceInfo;
162import android.content.pm.ShortcutServiceInternal;
163import android.content.pm.Signature;
164import android.content.pm.UserInfo;
165import android.content.pm.VerifierDeviceIdentity;
166import android.content.pm.VerifierInfo;
167import android.content.res.Resources;
168import android.graphics.Bitmap;
169import android.hardware.display.DisplayManager;
170import android.net.Uri;
171import android.os.Binder;
172import android.os.Build;
173import android.os.Bundle;
174import android.os.Debug;
175import android.os.Environment;
176import android.os.Environment.UserEnvironment;
177import android.os.FileUtils;
178import android.os.Handler;
179import android.os.IBinder;
180import android.os.Looper;
181import android.os.Message;
182import android.os.Parcel;
183import android.os.ParcelFileDescriptor;
184import android.os.Process;
185import android.os.RemoteCallbackList;
186import android.os.RemoteException;
187import android.os.ResultReceiver;
188import android.os.SELinux;
189import android.os.ServiceManager;
190import android.os.SystemClock;
191import android.os.SystemProperties;
192import android.os.Trace;
193import android.os.UserHandle;
194import android.os.UserManager;
195import android.os.UserManagerInternal;
196import android.os.storage.IMountService;
197import android.os.storage.MountServiceInternal;
198import android.os.storage.StorageEventListener;
199import android.os.storage.StorageManager;
200import android.os.storage.VolumeInfo;
201import android.os.storage.VolumeRecord;
202import android.provider.Settings.Global;
203import android.security.KeyStore;
204import android.security.SystemKeyStore;
205import android.system.ErrnoException;
206import android.system.Os;
207import android.text.TextUtils;
208import android.text.format.DateUtils;
209import android.util.ArrayMap;
210import android.util.ArraySet;
211import android.util.AtomicFile;
212import android.util.DisplayMetrics;
213import android.util.EventLog;
214import android.util.ExceptionUtils;
215import android.util.Log;
216import android.util.LogPrinter;
217import android.util.MathUtils;
218import android.util.PrintStreamPrinter;
219import android.util.Slog;
220import android.util.SparseArray;
221import android.util.SparseBooleanArray;
222import android.util.SparseIntArray;
223import android.util.Xml;
224import android.util.jar.StrictJarFile;
225import android.view.Display;
226
227import com.android.internal.R;
228import com.android.internal.annotations.GuardedBy;
229import com.android.internal.app.IMediaContainerService;
230import com.android.internal.app.ResolverActivity;
231import com.android.internal.content.NativeLibraryHelper;
232import com.android.internal.content.PackageHelper;
233import com.android.internal.logging.MetricsLogger;
234import com.android.internal.os.IParcelFileDescriptorFactory;
235import com.android.internal.os.InstallerConnection.InstallerException;
236import com.android.internal.os.SomeArgs;
237import com.android.internal.os.Zygote;
238import com.android.internal.telephony.CarrierAppUtils;
239import com.android.internal.util.ArrayUtils;
240import com.android.internal.util.FastPrintWriter;
241import com.android.internal.util.FastXmlSerializer;
242import com.android.internal.util.IndentingPrintWriter;
243import com.android.internal.util.Preconditions;
244import com.android.internal.util.XmlUtils;
245import com.android.server.AttributeCache;
246import com.android.server.EventLogTags;
247import com.android.server.FgThread;
248import com.android.server.IntentResolver;
249import com.android.server.LocalServices;
250import com.android.server.ServiceThread;
251import com.android.server.SystemConfig;
252import com.android.server.Watchdog;
253import com.android.server.net.NetworkPolicyManagerInternal;
254import com.android.server.pm.PermissionsState.PermissionState;
255import com.android.server.pm.Settings.DatabaseVersion;
256import com.android.server.pm.Settings.VersionInfo;
257import com.android.server.storage.DeviceStorageMonitorInternal;
258
259import dalvik.system.CloseGuard;
260import dalvik.system.DexFile;
261import dalvik.system.VMRuntime;
262
263import libcore.io.IoUtils;
264import libcore.util.EmptyArray;
265
266import org.xmlpull.v1.XmlPullParser;
267import org.xmlpull.v1.XmlPullParserException;
268import org.xmlpull.v1.XmlSerializer;
269
270import java.io.BufferedInputStream;
271import java.io.BufferedOutputStream;
272import java.io.BufferedReader;
273import java.io.ByteArrayInputStream;
274import java.io.ByteArrayOutputStream;
275import java.io.File;
276import java.io.FileDescriptor;
277import java.io.FileInputStream;
278import java.io.FileNotFoundException;
279import java.io.FileOutputStream;
280import java.io.FileReader;
281import java.io.FilenameFilter;
282import java.io.IOException;
283import java.io.InputStream;
284import java.io.PrintWriter;
285import java.nio.charset.StandardCharsets;
286import java.security.DigestInputStream;
287import java.security.MessageDigest;
288import java.security.NoSuchAlgorithmException;
289import java.security.PublicKey;
290import java.security.cert.Certificate;
291import java.security.cert.CertificateEncodingException;
292import java.security.cert.CertificateException;
293import java.text.SimpleDateFormat;
294import java.util.ArrayList;
295import java.util.Arrays;
296import java.util.Collection;
297import java.util.Collections;
298import java.util.Comparator;
299import java.util.Date;
300import java.util.HashSet;
301import java.util.Iterator;
302import java.util.List;
303import java.util.Map;
304import java.util.Objects;
305import java.util.Set;
306import java.util.concurrent.CountDownLatch;
307import java.util.concurrent.TimeUnit;
308import java.util.concurrent.atomic.AtomicBoolean;
309import java.util.concurrent.atomic.AtomicInteger;
310import java.util.concurrent.atomic.AtomicLong;
311
312/**
313 * Keep track of all those APKs everywhere.
314 * <p>
315 * Internally there are two important locks:
316 * <ul>
317 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
318 * and other related state. It is a fine-grained lock that should only be held
319 * momentarily, as it's one of the most contended locks in the system.
320 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
321 * operations typically involve heavy lifting of application data on disk. Since
322 * {@code installd} is single-threaded, and it's operations can often be slow,
323 * this lock should never be acquired while already holding {@link #mPackages}.
324 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
325 * holding {@link #mInstallLock}.
326 * </ul>
327 * Many internal methods rely on the caller to hold the appropriate locks, and
328 * this contract is expressed through method name suffixes:
329 * <ul>
330 * <li>fooLI(): the caller must hold {@link #mInstallLock}
331 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
332 * being modified must be frozen
333 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
334 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
335 * </ul>
336 * <p>
337 * Because this class is very central to the platform's security; please run all
338 * CTS and unit tests whenever making modifications:
339 *
340 * <pre>
341 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
342 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
343 * </pre>
344 */
345public class PackageManagerService extends IPackageManager.Stub {
346    static final String TAG = "PackageManager";
347    static final boolean DEBUG_SETTINGS = false;
348    static final boolean DEBUG_PREFERRED = false;
349    static final boolean DEBUG_UPGRADE = false;
350    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
351    private static final boolean DEBUG_BACKUP = false;
352    private static final boolean DEBUG_INSTALL = false;
353    private static final boolean DEBUG_REMOVE = false;
354    private static final boolean DEBUG_BROADCASTS = false;
355    private static final boolean DEBUG_SHOW_INFO = false;
356    private static final boolean DEBUG_PACKAGE_INFO = false;
357    private static final boolean DEBUG_INTENT_MATCHING = false;
358    private static final boolean DEBUG_PACKAGE_SCANNING = false;
359    private static final boolean DEBUG_VERIFY = false;
360    private static final boolean DEBUG_FILTERS = false;
361
362    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
363    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
364    // user, but by default initialize to this.
365    static final boolean DEBUG_DEXOPT = false;
366
367    private static final boolean DEBUG_ABI_SELECTION = false;
368    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
369    private static final boolean DEBUG_TRIAGED_MISSING = false;
370    private static final boolean DEBUG_APP_DATA = false;
371
372    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
373
374    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
375
376    private static final int RADIO_UID = Process.PHONE_UID;
377    private static final int LOG_UID = Process.LOG_UID;
378    private static final int NFC_UID = Process.NFC_UID;
379    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
380    private static final int SHELL_UID = Process.SHELL_UID;
381
382    // Cap the size of permission trees that 3rd party apps can define
383    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
384
385    // Suffix used during package installation when copying/moving
386    // package apks to install directory.
387    private static final String INSTALL_PACKAGE_SUFFIX = "-";
388
389    static final int SCAN_NO_DEX = 1<<1;
390    static final int SCAN_FORCE_DEX = 1<<2;
391    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
392    static final int SCAN_NEW_INSTALL = 1<<4;
393    static final int SCAN_NO_PATHS = 1<<5;
394    static final int SCAN_UPDATE_TIME = 1<<6;
395    static final int SCAN_DEFER_DEX = 1<<7;
396    static final int SCAN_BOOTING = 1<<8;
397    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
398    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
399    static final int SCAN_REPLACING = 1<<11;
400    static final int SCAN_REQUIRE_KNOWN = 1<<12;
401    static final int SCAN_MOVE = 1<<13;
402    static final int SCAN_INITIAL = 1<<14;
403    static final int SCAN_CHECK_ONLY = 1<<15;
404    static final int SCAN_DONT_KILL_APP = 1<<17;
405    static final int SCAN_IGNORE_FROZEN = 1<<18;
406
407    static final int REMOVE_CHATTY = 1<<16;
408
409    private static final int[] EMPTY_INT_ARRAY = new int[0];
410
411    /**
412     * Timeout (in milliseconds) after which the watchdog should declare that
413     * our handler thread is wedged.  The usual default for such things is one
414     * minute but we sometimes do very lengthy I/O operations on this thread,
415     * such as installing multi-gigabyte applications, so ours needs to be longer.
416     */
417    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
418
419    /**
420     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
421     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
422     * settings entry if available, otherwise we use the hardcoded default.  If it's been
423     * more than this long since the last fstrim, we force one during the boot sequence.
424     *
425     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
426     * one gets run at the next available charging+idle time.  This final mandatory
427     * no-fstrim check kicks in only of the other scheduling criteria is never met.
428     */
429    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
430
431    /**
432     * Whether verification is enabled by default.
433     */
434    private static final boolean DEFAULT_VERIFY_ENABLE = true;
435
436    /**
437     * The default maximum time to wait for the verification agent to return in
438     * milliseconds.
439     */
440    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
441
442    /**
443     * The default response for package verification timeout.
444     *
445     * This can be either PackageManager.VERIFICATION_ALLOW or
446     * PackageManager.VERIFICATION_REJECT.
447     */
448    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
449
450    static final String PLATFORM_PACKAGE_NAME = "android";
451
452    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
453
454    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
455            DEFAULT_CONTAINER_PACKAGE,
456            "com.android.defcontainer.DefaultContainerService");
457
458    private static final String KILL_APP_REASON_GIDS_CHANGED =
459            "permission grant or revoke changed gids";
460
461    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
462            "permissions revoked";
463
464    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
465
466    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
467
468    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
469    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
470
471    /** Permission grant: not grant the permission. */
472    private static final int GRANT_DENIED = 1;
473
474    /** Permission grant: grant the permission as an install permission. */
475    private static final int GRANT_INSTALL = 2;
476
477    /** Permission grant: grant the permission as a runtime one. */
478    private static final int GRANT_RUNTIME = 3;
479
480    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
481    private static final int GRANT_UPGRADE = 4;
482
483    /** Canonical intent used to identify what counts as a "web browser" app */
484    private static final Intent sBrowserIntent;
485    static {
486        sBrowserIntent = new Intent();
487        sBrowserIntent.setAction(Intent.ACTION_VIEW);
488        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
489        sBrowserIntent.setData(Uri.parse("http:"));
490    }
491
492    /**
493     * The set of all protected actions [i.e. those actions for which a high priority
494     * intent filter is disallowed].
495     */
496    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
497    static {
498        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
499        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
500        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
501        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
502    }
503
504    // Compilation reasons.
505    public static final int REASON_FIRST_BOOT = 0;
506    public static final int REASON_BOOT = 1;
507    public static final int REASON_INSTALL = 2;
508    public static final int REASON_BACKGROUND_DEXOPT = 3;
509    public static final int REASON_AB_OTA = 4;
510    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
511    public static final int REASON_SHARED_APK = 6;
512    public static final int REASON_FORCED_DEXOPT = 7;
513    public static final int REASON_CORE_APP = 8;
514
515    public static final int REASON_LAST = REASON_CORE_APP;
516
517    /** Special library name that skips shared libraries check during compilation. */
518    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
519
520    final ServiceThread mHandlerThread;
521
522    final PackageHandler mHandler;
523
524    private final ProcessLoggingHandler mProcessLoggingHandler;
525
526    /**
527     * Messages for {@link #mHandler} that need to wait for system ready before
528     * being dispatched.
529     */
530    private ArrayList<Message> mPostSystemReadyMessages;
531
532    final int mSdkVersion = Build.VERSION.SDK_INT;
533
534    final Context mContext;
535    final boolean mFactoryTest;
536    final boolean mOnlyCore;
537    final DisplayMetrics mMetrics;
538    final int mDefParseFlags;
539    final String[] mSeparateProcesses;
540    final boolean mIsUpgrade;
541    final boolean mIsPreNUpgrade;
542
543    /** The location for ASEC container files on internal storage. */
544    final String mAsecInternalPath;
545
546    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
547    // LOCK HELD.  Can be called with mInstallLock held.
548    @GuardedBy("mInstallLock")
549    final Installer mInstaller;
550
551    /** Directory where installed third-party apps stored */
552    final File mAppInstallDir;
553    final File mEphemeralInstallDir;
554
555    /**
556     * Directory to which applications installed internally have their
557     * 32 bit native libraries copied.
558     */
559    private File mAppLib32InstallDir;
560
561    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
562    // apps.
563    final File mDrmAppPrivateInstallDir;
564
565    // ----------------------------------------------------------------
566
567    // Lock for state used when installing and doing other long running
568    // operations.  Methods that must be called with this lock held have
569    // the suffix "LI".
570    final Object mInstallLock = new Object();
571
572    // ----------------------------------------------------------------
573
574    // Keys are String (package name), values are Package.  This also serves
575    // as the lock for the global state.  Methods that must be called with
576    // this lock held have the prefix "LP".
577    @GuardedBy("mPackages")
578    final ArrayMap<String, PackageParser.Package> mPackages =
579            new ArrayMap<String, PackageParser.Package>();
580
581    final ArrayMap<String, Set<String>> mKnownCodebase =
582            new ArrayMap<String, Set<String>>();
583
584    // Tracks available target package names -> overlay package paths.
585    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
586        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
587
588    /**
589     * Tracks new system packages [received in an OTA] that we expect to
590     * find updated user-installed versions. Keys are package name, values
591     * are package location.
592     */
593    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
594    /**
595     * Tracks high priority intent filters for protected actions. During boot, certain
596     * filter actions are protected and should never be allowed to have a high priority
597     * intent filter for them. However, there is one, and only one exception -- the
598     * setup wizard. It must be able to define a high priority intent filter for these
599     * actions to ensure there are no escapes from the wizard. We need to delay processing
600     * of these during boot as we need to look at all of the system packages in order
601     * to know which component is the setup wizard.
602     */
603    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
604    /**
605     * Whether or not processing protected filters should be deferred.
606     */
607    private boolean mDeferProtectedFilters = true;
608
609    /**
610     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
611     */
612    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
613    /**
614     * Whether or not system app permissions should be promoted from install to runtime.
615     */
616    boolean mPromoteSystemApps;
617
618    @GuardedBy("mPackages")
619    final Settings mSettings;
620
621    /**
622     * Set of package names that are currently "frozen", which means active
623     * surgery is being done on the code/data for that package. The platform
624     * will refuse to launch frozen packages to avoid race conditions.
625     *
626     * @see PackageFreezer
627     */
628    @GuardedBy("mPackages")
629    final ArraySet<String> mFrozenPackages = new ArraySet<>();
630
631    final ProtectedPackages mProtectedPackages;
632
633    boolean mFirstBoot;
634
635    // System configuration read by SystemConfig.
636    final int[] mGlobalGids;
637    final SparseArray<ArraySet<String>> mSystemPermissions;
638    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
639
640    // If mac_permissions.xml was found for seinfo labeling.
641    boolean mFoundPolicyFile;
642
643    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
644
645    public static final class SharedLibraryEntry {
646        public final String path;
647        public final String apk;
648
649        SharedLibraryEntry(String _path, String _apk) {
650            path = _path;
651            apk = _apk;
652        }
653    }
654
655    // Currently known shared libraries.
656    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
657            new ArrayMap<String, SharedLibraryEntry>();
658
659    // All available activities, for your resolving pleasure.
660    final ActivityIntentResolver mActivities =
661            new ActivityIntentResolver();
662
663    // All available receivers, for your resolving pleasure.
664    final ActivityIntentResolver mReceivers =
665            new ActivityIntentResolver();
666
667    // All available services, for your resolving pleasure.
668    final ServiceIntentResolver mServices = new ServiceIntentResolver();
669
670    // All available providers, for your resolving pleasure.
671    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
672
673    // Mapping from provider base names (first directory in content URI codePath)
674    // to the provider information.
675    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
676            new ArrayMap<String, PackageParser.Provider>();
677
678    // Mapping from instrumentation class names to info about them.
679    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
680            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
681
682    // Mapping from permission names to info about them.
683    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
684            new ArrayMap<String, PackageParser.PermissionGroup>();
685
686    // Packages whose data we have transfered into another package, thus
687    // should no longer exist.
688    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
689
690    // Broadcast actions that are only available to the system.
691    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
692
693    /** List of packages waiting for verification. */
694    final SparseArray<PackageVerificationState> mPendingVerification
695            = new SparseArray<PackageVerificationState>();
696
697    /** Set of packages associated with each app op permission. */
698    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
699
700    final PackageInstallerService mInstallerService;
701
702    private final PackageDexOptimizer mPackageDexOptimizer;
703
704    private AtomicInteger mNextMoveId = new AtomicInteger();
705    private final MoveCallbacks mMoveCallbacks;
706
707    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
708
709    // Cache of users who need badging.
710    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
711
712    /** Token for keys in mPendingVerification. */
713    private int mPendingVerificationToken = 0;
714
715    volatile boolean mSystemReady;
716    volatile boolean mSafeMode;
717    volatile boolean mHasSystemUidErrors;
718
719    ApplicationInfo mAndroidApplication;
720    final ActivityInfo mResolveActivity = new ActivityInfo();
721    final ResolveInfo mResolveInfo = new ResolveInfo();
722    ComponentName mResolveComponentName;
723    PackageParser.Package mPlatformPackage;
724    ComponentName mCustomResolverComponentName;
725
726    boolean mResolverReplaced = false;
727
728    private final @Nullable ComponentName mIntentFilterVerifierComponent;
729    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
730
731    private int mIntentFilterVerificationToken = 0;
732
733    /** Component that knows whether or not an ephemeral application exists */
734    final ComponentName mEphemeralResolverComponent;
735    /** The service connection to the ephemeral resolver */
736    final EphemeralResolverConnection mEphemeralResolverConnection;
737
738    /** Component used to install ephemeral applications */
739    final ComponentName mEphemeralInstallerComponent;
740    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
741    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
742
743    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
744            = new SparseArray<IntentFilterVerificationState>();
745
746    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
747            new DefaultPermissionGrantPolicy(this);
748
749    // List of packages names to keep cached, even if they are uninstalled for all users
750    private List<String> mKeepUninstalledPackages;
751
752    private UserManagerInternal mUserManagerInternal;
753
754    private static class IFVerificationParams {
755        PackageParser.Package pkg;
756        boolean replacing;
757        int userId;
758        int verifierUid;
759
760        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
761                int _userId, int _verifierUid) {
762            pkg = _pkg;
763            replacing = _replacing;
764            userId = _userId;
765            replacing = _replacing;
766            verifierUid = _verifierUid;
767        }
768    }
769
770    private interface IntentFilterVerifier<T extends IntentFilter> {
771        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
772                                               T filter, String packageName);
773        void startVerifications(int userId);
774        void receiveVerificationResponse(int verificationId);
775    }
776
777    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
778        private Context mContext;
779        private ComponentName mIntentFilterVerifierComponent;
780        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
781
782        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
783            mContext = context;
784            mIntentFilterVerifierComponent = verifierComponent;
785        }
786
787        private String getDefaultScheme() {
788            return IntentFilter.SCHEME_HTTPS;
789        }
790
791        @Override
792        public void startVerifications(int userId) {
793            // Launch verifications requests
794            int count = mCurrentIntentFilterVerifications.size();
795            for (int n=0; n<count; n++) {
796                int verificationId = mCurrentIntentFilterVerifications.get(n);
797                final IntentFilterVerificationState ivs =
798                        mIntentFilterVerificationStates.get(verificationId);
799
800                String packageName = ivs.getPackageName();
801
802                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
803                final int filterCount = filters.size();
804                ArraySet<String> domainsSet = new ArraySet<>();
805                for (int m=0; m<filterCount; m++) {
806                    PackageParser.ActivityIntentInfo filter = filters.get(m);
807                    domainsSet.addAll(filter.getHostsList());
808                }
809                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
810                synchronized (mPackages) {
811                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
812                            packageName, domainsList) != null) {
813                        scheduleWriteSettingsLocked();
814                    }
815                }
816                sendVerificationRequest(userId, verificationId, ivs);
817            }
818            mCurrentIntentFilterVerifications.clear();
819        }
820
821        private void sendVerificationRequest(int userId, int verificationId,
822                IntentFilterVerificationState ivs) {
823
824            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
827                    verificationId);
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
830                    getDefaultScheme());
831            verificationIntent.putExtra(
832                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
833                    ivs.getHostsString());
834            verificationIntent.putExtra(
835                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
836                    ivs.getPackageName());
837            verificationIntent.setComponent(mIntentFilterVerifierComponent);
838            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
839
840            UserHandle user = new UserHandle(userId);
841            mContext.sendBroadcastAsUser(verificationIntent, user);
842            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
843                    "Sending IntentFilter verification broadcast");
844        }
845
846        public void receiveVerificationResponse(int verificationId) {
847            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
848
849            final boolean verified = ivs.isVerified();
850
851            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
852            final int count = filters.size();
853            if (DEBUG_DOMAIN_VERIFICATION) {
854                Slog.i(TAG, "Received verification response " + verificationId
855                        + " for " + count + " filters, verified=" + verified);
856            }
857            for (int n=0; n<count; n++) {
858                PackageParser.ActivityIntentInfo filter = filters.get(n);
859                filter.setVerified(verified);
860
861                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
862                        + " verified with result:" + verified + " and hosts:"
863                        + ivs.getHostsString());
864            }
865
866            mIntentFilterVerificationStates.remove(verificationId);
867
868            final String packageName = ivs.getPackageName();
869            IntentFilterVerificationInfo ivi = null;
870
871            synchronized (mPackages) {
872                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
873            }
874            if (ivi == null) {
875                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
876                        + verificationId + " packageName:" + packageName);
877                return;
878            }
879            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
880                    "Updating IntentFilterVerificationInfo for package " + packageName
881                            +" verificationId:" + verificationId);
882
883            synchronized (mPackages) {
884                if (verified) {
885                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
886                } else {
887                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
888                }
889                scheduleWriteSettingsLocked();
890
891                final int userId = ivs.getUserId();
892                if (userId != UserHandle.USER_ALL) {
893                    final int userStatus =
894                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
895
896                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
897                    boolean needUpdate = false;
898
899                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
900                    // already been set by the User thru the Disambiguation dialog
901                    switch (userStatus) {
902                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
903                            if (verified) {
904                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
905                            } else {
906                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
907                            }
908                            needUpdate = true;
909                            break;
910
911                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
912                            if (verified) {
913                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914                                needUpdate = true;
915                            }
916                            break;
917
918                        default:
919                            // Nothing to do
920                    }
921
922                    if (needUpdate) {
923                        mSettings.updateIntentFilterVerificationStatusLPw(
924                                packageName, updatedStatus, userId);
925                        scheduleWritePackageRestrictionsLocked(userId);
926                    }
927                }
928            }
929        }
930
931        @Override
932        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
933                    ActivityIntentInfo filter, String packageName) {
934            if (!hasValidDomains(filter)) {
935                return false;
936            }
937            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
938            if (ivs == null) {
939                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
940                        packageName);
941            }
942            if (DEBUG_DOMAIN_VERIFICATION) {
943                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
944            }
945            ivs.addFilter(filter);
946            return true;
947        }
948
949        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
950                int userId, int verificationId, String packageName) {
951            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
952                    verifierUid, userId, packageName);
953            ivs.setPendingState();
954            synchronized (mPackages) {
955                mIntentFilterVerificationStates.append(verificationId, ivs);
956                mCurrentIntentFilterVerifications.add(verificationId);
957            }
958            return ivs;
959        }
960    }
961
962    private static boolean hasValidDomains(ActivityIntentInfo filter) {
963        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
964                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
965                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
966    }
967
968    // Set of pending broadcasts for aggregating enable/disable of components.
969    static class PendingPackageBroadcasts {
970        // for each user id, a map of <package name -> components within that package>
971        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
972
973        public PendingPackageBroadcasts() {
974            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
975        }
976
977        public ArrayList<String> get(int userId, String packageName) {
978            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
979            return packages.get(packageName);
980        }
981
982        public void put(int userId, String packageName, ArrayList<String> components) {
983            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
984            packages.put(packageName, components);
985        }
986
987        public void remove(int userId, String packageName) {
988            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
989            if (packages != null) {
990                packages.remove(packageName);
991            }
992        }
993
994        public void remove(int userId) {
995            mUidMap.remove(userId);
996        }
997
998        public int userIdCount() {
999            return mUidMap.size();
1000        }
1001
1002        public int userIdAt(int n) {
1003            return mUidMap.keyAt(n);
1004        }
1005
1006        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1007            return mUidMap.get(userId);
1008        }
1009
1010        public int size() {
1011            // total number of pending broadcast entries across all userIds
1012            int num = 0;
1013            for (int i = 0; i< mUidMap.size(); i++) {
1014                num += mUidMap.valueAt(i).size();
1015            }
1016            return num;
1017        }
1018
1019        public void clear() {
1020            mUidMap.clear();
1021        }
1022
1023        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1024            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1025            if (map == null) {
1026                map = new ArrayMap<String, ArrayList<String>>();
1027                mUidMap.put(userId, map);
1028            }
1029            return map;
1030        }
1031    }
1032    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1033
1034    // Service Connection to remote media container service to copy
1035    // package uri's from external media onto secure containers
1036    // or internal storage.
1037    private IMediaContainerService mContainerService = null;
1038
1039    static final int SEND_PENDING_BROADCAST = 1;
1040    static final int MCS_BOUND = 3;
1041    static final int END_COPY = 4;
1042    static final int INIT_COPY = 5;
1043    static final int MCS_UNBIND = 6;
1044    static final int START_CLEANING_PACKAGE = 7;
1045    static final int FIND_INSTALL_LOC = 8;
1046    static final int POST_INSTALL = 9;
1047    static final int MCS_RECONNECT = 10;
1048    static final int MCS_GIVE_UP = 11;
1049    static final int UPDATED_MEDIA_STATUS = 12;
1050    static final int WRITE_SETTINGS = 13;
1051    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1052    static final int PACKAGE_VERIFIED = 15;
1053    static final int CHECK_PENDING_VERIFICATION = 16;
1054    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1055    static final int INTENT_FILTER_VERIFIED = 18;
1056    static final int WRITE_PACKAGE_LIST = 19;
1057
1058    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1059
1060    // Delay time in millisecs
1061    static final int BROADCAST_DELAY = 10 * 1000;
1062
1063    static UserManagerService sUserManager;
1064
1065    // Stores a list of users whose package restrictions file needs to be updated
1066    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1067
1068    final private DefaultContainerConnection mDefContainerConn =
1069            new DefaultContainerConnection();
1070    class DefaultContainerConnection implements ServiceConnection {
1071        public void onServiceConnected(ComponentName name, IBinder service) {
1072            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1073            IMediaContainerService imcs =
1074                IMediaContainerService.Stub.asInterface(service);
1075            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1076        }
1077
1078        public void onServiceDisconnected(ComponentName name) {
1079            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1080        }
1081    }
1082
1083    // Recordkeeping of restore-after-install operations that are currently in flight
1084    // between the Package Manager and the Backup Manager
1085    static class PostInstallData {
1086        public InstallArgs args;
1087        public PackageInstalledInfo res;
1088
1089        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1090            args = _a;
1091            res = _r;
1092        }
1093    }
1094
1095    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1096    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1097
1098    // XML tags for backup/restore of various bits of state
1099    private static final String TAG_PREFERRED_BACKUP = "pa";
1100    private static final String TAG_DEFAULT_APPS = "da";
1101    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1102
1103    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1104    private static final String TAG_ALL_GRANTS = "rt-grants";
1105    private static final String TAG_GRANT = "grant";
1106    private static final String ATTR_PACKAGE_NAME = "pkg";
1107
1108    private static final String TAG_PERMISSION = "perm";
1109    private static final String ATTR_PERMISSION_NAME = "name";
1110    private static final String ATTR_IS_GRANTED = "g";
1111    private static final String ATTR_USER_SET = "set";
1112    private static final String ATTR_USER_FIXED = "fixed";
1113    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1114
1115    // System/policy permission grants are not backed up
1116    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_POLICY_FIXED
1118            | FLAG_PERMISSION_SYSTEM_FIXED
1119            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1120
1121    // And we back up these user-adjusted states
1122    private static final int USER_RUNTIME_GRANT_MASK =
1123            FLAG_PERMISSION_USER_SET
1124            | FLAG_PERMISSION_USER_FIXED
1125            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1126
1127    final @Nullable String mRequiredVerifierPackage;
1128    final @NonNull String mRequiredInstallerPackage;
1129    final @Nullable String mSetupWizardPackage;
1130    final @NonNull String mServicesSystemSharedLibraryPackageName;
1131    final @NonNull String mSharedSystemSharedLibraryPackageName;
1132
1133    private final PackageUsage mPackageUsage = new PackageUsage();
1134
1135    private class PackageUsage {
1136        private static final int WRITE_INTERVAL
1137            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1138
1139        private final Object mFileLock = new Object();
1140        private final AtomicLong mLastWritten = new AtomicLong(0);
1141        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1142
1143        private boolean mIsHistoricalPackageUsageAvailable = true;
1144
1145        boolean isHistoricalPackageUsageAvailable() {
1146            return mIsHistoricalPackageUsageAvailable;
1147        }
1148
1149        void write(boolean force) {
1150            if (force) {
1151                writeInternal();
1152                return;
1153            }
1154            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1155                && !DEBUG_DEXOPT) {
1156                return;
1157            }
1158            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1159                new Thread("PackageUsage_DiskWriter") {
1160                    @Override
1161                    public void run() {
1162                        try {
1163                            writeInternal();
1164                        } finally {
1165                            mBackgroundWriteRunning.set(false);
1166                        }
1167                    }
1168                }.start();
1169            }
1170        }
1171
1172        private void writeInternal() {
1173            synchronized (mPackages) {
1174                synchronized (mFileLock) {
1175                    AtomicFile file = getFile();
1176                    FileOutputStream f = null;
1177                    try {
1178                        f = file.startWrite();
1179                        BufferedOutputStream out = new BufferedOutputStream(f);
1180                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1181                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1182                        StringBuilder sb = new StringBuilder();
1183
1184                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1185                        sb.append('\n');
1186                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1187
1188                        for (PackageParser.Package pkg : mPackages.values()) {
1189                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1190                                continue;
1191                            }
1192                            sb.setLength(0);
1193                            sb.append(pkg.packageName);
1194                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1195                                sb.append(' ');
1196                                sb.append(usageTimeInMillis);
1197                            }
1198                            sb.append('\n');
1199                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1200                        }
1201                        out.flush();
1202                        file.finishWrite(f);
1203                    } catch (IOException e) {
1204                        if (f != null) {
1205                            file.failWrite(f);
1206                        }
1207                        Log.e(TAG, "Failed to write package usage times", e);
1208                    }
1209                }
1210            }
1211            mLastWritten.set(SystemClock.elapsedRealtime());
1212        }
1213
1214        void readLP() {
1215            synchronized (mFileLock) {
1216                AtomicFile file = getFile();
1217                BufferedInputStream in = null;
1218                try {
1219                    in = new BufferedInputStream(file.openRead());
1220                    StringBuffer sb = new StringBuffer();
1221
1222                    String firstLine = readLine(in, sb);
1223                    if (firstLine == null) {
1224                        // Empty file. Do nothing.
1225                    } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) {
1226                        readVersion1LP(in, sb);
1227                    } else {
1228                        readVersion0LP(in, sb, firstLine);
1229                    }
1230                } catch (FileNotFoundException expected) {
1231                    mIsHistoricalPackageUsageAvailable = false;
1232                } catch (IOException e) {
1233                    Log.w(TAG, "Failed to read package usage times", e);
1234                } finally {
1235                    IoUtils.closeQuietly(in);
1236                }
1237            }
1238            mLastWritten.set(SystemClock.elapsedRealtime());
1239        }
1240
1241        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1242                throws IOException {
1243            // Initial version of the file had no version number and stored one
1244            // package-timestamp pair per line.
1245            // Note that the first line has already been read from the InputStream.
1246            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1247                String[] tokens = line.split(" ");
1248                if (tokens.length != 2) {
1249                    throw new IOException("Failed to parse " + line +
1250                            " as package-timestamp pair.");
1251                }
1252
1253                String packageName = tokens[0];
1254                PackageParser.Package pkg = mPackages.get(packageName);
1255                if (pkg == null) {
1256                    continue;
1257                }
1258
1259                long timestamp = parseAsLong(tokens[1]);
1260                for (int reason = 0;
1261                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1262                        reason++) {
1263                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1264                }
1265            }
1266        }
1267
1268        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1269            // Version 1 of the file started with the corresponding version
1270            // number and then stored a package name and eight timestamps per line.
1271            String line;
1272            while ((line = readLine(in, sb)) != null) {
1273                String[] tokens = line.split(" ");
1274                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1275                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1276                }
1277
1278                String packageName = tokens[0];
1279                PackageParser.Package pkg = mPackages.get(packageName);
1280                if (pkg == null) {
1281                    continue;
1282                }
1283
1284                for (int reason = 0;
1285                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1286                        reason++) {
1287                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1288                }
1289            }
1290        }
1291
1292        private long parseAsLong(String token) throws IOException {
1293            try {
1294                return Long.parseLong(token);
1295            } catch (NumberFormatException e) {
1296                throw new IOException("Failed to parse " + token + " as a long.", e);
1297            }
1298        }
1299
1300        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1301            return readToken(in, sb, '\n');
1302        }
1303
1304        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1305                throws IOException {
1306            sb.setLength(0);
1307            while (true) {
1308                int ch = in.read();
1309                if (ch == -1) {
1310                    if (sb.length() == 0) {
1311                        return null;
1312                    }
1313                    throw new IOException("Unexpected EOF");
1314                }
1315                if (ch == endOfToken) {
1316                    return sb.toString();
1317                }
1318                sb.append((char)ch);
1319            }
1320        }
1321
1322        private AtomicFile getFile() {
1323            File dataDir = Environment.getDataDirectory();
1324            File systemDir = new File(dataDir, "system");
1325            File fname = new File(systemDir, "package-usage.list");
1326            return new AtomicFile(fname);
1327        }
1328
1329        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1330        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1331    }
1332
1333    class PackageHandler extends Handler {
1334        private boolean mBound = false;
1335        final ArrayList<HandlerParams> mPendingInstalls =
1336            new ArrayList<HandlerParams>();
1337
1338        private boolean connectToService() {
1339            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1340                    " DefaultContainerService");
1341            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1342            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1343            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1344                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1345                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1346                mBound = true;
1347                return true;
1348            }
1349            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1350            return false;
1351        }
1352
1353        private void disconnectService() {
1354            mContainerService = null;
1355            mBound = false;
1356            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1357            mContext.unbindService(mDefContainerConn);
1358            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1359        }
1360
1361        PackageHandler(Looper looper) {
1362            super(looper);
1363        }
1364
1365        public void handleMessage(Message msg) {
1366            try {
1367                doHandleMessage(msg);
1368            } finally {
1369                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1370            }
1371        }
1372
1373        void doHandleMessage(Message msg) {
1374            switch (msg.what) {
1375                case INIT_COPY: {
1376                    HandlerParams params = (HandlerParams) msg.obj;
1377                    int idx = mPendingInstalls.size();
1378                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1379                    // If a bind was already initiated we dont really
1380                    // need to do anything. The pending install
1381                    // will be processed later on.
1382                    if (!mBound) {
1383                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1384                                System.identityHashCode(mHandler));
1385                        // If this is the only one pending we might
1386                        // have to bind to the service again.
1387                        if (!connectToService()) {
1388                            Slog.e(TAG, "Failed to bind to media container service");
1389                            params.serviceError();
1390                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1391                                    System.identityHashCode(mHandler));
1392                            if (params.traceMethod != null) {
1393                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1394                                        params.traceCookie);
1395                            }
1396                            return;
1397                        } else {
1398                            // Once we bind to the service, the first
1399                            // pending request will be processed.
1400                            mPendingInstalls.add(idx, params);
1401                        }
1402                    } else {
1403                        mPendingInstalls.add(idx, params);
1404                        // Already bound to the service. Just make
1405                        // sure we trigger off processing the first request.
1406                        if (idx == 0) {
1407                            mHandler.sendEmptyMessage(MCS_BOUND);
1408                        }
1409                    }
1410                    break;
1411                }
1412                case MCS_BOUND: {
1413                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1414                    if (msg.obj != null) {
1415                        mContainerService = (IMediaContainerService) msg.obj;
1416                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1417                                System.identityHashCode(mHandler));
1418                    }
1419                    if (mContainerService == null) {
1420                        if (!mBound) {
1421                            // Something seriously wrong since we are not bound and we are not
1422                            // waiting for connection. Bail out.
1423                            Slog.e(TAG, "Cannot bind to media container service");
1424                            for (HandlerParams params : mPendingInstalls) {
1425                                // Indicate service bind error
1426                                params.serviceError();
1427                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1428                                        System.identityHashCode(params));
1429                                if (params.traceMethod != null) {
1430                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1431                                            params.traceMethod, params.traceCookie);
1432                                }
1433                                return;
1434                            }
1435                            mPendingInstalls.clear();
1436                        } else {
1437                            Slog.w(TAG, "Waiting to connect to media container service");
1438                        }
1439                    } else if (mPendingInstalls.size() > 0) {
1440                        HandlerParams params = mPendingInstalls.get(0);
1441                        if (params != null) {
1442                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1443                                    System.identityHashCode(params));
1444                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1445                            if (params.startCopy()) {
1446                                // We are done...  look for more work or to
1447                                // go idle.
1448                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1449                                        "Checking for more work or unbind...");
1450                                // Delete pending install
1451                                if (mPendingInstalls.size() > 0) {
1452                                    mPendingInstalls.remove(0);
1453                                }
1454                                if (mPendingInstalls.size() == 0) {
1455                                    if (mBound) {
1456                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1457                                                "Posting delayed MCS_UNBIND");
1458                                        removeMessages(MCS_UNBIND);
1459                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1460                                        // Unbind after a little delay, to avoid
1461                                        // continual thrashing.
1462                                        sendMessageDelayed(ubmsg, 10000);
1463                                    }
1464                                } else {
1465                                    // There are more pending requests in queue.
1466                                    // Just post MCS_BOUND message to trigger processing
1467                                    // of next pending install.
1468                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1469                                            "Posting MCS_BOUND for next work");
1470                                    mHandler.sendEmptyMessage(MCS_BOUND);
1471                                }
1472                            }
1473                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1474                        }
1475                    } else {
1476                        // Should never happen ideally.
1477                        Slog.w(TAG, "Empty queue");
1478                    }
1479                    break;
1480                }
1481                case MCS_RECONNECT: {
1482                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1483                    if (mPendingInstalls.size() > 0) {
1484                        if (mBound) {
1485                            disconnectService();
1486                        }
1487                        if (!connectToService()) {
1488                            Slog.e(TAG, "Failed to bind to media container service");
1489                            for (HandlerParams params : mPendingInstalls) {
1490                                // Indicate service bind error
1491                                params.serviceError();
1492                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1493                                        System.identityHashCode(params));
1494                            }
1495                            mPendingInstalls.clear();
1496                        }
1497                    }
1498                    break;
1499                }
1500                case MCS_UNBIND: {
1501                    // If there is no actual work left, then time to unbind.
1502                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1503
1504                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1505                        if (mBound) {
1506                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1507
1508                            disconnectService();
1509                        }
1510                    } else if (mPendingInstalls.size() > 0) {
1511                        // There are more pending requests in queue.
1512                        // Just post MCS_BOUND message to trigger processing
1513                        // of next pending install.
1514                        mHandler.sendEmptyMessage(MCS_BOUND);
1515                    }
1516
1517                    break;
1518                }
1519                case MCS_GIVE_UP: {
1520                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1521                    HandlerParams params = mPendingInstalls.remove(0);
1522                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1523                            System.identityHashCode(params));
1524                    break;
1525                }
1526                case SEND_PENDING_BROADCAST: {
1527                    String packages[];
1528                    ArrayList<String> components[];
1529                    int size = 0;
1530                    int uids[];
1531                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1532                    synchronized (mPackages) {
1533                        if (mPendingBroadcasts == null) {
1534                            return;
1535                        }
1536                        size = mPendingBroadcasts.size();
1537                        if (size <= 0) {
1538                            // Nothing to be done. Just return
1539                            return;
1540                        }
1541                        packages = new String[size];
1542                        components = new ArrayList[size];
1543                        uids = new int[size];
1544                        int i = 0;  // filling out the above arrays
1545
1546                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1547                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1548                            Iterator<Map.Entry<String, ArrayList<String>>> it
1549                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1550                                            .entrySet().iterator();
1551                            while (it.hasNext() && i < size) {
1552                                Map.Entry<String, ArrayList<String>> ent = it.next();
1553                                packages[i] = ent.getKey();
1554                                components[i] = ent.getValue();
1555                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1556                                uids[i] = (ps != null)
1557                                        ? UserHandle.getUid(packageUserId, ps.appId)
1558                                        : -1;
1559                                i++;
1560                            }
1561                        }
1562                        size = i;
1563                        mPendingBroadcasts.clear();
1564                    }
1565                    // Send broadcasts
1566                    for (int i = 0; i < size; i++) {
1567                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1568                    }
1569                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1570                    break;
1571                }
1572                case START_CLEANING_PACKAGE: {
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1574                    final String packageName = (String)msg.obj;
1575                    final int userId = msg.arg1;
1576                    final boolean andCode = msg.arg2 != 0;
1577                    synchronized (mPackages) {
1578                        if (userId == UserHandle.USER_ALL) {
1579                            int[] users = sUserManager.getUserIds();
1580                            for (int user : users) {
1581                                mSettings.addPackageToCleanLPw(
1582                                        new PackageCleanItem(user, packageName, andCode));
1583                            }
1584                        } else {
1585                            mSettings.addPackageToCleanLPw(
1586                                    new PackageCleanItem(userId, packageName, andCode));
1587                        }
1588                    }
1589                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1590                    startCleaningPackages();
1591                } break;
1592                case POST_INSTALL: {
1593                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1594
1595                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1596                    final boolean didRestore = (msg.arg2 != 0);
1597                    mRunningInstalls.delete(msg.arg1);
1598
1599                    if (data != null) {
1600                        InstallArgs args = data.args;
1601                        PackageInstalledInfo parentRes = data.res;
1602
1603                        final boolean grantPermissions = (args.installFlags
1604                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1605                        final boolean killApp = (args.installFlags
1606                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1607                        final String[] grantedPermissions = args.installGrantPermissions;
1608
1609                        // Handle the parent package
1610                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1611                                grantedPermissions, didRestore, args.installerPackageName,
1612                                args.observer);
1613
1614                        // Handle the child packages
1615                        final int childCount = (parentRes.addedChildPackages != null)
1616                                ? parentRes.addedChildPackages.size() : 0;
1617                        for (int i = 0; i < childCount; i++) {
1618                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1619                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1620                                    grantedPermissions, false, args.installerPackageName,
1621                                    args.observer);
1622                        }
1623
1624                        // Log tracing if needed
1625                        if (args.traceMethod != null) {
1626                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1627                                    args.traceCookie);
1628                        }
1629                    } else {
1630                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1631                    }
1632
1633                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1634                } break;
1635                case UPDATED_MEDIA_STATUS: {
1636                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1637                    boolean reportStatus = msg.arg1 == 1;
1638                    boolean doGc = msg.arg2 == 1;
1639                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1640                    if (doGc) {
1641                        // Force a gc to clear up stale containers.
1642                        Runtime.getRuntime().gc();
1643                    }
1644                    if (msg.obj != null) {
1645                        @SuppressWarnings("unchecked")
1646                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1647                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1648                        // Unload containers
1649                        unloadAllContainers(args);
1650                    }
1651                    if (reportStatus) {
1652                        try {
1653                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1654                            PackageHelper.getMountService().finishMediaUpdate();
1655                        } catch (RemoteException e) {
1656                            Log.e(TAG, "MountService not running?");
1657                        }
1658                    }
1659                } break;
1660                case WRITE_SETTINGS: {
1661                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1662                    synchronized (mPackages) {
1663                        removeMessages(WRITE_SETTINGS);
1664                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1665                        mSettings.writeLPr();
1666                        mDirtyUsers.clear();
1667                    }
1668                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1669                } break;
1670                case WRITE_PACKAGE_RESTRICTIONS: {
1671                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1672                    synchronized (mPackages) {
1673                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1674                        for (int userId : mDirtyUsers) {
1675                            mSettings.writePackageRestrictionsLPr(userId);
1676                        }
1677                        mDirtyUsers.clear();
1678                    }
1679                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1680                } break;
1681                case WRITE_PACKAGE_LIST: {
1682                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1683                    synchronized (mPackages) {
1684                        removeMessages(WRITE_PACKAGE_LIST);
1685                        mSettings.writePackageListLPr(msg.arg1);
1686                    }
1687                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1688                } break;
1689                case CHECK_PENDING_VERIFICATION: {
1690                    final int verificationId = msg.arg1;
1691                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1692
1693                    if ((state != null) && !state.timeoutExtended()) {
1694                        final InstallArgs args = state.getInstallArgs();
1695                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1696
1697                        Slog.i(TAG, "Verification timed out for " + originUri);
1698                        mPendingVerification.remove(verificationId);
1699
1700                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1701
1702                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1703                            Slog.i(TAG, "Continuing with installation of " + originUri);
1704                            state.setVerifierResponse(Binder.getCallingUid(),
1705                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1706                            broadcastPackageVerified(verificationId, originUri,
1707                                    PackageManager.VERIFICATION_ALLOW,
1708                                    state.getInstallArgs().getUser());
1709                            try {
1710                                ret = args.copyApk(mContainerService, true);
1711                            } catch (RemoteException e) {
1712                                Slog.e(TAG, "Could not contact the ContainerService");
1713                            }
1714                        } else {
1715                            broadcastPackageVerified(verificationId, originUri,
1716                                    PackageManager.VERIFICATION_REJECT,
1717                                    state.getInstallArgs().getUser());
1718                        }
1719
1720                        Trace.asyncTraceEnd(
1721                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1722
1723                        processPendingInstall(args, ret);
1724                        mHandler.sendEmptyMessage(MCS_UNBIND);
1725                    }
1726                    break;
1727                }
1728                case PACKAGE_VERIFIED: {
1729                    final int verificationId = msg.arg1;
1730
1731                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1732                    if (state == null) {
1733                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1734                        break;
1735                    }
1736
1737                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1738
1739                    state.setVerifierResponse(response.callerUid, response.code);
1740
1741                    if (state.isVerificationComplete()) {
1742                        mPendingVerification.remove(verificationId);
1743
1744                        final InstallArgs args = state.getInstallArgs();
1745                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1746
1747                        int ret;
1748                        if (state.isInstallAllowed()) {
1749                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1750                            broadcastPackageVerified(verificationId, originUri,
1751                                    response.code, state.getInstallArgs().getUser());
1752                            try {
1753                                ret = args.copyApk(mContainerService, true);
1754                            } catch (RemoteException e) {
1755                                Slog.e(TAG, "Could not contact the ContainerService");
1756                            }
1757                        } else {
1758                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1759                        }
1760
1761                        Trace.asyncTraceEnd(
1762                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1763
1764                        processPendingInstall(args, ret);
1765                        mHandler.sendEmptyMessage(MCS_UNBIND);
1766                    }
1767
1768                    break;
1769                }
1770                case START_INTENT_FILTER_VERIFICATIONS: {
1771                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1772                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1773                            params.replacing, params.pkg);
1774                    break;
1775                }
1776                case INTENT_FILTER_VERIFIED: {
1777                    final int verificationId = msg.arg1;
1778
1779                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1780                            verificationId);
1781                    if (state == null) {
1782                        Slog.w(TAG, "Invalid IntentFilter verification token "
1783                                + verificationId + " received");
1784                        break;
1785                    }
1786
1787                    final int userId = state.getUserId();
1788
1789                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1790                            "Processing IntentFilter verification with token:"
1791                            + verificationId + " and userId:" + userId);
1792
1793                    final IntentFilterVerificationResponse response =
1794                            (IntentFilterVerificationResponse) msg.obj;
1795
1796                    state.setVerifierResponse(response.callerUid, response.code);
1797
1798                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1799                            "IntentFilter verification with token:" + verificationId
1800                            + " and userId:" + userId
1801                            + " is settings verifier response with response code:"
1802                            + response.code);
1803
1804                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1805                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1806                                + response.getFailedDomainsString());
1807                    }
1808
1809                    if (state.isVerificationComplete()) {
1810                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1811                    } else {
1812                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1813                                "IntentFilter verification with token:" + verificationId
1814                                + " was not said to be complete");
1815                    }
1816
1817                    break;
1818                }
1819            }
1820        }
1821    }
1822
1823    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1824            boolean killApp, String[] grantedPermissions,
1825            boolean launchedForRestore, String installerPackage,
1826            IPackageInstallObserver2 installObserver) {
1827        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1828            // Send the removed broadcasts
1829            if (res.removedInfo != null) {
1830                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1831            }
1832
1833            // Now that we successfully installed the package, grant runtime
1834            // permissions if requested before broadcasting the install.
1835            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1836                    >= Build.VERSION_CODES.M) {
1837                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1838            }
1839
1840            final boolean update = res.removedInfo != null
1841                    && res.removedInfo.removedPackage != null;
1842
1843            // If this is the first time we have child packages for a disabled privileged
1844            // app that had no children, we grant requested runtime permissions to the new
1845            // children if the parent on the system image had them already granted.
1846            if (res.pkg.parentPackage != null) {
1847                synchronized (mPackages) {
1848                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1849                }
1850            }
1851
1852            synchronized (mPackages) {
1853                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1854            }
1855
1856            final String packageName = res.pkg.applicationInfo.packageName;
1857            Bundle extras = new Bundle(1);
1858            extras.putInt(Intent.EXTRA_UID, res.uid);
1859
1860            // Determine the set of users who are adding this package for
1861            // the first time vs. those who are seeing an update.
1862            int[] firstUsers = EMPTY_INT_ARRAY;
1863            int[] updateUsers = EMPTY_INT_ARRAY;
1864            if (res.origUsers == null || res.origUsers.length == 0) {
1865                firstUsers = res.newUsers;
1866            } else {
1867                for (int newUser : res.newUsers) {
1868                    boolean isNew = true;
1869                    for (int origUser : res.origUsers) {
1870                        if (origUser == newUser) {
1871                            isNew = false;
1872                            break;
1873                        }
1874                    }
1875                    if (isNew) {
1876                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1877                    } else {
1878                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1879                    }
1880                }
1881            }
1882
1883            // Send installed broadcasts if the install/update is not ephemeral
1884            if (!isEphemeral(res.pkg)) {
1885                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1886
1887                // Send added for users that see the package for the first time
1888                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1889                        extras, 0 /*flags*/, null /*targetPackage*/,
1890                        null /*finishedReceiver*/, firstUsers);
1891
1892                // Send added for users that don't see the package for the first time
1893                if (update) {
1894                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1895                }
1896                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1897                        extras, 0 /*flags*/, null /*targetPackage*/,
1898                        null /*finishedReceiver*/, updateUsers);
1899
1900                // Send replaced for users that don't see the package for the first time
1901                if (update) {
1902                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1903                            packageName, extras, 0 /*flags*/,
1904                            null /*targetPackage*/, null /*finishedReceiver*/,
1905                            updateUsers);
1906                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1907                            null /*package*/, null /*extras*/, 0 /*flags*/,
1908                            packageName /*targetPackage*/,
1909                            null /*finishedReceiver*/, updateUsers);
1910                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1911                    // First-install and we did a restore, so we're responsible for the
1912                    // first-launch broadcast.
1913                    if (DEBUG_BACKUP) {
1914                        Slog.i(TAG, "Post-restore of " + packageName
1915                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1916                    }
1917                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1918                }
1919
1920                // Send broadcast package appeared if forward locked/external for all users
1921                // treat asec-hosted packages like removable media on upgrade
1922                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1923                    if (DEBUG_INSTALL) {
1924                        Slog.i(TAG, "upgrading pkg " + res.pkg
1925                                + " is ASEC-hosted -> AVAILABLE");
1926                    }
1927                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1928                    ArrayList<String> pkgList = new ArrayList<>(1);
1929                    pkgList.add(packageName);
1930                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1931                }
1932            }
1933
1934            // Work that needs to happen on first install within each user
1935            if (firstUsers != null && firstUsers.length > 0) {
1936                synchronized (mPackages) {
1937                    for (int userId : firstUsers) {
1938                        // If this app is a browser and it's newly-installed for some
1939                        // users, clear any default-browser state in those users. The
1940                        // app's nature doesn't depend on the user, so we can just check
1941                        // its browser nature in any user and generalize.
1942                        if (packageIsBrowser(packageName, userId)) {
1943                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1944                        }
1945
1946                        // We may also need to apply pending (restored) runtime
1947                        // permission grants within these users.
1948                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1949                    }
1950                }
1951            }
1952
1953            // Log current value of "unknown sources" setting
1954            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1955                    getUnknownSourcesSettings());
1956
1957            // Force a gc to clear up things
1958            Runtime.getRuntime().gc();
1959
1960            // Remove the replaced package's older resources safely now
1961            // We delete after a gc for applications  on sdcard.
1962            if (res.removedInfo != null && res.removedInfo.args != null) {
1963                synchronized (mInstallLock) {
1964                    res.removedInfo.args.doPostDeleteLI(true);
1965                }
1966            }
1967        }
1968
1969        // If someone is watching installs - notify them
1970        if (installObserver != null) {
1971            try {
1972                Bundle extras = extrasForInstallResult(res);
1973                installObserver.onPackageInstalled(res.name, res.returnCode,
1974                        res.returnMsg, extras);
1975            } catch (RemoteException e) {
1976                Slog.i(TAG, "Observer no longer exists.");
1977            }
1978        }
1979    }
1980
1981    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1982            PackageParser.Package pkg) {
1983        if (pkg.parentPackage == null) {
1984            return;
1985        }
1986        if (pkg.requestedPermissions == null) {
1987            return;
1988        }
1989        final PackageSetting disabledSysParentPs = mSettings
1990                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1991        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1992                || !disabledSysParentPs.isPrivileged()
1993                || (disabledSysParentPs.childPackageNames != null
1994                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1995            return;
1996        }
1997        final int[] allUserIds = sUserManager.getUserIds();
1998        final int permCount = pkg.requestedPermissions.size();
1999        for (int i = 0; i < permCount; i++) {
2000            String permission = pkg.requestedPermissions.get(i);
2001            BasePermission bp = mSettings.mPermissions.get(permission);
2002            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2003                continue;
2004            }
2005            for (int userId : allUserIds) {
2006                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2007                        permission, userId)) {
2008                    grantRuntimePermission(pkg.packageName, permission, userId);
2009                }
2010            }
2011        }
2012    }
2013
2014    private StorageEventListener mStorageListener = new StorageEventListener() {
2015        @Override
2016        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2017            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2018                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2019                    final String volumeUuid = vol.getFsUuid();
2020
2021                    // Clean up any users or apps that were removed or recreated
2022                    // while this volume was missing
2023                    reconcileUsers(volumeUuid);
2024                    reconcileApps(volumeUuid);
2025
2026                    // Clean up any install sessions that expired or were
2027                    // cancelled while this volume was missing
2028                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2029
2030                    loadPrivatePackages(vol);
2031
2032                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2033                    unloadPrivatePackages(vol);
2034                }
2035            }
2036
2037            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2038                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2039                    updateExternalMediaStatus(true, false);
2040                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2041                    updateExternalMediaStatus(false, false);
2042                }
2043            }
2044        }
2045
2046        @Override
2047        public void onVolumeForgotten(String fsUuid) {
2048            if (TextUtils.isEmpty(fsUuid)) {
2049                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2050                return;
2051            }
2052
2053            // Remove any apps installed on the forgotten volume
2054            synchronized (mPackages) {
2055                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2056                for (PackageSetting ps : packages) {
2057                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2058                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2059                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2060                }
2061
2062                mSettings.onVolumeForgotten(fsUuid);
2063                mSettings.writeLPr();
2064            }
2065        }
2066    };
2067
2068    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2069            String[] grantedPermissions) {
2070        for (int userId : userIds) {
2071            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2072        }
2073
2074        // We could have touched GID membership, so flush out packages.list
2075        synchronized (mPackages) {
2076            mSettings.writePackageListLPr();
2077        }
2078    }
2079
2080    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2081            String[] grantedPermissions) {
2082        SettingBase sb = (SettingBase) pkg.mExtras;
2083        if (sb == null) {
2084            return;
2085        }
2086
2087        PermissionsState permissionsState = sb.getPermissionsState();
2088
2089        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2090                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2091
2092        for (String permission : pkg.requestedPermissions) {
2093            final BasePermission bp;
2094            synchronized (mPackages) {
2095                bp = mSettings.mPermissions.get(permission);
2096            }
2097            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2098                    && (grantedPermissions == null
2099                           || ArrayUtils.contains(grantedPermissions, permission))) {
2100                final int flags = permissionsState.getPermissionFlags(permission, userId);
2101                // Installer cannot change immutable permissions.
2102                if ((flags & immutableFlags) == 0) {
2103                    grantRuntimePermission(pkg.packageName, permission, userId);
2104                }
2105            }
2106        }
2107    }
2108
2109    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2110        Bundle extras = null;
2111        switch (res.returnCode) {
2112            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2113                extras = new Bundle();
2114                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2115                        res.origPermission);
2116                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2117                        res.origPackage);
2118                break;
2119            }
2120            case PackageManager.INSTALL_SUCCEEDED: {
2121                extras = new Bundle();
2122                extras.putBoolean(Intent.EXTRA_REPLACING,
2123                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2124                break;
2125            }
2126        }
2127        return extras;
2128    }
2129
2130    void scheduleWriteSettingsLocked() {
2131        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2132            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2133        }
2134    }
2135
2136    void scheduleWritePackageListLocked(int userId) {
2137        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2138            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2139            msg.arg1 = userId;
2140            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2141        }
2142    }
2143
2144    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2145        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2146        scheduleWritePackageRestrictionsLocked(userId);
2147    }
2148
2149    void scheduleWritePackageRestrictionsLocked(int userId) {
2150        final int[] userIds = (userId == UserHandle.USER_ALL)
2151                ? sUserManager.getUserIds() : new int[]{userId};
2152        for (int nextUserId : userIds) {
2153            if (!sUserManager.exists(nextUserId)) return;
2154            mDirtyUsers.add(nextUserId);
2155            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2156                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2157            }
2158        }
2159    }
2160
2161    public static PackageManagerService main(Context context, Installer installer,
2162            boolean factoryTest, boolean onlyCore) {
2163        // Self-check for initial settings.
2164        PackageManagerServiceCompilerMapping.checkProperties();
2165
2166        PackageManagerService m = new PackageManagerService(context, installer,
2167                factoryTest, onlyCore);
2168        m.enableSystemUserPackages();
2169        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2170        // disabled after already being started.
2171        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2172                UserHandle.USER_SYSTEM);
2173        ServiceManager.addService("package", m);
2174        return m;
2175    }
2176
2177    private void enableSystemUserPackages() {
2178        if (!UserManager.isSplitSystemUser()) {
2179            return;
2180        }
2181        // For system user, enable apps based on the following conditions:
2182        // - app is whitelisted or belong to one of these groups:
2183        //   -- system app which has no launcher icons
2184        //   -- system app which has INTERACT_ACROSS_USERS permission
2185        //   -- system IME app
2186        // - app is not in the blacklist
2187        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2188        Set<String> enableApps = new ArraySet<>();
2189        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2190                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2191                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2192        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2193        enableApps.addAll(wlApps);
2194        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2195                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2196        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2197        enableApps.removeAll(blApps);
2198        Log.i(TAG, "Applications installed for system user: " + enableApps);
2199        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2200                UserHandle.SYSTEM);
2201        final int allAppsSize = allAps.size();
2202        synchronized (mPackages) {
2203            for (int i = 0; i < allAppsSize; i++) {
2204                String pName = allAps.get(i);
2205                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2206                // Should not happen, but we shouldn't be failing if it does
2207                if (pkgSetting == null) {
2208                    continue;
2209                }
2210                boolean install = enableApps.contains(pName);
2211                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2212                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2213                            + " for system user");
2214                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2215                }
2216            }
2217        }
2218    }
2219
2220    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2221        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2222                Context.DISPLAY_SERVICE);
2223        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2224    }
2225
2226    /**
2227     * Requests that files preopted on a secondary system partition be copied to the data partition
2228     * if possible.  Note that the actual copying of the files is accomplished by init for security
2229     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2230     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2231     */
2232    private static void requestCopyPreoptedFiles() {
2233        final int WAIT_TIME_MS = 100;
2234        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2235        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2236            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2237            // We will wait for up to 100 seconds.
2238            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2239            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2240                try {
2241                    Thread.sleep(WAIT_TIME_MS);
2242                } catch (InterruptedException e) {
2243                    // Do nothing
2244                }
2245                if (SystemClock.uptimeMillis() > timeEnd) {
2246                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2247                    Slog.wtf(TAG, "cppreopt did not finish!");
2248                    break;
2249                }
2250            }
2251        }
2252    }
2253
2254    public PackageManagerService(Context context, Installer installer,
2255            boolean factoryTest, boolean onlyCore) {
2256        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2257                SystemClock.uptimeMillis());
2258
2259        if (mSdkVersion <= 0) {
2260            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2261        }
2262
2263        mContext = context;
2264        mFactoryTest = factoryTest;
2265        mOnlyCore = onlyCore;
2266        mMetrics = new DisplayMetrics();
2267        mSettings = new Settings(mPackages);
2268        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2269                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2270        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2271                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2272        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2273                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2274        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2275                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2276        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2277                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2278        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2279                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2280
2281        String separateProcesses = SystemProperties.get("debug.separate_processes");
2282        if (separateProcesses != null && separateProcesses.length() > 0) {
2283            if ("*".equals(separateProcesses)) {
2284                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2285                mSeparateProcesses = null;
2286                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2287            } else {
2288                mDefParseFlags = 0;
2289                mSeparateProcesses = separateProcesses.split(",");
2290                Slog.w(TAG, "Running with debug.separate_processes: "
2291                        + separateProcesses);
2292            }
2293        } else {
2294            mDefParseFlags = 0;
2295            mSeparateProcesses = null;
2296        }
2297
2298        mInstaller = installer;
2299        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2300                "*dexopt*");
2301        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2302
2303        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2304                FgThread.get().getLooper());
2305
2306        getDefaultDisplayMetrics(context, mMetrics);
2307
2308        SystemConfig systemConfig = SystemConfig.getInstance();
2309        mGlobalGids = systemConfig.getGlobalGids();
2310        mSystemPermissions = systemConfig.getSystemPermissions();
2311        mAvailableFeatures = systemConfig.getAvailableFeatures();
2312
2313        mProtectedPackages = new ProtectedPackages(mContext);
2314
2315        synchronized (mInstallLock) {
2316        // writer
2317        synchronized (mPackages) {
2318            mHandlerThread = new ServiceThread(TAG,
2319                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2320            mHandlerThread.start();
2321            mHandler = new PackageHandler(mHandlerThread.getLooper());
2322            mProcessLoggingHandler = new ProcessLoggingHandler();
2323            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2324
2325            File dataDir = Environment.getDataDirectory();
2326            mAppInstallDir = new File(dataDir, "app");
2327            mAppLib32InstallDir = new File(dataDir, "app-lib");
2328            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2329            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2330            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2331
2332            sUserManager = new UserManagerService(context, this, mPackages);
2333
2334            // Propagate permission configuration in to package manager.
2335            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2336                    = systemConfig.getPermissions();
2337            for (int i=0; i<permConfig.size(); i++) {
2338                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2339                BasePermission bp = mSettings.mPermissions.get(perm.name);
2340                if (bp == null) {
2341                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2342                    mSettings.mPermissions.put(perm.name, bp);
2343                }
2344                if (perm.gids != null) {
2345                    bp.setGids(perm.gids, perm.perUser);
2346                }
2347            }
2348
2349            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2350            for (int i=0; i<libConfig.size(); i++) {
2351                mSharedLibraries.put(libConfig.keyAt(i),
2352                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2353            }
2354
2355            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2356
2357            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2358
2359            if (mFirstBoot) {
2360                requestCopyPreoptedFiles();
2361            }
2362
2363            String customResolverActivity = Resources.getSystem().getString(
2364                    R.string.config_customResolverActivity);
2365            if (TextUtils.isEmpty(customResolverActivity)) {
2366                customResolverActivity = null;
2367            } else {
2368                mCustomResolverComponentName = ComponentName.unflattenFromString(
2369                        customResolverActivity);
2370            }
2371
2372            long startTime = SystemClock.uptimeMillis();
2373
2374            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2375                    startTime);
2376
2377            // Set flag to monitor and not change apk file paths when
2378            // scanning install directories.
2379            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2380
2381            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2382            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2383
2384            if (bootClassPath == null) {
2385                Slog.w(TAG, "No BOOTCLASSPATH found!");
2386            }
2387
2388            if (systemServerClassPath == null) {
2389                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2390            }
2391
2392            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2393            final String[] dexCodeInstructionSets =
2394                    getDexCodeInstructionSets(
2395                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2396
2397            /**
2398             * Ensure all external libraries have had dexopt run on them.
2399             */
2400            if (mSharedLibraries.size() > 0) {
2401                // NOTE: For now, we're compiling these system "shared libraries"
2402                // (and framework jars) into all available architectures. It's possible
2403                // to compile them only when we come across an app that uses them (there's
2404                // already logic for that in scanPackageLI) but that adds some complexity.
2405                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2406                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2407                        final String lib = libEntry.path;
2408                        if (lib == null) {
2409                            continue;
2410                        }
2411
2412                        try {
2413                            // Shared libraries do not have profiles so we perform a full
2414                            // AOT compilation (if needed).
2415                            int dexoptNeeded = DexFile.getDexOptNeeded(
2416                                    lib, dexCodeInstructionSet,
2417                                    getCompilerFilterForReason(REASON_SHARED_APK),
2418                                    false /* newProfile */);
2419                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2420                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2421                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2422                                        getCompilerFilterForReason(REASON_SHARED_APK),
2423                                        StorageManager.UUID_PRIVATE_INTERNAL,
2424                                        SKIP_SHARED_LIBRARY_CHECK);
2425                            }
2426                        } catch (FileNotFoundException e) {
2427                            Slog.w(TAG, "Library not found: " + lib);
2428                        } catch (IOException | InstallerException e) {
2429                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2430                                    + e.getMessage());
2431                        }
2432                    }
2433                }
2434            }
2435
2436            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2437
2438            final VersionInfo ver = mSettings.getInternalVersion();
2439            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2440
2441            // when upgrading from pre-M, promote system app permissions from install to runtime
2442            mPromoteSystemApps =
2443                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2444
2445            // When upgrading from pre-N, we need to handle package extraction like first boot,
2446            // as there is no profiling data available.
2447            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2448
2449            // save off the names of pre-existing system packages prior to scanning; we don't
2450            // want to automatically grant runtime permissions for new system apps
2451            if (mPromoteSystemApps) {
2452                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2453                while (pkgSettingIter.hasNext()) {
2454                    PackageSetting ps = pkgSettingIter.next();
2455                    if (isSystemApp(ps)) {
2456                        mExistingSystemPackages.add(ps.name);
2457                    }
2458                }
2459            }
2460
2461            // Collect vendor overlay packages.
2462            // (Do this before scanning any apps.)
2463            // For security and version matching reason, only consider
2464            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2465            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2466            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2467                    | PackageParser.PARSE_IS_SYSTEM
2468                    | PackageParser.PARSE_IS_SYSTEM_DIR
2469                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2470
2471            // Find base frameworks (resource packages without code).
2472            scanDirTracedLI(frameworkDir, mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR
2475                    | PackageParser.PARSE_IS_PRIVILEGED,
2476                    scanFlags | SCAN_NO_DEX, 0);
2477
2478            // Collected privileged system packages.
2479            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2480            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2481                    | PackageParser.PARSE_IS_SYSTEM
2482                    | PackageParser.PARSE_IS_SYSTEM_DIR
2483                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2484
2485            // Collect ordinary system packages.
2486            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2487            scanDirTracedLI(systemAppDir, mDefParseFlags
2488                    | PackageParser.PARSE_IS_SYSTEM
2489                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2490
2491            // Collect all vendor packages.
2492            File vendorAppDir = new File("/vendor/app");
2493            try {
2494                vendorAppDir = vendorAppDir.getCanonicalFile();
2495            } catch (IOException e) {
2496                // failed to look up canonical path, continue with original one
2497            }
2498            scanDirTracedLI(vendorAppDir, mDefParseFlags
2499                    | PackageParser.PARSE_IS_SYSTEM
2500                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2501
2502            // Collect all OEM packages.
2503            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2504            scanDirTracedLI(oemAppDir, mDefParseFlags
2505                    | PackageParser.PARSE_IS_SYSTEM
2506                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2507
2508            // Prune any system packages that no longer exist.
2509            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2510            if (!mOnlyCore) {
2511                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2512                while (psit.hasNext()) {
2513                    PackageSetting ps = psit.next();
2514
2515                    /*
2516                     * If this is not a system app, it can't be a
2517                     * disable system app.
2518                     */
2519                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2520                        continue;
2521                    }
2522
2523                    /*
2524                     * If the package is scanned, it's not erased.
2525                     */
2526                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2527                    if (scannedPkg != null) {
2528                        /*
2529                         * If the system app is both scanned and in the
2530                         * disabled packages list, then it must have been
2531                         * added via OTA. Remove it from the currently
2532                         * scanned package so the previously user-installed
2533                         * application can be scanned.
2534                         */
2535                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2536                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2537                                    + ps.name + "; removing system app.  Last known codePath="
2538                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2539                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2540                                    + scannedPkg.mVersionCode);
2541                            removePackageLI(scannedPkg, true);
2542                            mExpectingBetter.put(ps.name, ps.codePath);
2543                        }
2544
2545                        continue;
2546                    }
2547
2548                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2549                        psit.remove();
2550                        logCriticalInfo(Log.WARN, "System package " + ps.name
2551                                + " no longer exists; it's data will be wiped");
2552                        // Actual deletion of code and data will be handled by later
2553                        // reconciliation step
2554                    } else {
2555                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2556                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2557                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2558                        }
2559                    }
2560                }
2561            }
2562
2563            //look for any incomplete package installations
2564            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2565            for (int i = 0; i < deletePkgsList.size(); i++) {
2566                // Actual deletion of code and data will be handled by later
2567                // reconciliation step
2568                final String packageName = deletePkgsList.get(i).name;
2569                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2570                synchronized (mPackages) {
2571                    mSettings.removePackageLPw(packageName);
2572                }
2573            }
2574
2575            //delete tmp files
2576            deleteTempPackageFiles();
2577
2578            // Remove any shared userIDs that have no associated packages
2579            mSettings.pruneSharedUsersLPw();
2580
2581            if (!mOnlyCore) {
2582                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2583                        SystemClock.uptimeMillis());
2584                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2585
2586                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2587                        | PackageParser.PARSE_FORWARD_LOCK,
2588                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2589
2590                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2591                        | PackageParser.PARSE_IS_EPHEMERAL,
2592                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2593
2594                /**
2595                 * Remove disable package settings for any updated system
2596                 * apps that were removed via an OTA. If they're not a
2597                 * previously-updated app, remove them completely.
2598                 * Otherwise, just revoke their system-level permissions.
2599                 */
2600                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2601                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2602                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2603
2604                    String msg;
2605                    if (deletedPkg == null) {
2606                        msg = "Updated system package " + deletedAppName
2607                                + " no longer exists; it's data will be wiped";
2608                        // Actual deletion of code and data will be handled by later
2609                        // reconciliation step
2610                    } else {
2611                        msg = "Updated system app + " + deletedAppName
2612                                + " no longer present; removing system privileges for "
2613                                + deletedAppName;
2614
2615                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2616
2617                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2618                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2619                    }
2620                    logCriticalInfo(Log.WARN, msg);
2621                }
2622
2623                /**
2624                 * Make sure all system apps that we expected to appear on
2625                 * the userdata partition actually showed up. If they never
2626                 * appeared, crawl back and revive the system version.
2627                 */
2628                for (int i = 0; i < mExpectingBetter.size(); i++) {
2629                    final String packageName = mExpectingBetter.keyAt(i);
2630                    if (!mPackages.containsKey(packageName)) {
2631                        final File scanFile = mExpectingBetter.valueAt(i);
2632
2633                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2634                                + " but never showed up; reverting to system");
2635
2636                        int reparseFlags = mDefParseFlags;
2637                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2638                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2639                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2640                                    | PackageParser.PARSE_IS_PRIVILEGED;
2641                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2642                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2643                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2644                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2645                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2646                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2647                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2648                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2649                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2650                        } else {
2651                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2652                            continue;
2653                        }
2654
2655                        mSettings.enableSystemPackageLPw(packageName);
2656
2657                        try {
2658                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2659                        } catch (PackageManagerException e) {
2660                            Slog.e(TAG, "Failed to parse original system package: "
2661                                    + e.getMessage());
2662                        }
2663                    }
2664                }
2665            }
2666            mExpectingBetter.clear();
2667
2668            // Resolve protected action filters. Only the setup wizard is allowed to
2669            // have a high priority filter for these actions.
2670            mSetupWizardPackage = getSetupWizardPackageName();
2671            if (mProtectedFilters.size() > 0) {
2672                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2673                    Slog.i(TAG, "No setup wizard;"
2674                        + " All protected intents capped to priority 0");
2675                }
2676                for (ActivityIntentInfo filter : mProtectedFilters) {
2677                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2678                        if (DEBUG_FILTERS) {
2679                            Slog.i(TAG, "Found setup wizard;"
2680                                + " allow priority " + filter.getPriority() + ";"
2681                                + " package: " + filter.activity.info.packageName
2682                                + " activity: " + filter.activity.className
2683                                + " priority: " + filter.getPriority());
2684                        }
2685                        // skip setup wizard; allow it to keep the high priority filter
2686                        continue;
2687                    }
2688                    Slog.w(TAG, "Protected action; cap priority to 0;"
2689                            + " package: " + filter.activity.info.packageName
2690                            + " activity: " + filter.activity.className
2691                            + " origPrio: " + filter.getPriority());
2692                    filter.setPriority(0);
2693                }
2694            }
2695            mDeferProtectedFilters = false;
2696            mProtectedFilters.clear();
2697
2698            // Now that we know all of the shared libraries, update all clients to have
2699            // the correct library paths.
2700            updateAllSharedLibrariesLPw();
2701
2702            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2703                // NOTE: We ignore potential failures here during a system scan (like
2704                // the rest of the commands above) because there's precious little we
2705                // can do about it. A settings error is reported, though.
2706                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2707                        false /* boot complete */);
2708            }
2709
2710            // Now that we know all the packages we are keeping,
2711            // read and update their last usage times.
2712            mPackageUsage.readLP();
2713
2714            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2715                    SystemClock.uptimeMillis());
2716            Slog.i(TAG, "Time to scan packages: "
2717                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2718                    + " seconds");
2719
2720            // If the platform SDK has changed since the last time we booted,
2721            // we need to re-grant app permission to catch any new ones that
2722            // appear.  This is really a hack, and means that apps can in some
2723            // cases get permissions that the user didn't initially explicitly
2724            // allow...  it would be nice to have some better way to handle
2725            // this situation.
2726            int updateFlags = UPDATE_PERMISSIONS_ALL;
2727            if (ver.sdkVersion != mSdkVersion) {
2728                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2729                        + mSdkVersion + "; regranting permissions for internal storage");
2730                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2731            }
2732            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2733            ver.sdkVersion = mSdkVersion;
2734
2735            // If this is the first boot or an update from pre-M, and it is a normal
2736            // boot, then we need to initialize the default preferred apps across
2737            // all defined users.
2738            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2739                for (UserInfo user : sUserManager.getUsers(true)) {
2740                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2741                    applyFactoryDefaultBrowserLPw(user.id);
2742                    primeDomainVerificationsLPw(user.id);
2743                }
2744            }
2745
2746            // Prepare storage for system user really early during boot,
2747            // since core system apps like SettingsProvider and SystemUI
2748            // can't wait for user to start
2749            final int storageFlags;
2750            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2751                storageFlags = StorageManager.FLAG_STORAGE_DE;
2752            } else {
2753                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2754            }
2755            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2756                    storageFlags);
2757
2758            // If this is first boot after an OTA, and a normal boot, then
2759            // we need to clear code cache directories.
2760            // Note that we do *not* clear the application profiles. These remain valid
2761            // across OTAs and are used to drive profile verification (post OTA) and
2762            // profile compilation (without waiting to collect a fresh set of profiles).
2763            if (mIsUpgrade && !onlyCore) {
2764                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2765                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2766                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2767                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2768                        // No apps are running this early, so no need to freeze
2769                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2770                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2771                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2772                    }
2773                }
2774                ver.fingerprint = Build.FINGERPRINT;
2775            }
2776
2777            checkDefaultBrowser();
2778
2779            // clear only after permissions and other defaults have been updated
2780            mExistingSystemPackages.clear();
2781            mPromoteSystemApps = false;
2782
2783            // All the changes are done during package scanning.
2784            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2785
2786            // can downgrade to reader
2787            mSettings.writeLPr();
2788
2789            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2790            // early on (before the package manager declares itself as early) because other
2791            // components in the system server might ask for package contexts for these apps.
2792            //
2793            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2794            // (i.e, that the data partition is unavailable).
2795            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2796                long start = System.nanoTime();
2797                List<PackageParser.Package> coreApps = new ArrayList<>();
2798                for (PackageParser.Package pkg : mPackages.values()) {
2799                    if (pkg.coreApp) {
2800                        coreApps.add(pkg);
2801                    }
2802                }
2803
2804                int[] stats = performDexOpt(coreApps, false,
2805                        getCompilerFilterForReason(REASON_CORE_APP));
2806
2807                final int elapsedTimeSeconds =
2808                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2809                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2810
2811                if (DEBUG_DEXOPT) {
2812                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2813                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2814                }
2815
2816
2817                // TODO: Should we log these stats to tron too ?
2818                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2819                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2820                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2821                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2822            }
2823
2824            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2825                    SystemClock.uptimeMillis());
2826
2827            if (!mOnlyCore) {
2828                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2829                mRequiredInstallerPackage = getRequiredInstallerLPr();
2830                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2831                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2832                        mIntentFilterVerifierComponent);
2833                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2834                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2835                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2836                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2837            } else {
2838                mRequiredVerifierPackage = null;
2839                mRequiredInstallerPackage = null;
2840                mIntentFilterVerifierComponent = null;
2841                mIntentFilterVerifier = null;
2842                mServicesSystemSharedLibraryPackageName = null;
2843                mSharedSystemSharedLibraryPackageName = null;
2844            }
2845
2846            mInstallerService = new PackageInstallerService(context, this);
2847
2848            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2849            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2850            // both the installer and resolver must be present to enable ephemeral
2851            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2852                if (DEBUG_EPHEMERAL) {
2853                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2854                            + " installer:" + ephemeralInstallerComponent);
2855                }
2856                mEphemeralResolverComponent = ephemeralResolverComponent;
2857                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2858                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2859                mEphemeralResolverConnection =
2860                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2861            } else {
2862                if (DEBUG_EPHEMERAL) {
2863                    final String missingComponent =
2864                            (ephemeralResolverComponent == null)
2865                            ? (ephemeralInstallerComponent == null)
2866                                    ? "resolver and installer"
2867                                    : "resolver"
2868                            : "installer";
2869                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2870                }
2871                mEphemeralResolverComponent = null;
2872                mEphemeralInstallerComponent = null;
2873                mEphemeralResolverConnection = null;
2874            }
2875
2876            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2877        } // synchronized (mPackages)
2878        } // synchronized (mInstallLock)
2879
2880        // Now after opening every single application zip, make sure they
2881        // are all flushed.  Not really needed, but keeps things nice and
2882        // tidy.
2883        Runtime.getRuntime().gc();
2884
2885        // The initial scanning above does many calls into installd while
2886        // holding the mPackages lock, but we're mostly interested in yelling
2887        // once we have a booted system.
2888        mInstaller.setWarnIfHeld(mPackages);
2889
2890        // Expose private service for system components to use.
2891        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2892    }
2893
2894    @Override
2895    public boolean isFirstBoot() {
2896        return mFirstBoot;
2897    }
2898
2899    @Override
2900    public boolean isOnlyCoreApps() {
2901        return mOnlyCore;
2902    }
2903
2904    @Override
2905    public boolean isUpgrade() {
2906        return mIsUpgrade;
2907    }
2908
2909    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2910        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2911
2912        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2913                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2914                UserHandle.USER_SYSTEM);
2915        if (matches.size() == 1) {
2916            return matches.get(0).getComponentInfo().packageName;
2917        } else {
2918            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2919            return null;
2920        }
2921    }
2922
2923    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2924        synchronized (mPackages) {
2925            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2926            if (libraryEntry == null) {
2927                throw new IllegalStateException("Missing required shared library:" + libraryName);
2928            }
2929            return libraryEntry.apk;
2930        }
2931    }
2932
2933    private @NonNull String getRequiredInstallerLPr() {
2934        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2935        intent.addCategory(Intent.CATEGORY_DEFAULT);
2936        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2937
2938        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2939                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2940                UserHandle.USER_SYSTEM);
2941        if (matches.size() == 1) {
2942            ResolveInfo resolveInfo = matches.get(0);
2943            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2944                throw new RuntimeException("The installer must be a privileged app");
2945            }
2946            return matches.get(0).getComponentInfo().packageName;
2947        } else {
2948            throw new RuntimeException("There must be exactly one installer; found " + matches);
2949        }
2950    }
2951
2952    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2953        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2954
2955        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2956                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2957                UserHandle.USER_SYSTEM);
2958        ResolveInfo best = null;
2959        final int N = matches.size();
2960        for (int i = 0; i < N; i++) {
2961            final ResolveInfo cur = matches.get(i);
2962            final String packageName = cur.getComponentInfo().packageName;
2963            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2964                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2965                continue;
2966            }
2967
2968            if (best == null || cur.priority > best.priority) {
2969                best = cur;
2970            }
2971        }
2972
2973        if (best != null) {
2974            return best.getComponentInfo().getComponentName();
2975        } else {
2976            throw new RuntimeException("There must be at least one intent filter verifier");
2977        }
2978    }
2979
2980    private @Nullable ComponentName getEphemeralResolverLPr() {
2981        final String[] packageArray =
2982                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2983        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2984            if (DEBUG_EPHEMERAL) {
2985                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2986            }
2987            return null;
2988        }
2989
2990        final int resolveFlags =
2991                MATCH_DIRECT_BOOT_AWARE
2992                | MATCH_DIRECT_BOOT_UNAWARE
2993                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2994        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2995        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2996                resolveFlags, UserHandle.USER_SYSTEM);
2997
2998        final int N = resolvers.size();
2999        if (N == 0) {
3000            if (DEBUG_EPHEMERAL) {
3001                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3002            }
3003            return null;
3004        }
3005
3006        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3007        for (int i = 0; i < N; i++) {
3008            final ResolveInfo info = resolvers.get(i);
3009
3010            if (info.serviceInfo == null) {
3011                continue;
3012            }
3013
3014            final String packageName = info.serviceInfo.packageName;
3015            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3016                if (DEBUG_EPHEMERAL) {
3017                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3018                            + " pkg: " + packageName + ", info:" + info);
3019                }
3020                continue;
3021            }
3022
3023            if (DEBUG_EPHEMERAL) {
3024                Slog.v(TAG, "Ephemeral resolver found;"
3025                        + " pkg: " + packageName + ", info:" + info);
3026            }
3027            return new ComponentName(packageName, info.serviceInfo.name);
3028        }
3029        if (DEBUG_EPHEMERAL) {
3030            Slog.v(TAG, "Ephemeral resolver NOT found");
3031        }
3032        return null;
3033    }
3034
3035    private @Nullable ComponentName getEphemeralInstallerLPr() {
3036        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3037        intent.addCategory(Intent.CATEGORY_DEFAULT);
3038        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3039
3040        final int resolveFlags =
3041                MATCH_DIRECT_BOOT_AWARE
3042                | MATCH_DIRECT_BOOT_UNAWARE
3043                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3044        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3045                resolveFlags, UserHandle.USER_SYSTEM);
3046        if (matches.size() == 0) {
3047            return null;
3048        } else if (matches.size() == 1) {
3049            return matches.get(0).getComponentInfo().getComponentName();
3050        } else {
3051            throw new RuntimeException(
3052                    "There must be at most one ephemeral installer; found " + matches);
3053        }
3054    }
3055
3056    private void primeDomainVerificationsLPw(int userId) {
3057        if (DEBUG_DOMAIN_VERIFICATION) {
3058            Slog.d(TAG, "Priming domain verifications in user " + userId);
3059        }
3060
3061        SystemConfig systemConfig = SystemConfig.getInstance();
3062        ArraySet<String> packages = systemConfig.getLinkedApps();
3063        ArraySet<String> domains = new ArraySet<String>();
3064
3065        for (String packageName : packages) {
3066            PackageParser.Package pkg = mPackages.get(packageName);
3067            if (pkg != null) {
3068                if (!pkg.isSystemApp()) {
3069                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3070                    continue;
3071                }
3072
3073                domains.clear();
3074                for (PackageParser.Activity a : pkg.activities) {
3075                    for (ActivityIntentInfo filter : a.intents) {
3076                        if (hasValidDomains(filter)) {
3077                            domains.addAll(filter.getHostsList());
3078                        }
3079                    }
3080                }
3081
3082                if (domains.size() > 0) {
3083                    if (DEBUG_DOMAIN_VERIFICATION) {
3084                        Slog.v(TAG, "      + " + packageName);
3085                    }
3086                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3087                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3088                    // and then 'always' in the per-user state actually used for intent resolution.
3089                    final IntentFilterVerificationInfo ivi;
3090                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3091                            new ArrayList<String>(domains));
3092                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3093                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3094                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3095                } else {
3096                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3097                            + "' does not handle web links");
3098                }
3099            } else {
3100                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3101            }
3102        }
3103
3104        scheduleWritePackageRestrictionsLocked(userId);
3105        scheduleWriteSettingsLocked();
3106    }
3107
3108    private void applyFactoryDefaultBrowserLPw(int userId) {
3109        // The default browser app's package name is stored in a string resource,
3110        // with a product-specific overlay used for vendor customization.
3111        String browserPkg = mContext.getResources().getString(
3112                com.android.internal.R.string.default_browser);
3113        if (!TextUtils.isEmpty(browserPkg)) {
3114            // non-empty string => required to be a known package
3115            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3116            if (ps == null) {
3117                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3118                browserPkg = null;
3119            } else {
3120                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3121            }
3122        }
3123
3124        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3125        // default.  If there's more than one, just leave everything alone.
3126        if (browserPkg == null) {
3127            calculateDefaultBrowserLPw(userId);
3128        }
3129    }
3130
3131    private void calculateDefaultBrowserLPw(int userId) {
3132        List<String> allBrowsers = resolveAllBrowserApps(userId);
3133        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3134        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3135    }
3136
3137    private List<String> resolveAllBrowserApps(int userId) {
3138        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3139        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3140                PackageManager.MATCH_ALL, userId);
3141
3142        final int count = list.size();
3143        List<String> result = new ArrayList<String>(count);
3144        for (int i=0; i<count; i++) {
3145            ResolveInfo info = list.get(i);
3146            if (info.activityInfo == null
3147                    || !info.handleAllWebDataURI
3148                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3149                    || result.contains(info.activityInfo.packageName)) {
3150                continue;
3151            }
3152            result.add(info.activityInfo.packageName);
3153        }
3154
3155        return result;
3156    }
3157
3158    private boolean packageIsBrowser(String packageName, int userId) {
3159        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3160                PackageManager.MATCH_ALL, userId);
3161        final int N = list.size();
3162        for (int i = 0; i < N; i++) {
3163            ResolveInfo info = list.get(i);
3164            if (packageName.equals(info.activityInfo.packageName)) {
3165                return true;
3166            }
3167        }
3168        return false;
3169    }
3170
3171    private void checkDefaultBrowser() {
3172        final int myUserId = UserHandle.myUserId();
3173        final String packageName = getDefaultBrowserPackageName(myUserId);
3174        if (packageName != null) {
3175            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3176            if (info == null) {
3177                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3178                synchronized (mPackages) {
3179                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3180                }
3181            }
3182        }
3183    }
3184
3185    @Override
3186    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3187            throws RemoteException {
3188        try {
3189            return super.onTransact(code, data, reply, flags);
3190        } catch (RuntimeException e) {
3191            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3192                Slog.wtf(TAG, "Package Manager Crash", e);
3193            }
3194            throw e;
3195        }
3196    }
3197
3198    static int[] appendInts(int[] cur, int[] add) {
3199        if (add == null) return cur;
3200        if (cur == null) return add;
3201        final int N = add.length;
3202        for (int i=0; i<N; i++) {
3203            cur = appendInt(cur, add[i]);
3204        }
3205        return cur;
3206    }
3207
3208    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3209        if (!sUserManager.exists(userId)) return null;
3210        if (ps == null) {
3211            return null;
3212        }
3213        final PackageParser.Package p = ps.pkg;
3214        if (p == null) {
3215            return null;
3216        }
3217
3218        final PermissionsState permissionsState = ps.getPermissionsState();
3219
3220        // Compute GIDs only if requested
3221        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3222                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3223        // Compute granted permissions only if package has requested permissions
3224        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3225                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3226        final PackageUserState state = ps.readUserState(userId);
3227
3228        return PackageParser.generatePackageInfo(p, gids, flags,
3229                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3230    }
3231
3232    @Override
3233    public void checkPackageStartable(String packageName, int userId) {
3234        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3235
3236        synchronized (mPackages) {
3237            final PackageSetting ps = mSettings.mPackages.get(packageName);
3238            if (ps == null) {
3239                throw new SecurityException("Package " + packageName + " was not found!");
3240            }
3241
3242            if (!ps.getInstalled(userId)) {
3243                throw new SecurityException(
3244                        "Package " + packageName + " was not installed for user " + userId + "!");
3245            }
3246
3247            if (mSafeMode && !ps.isSystem()) {
3248                throw new SecurityException("Package " + packageName + " not a system app!");
3249            }
3250
3251            if (mFrozenPackages.contains(packageName)) {
3252                throw new SecurityException("Package " + packageName + " is currently frozen!");
3253            }
3254
3255            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3256                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3257                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3258            }
3259        }
3260    }
3261
3262    @Override
3263    public boolean isPackageAvailable(String packageName, int userId) {
3264        if (!sUserManager.exists(userId)) return false;
3265        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3266                false /* requireFullPermission */, false /* checkShell */, "is package available");
3267        synchronized (mPackages) {
3268            PackageParser.Package p = mPackages.get(packageName);
3269            if (p != null) {
3270                final PackageSetting ps = (PackageSetting) p.mExtras;
3271                if (ps != null) {
3272                    final PackageUserState state = ps.readUserState(userId);
3273                    if (state != null) {
3274                        return PackageParser.isAvailable(state);
3275                    }
3276                }
3277            }
3278        }
3279        return false;
3280    }
3281
3282    @Override
3283    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3284        if (!sUserManager.exists(userId)) return null;
3285        flags = updateFlagsForPackage(flags, userId, packageName);
3286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3287                false /* requireFullPermission */, false /* checkShell */, "get package info");
3288        // reader
3289        synchronized (mPackages) {
3290            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3291            PackageParser.Package p = null;
3292            if (matchFactoryOnly) {
3293                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3294                if (ps != null) {
3295                    return generatePackageInfo(ps, flags, userId);
3296                }
3297            }
3298            if (p == null) {
3299                p = mPackages.get(packageName);
3300                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3301                    return null;
3302                }
3303            }
3304            if (DEBUG_PACKAGE_INFO)
3305                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3306            if (p != null) {
3307                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3308            }
3309            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3310                final PackageSetting ps = mSettings.mPackages.get(packageName);
3311                return generatePackageInfo(ps, flags, userId);
3312            }
3313        }
3314        return null;
3315    }
3316
3317    @Override
3318    public String[] currentToCanonicalPackageNames(String[] names) {
3319        String[] out = new String[names.length];
3320        // reader
3321        synchronized (mPackages) {
3322            for (int i=names.length-1; i>=0; i--) {
3323                PackageSetting ps = mSettings.mPackages.get(names[i]);
3324                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3325            }
3326        }
3327        return out;
3328    }
3329
3330    @Override
3331    public String[] canonicalToCurrentPackageNames(String[] names) {
3332        String[] out = new String[names.length];
3333        // reader
3334        synchronized (mPackages) {
3335            for (int i=names.length-1; i>=0; i--) {
3336                String cur = mSettings.mRenamedPackages.get(names[i]);
3337                out[i] = cur != null ? cur : names[i];
3338            }
3339        }
3340        return out;
3341    }
3342
3343    @Override
3344    public int getPackageUid(String packageName, int flags, int userId) {
3345        if (!sUserManager.exists(userId)) return -1;
3346        flags = updateFlagsForPackage(flags, userId, packageName);
3347        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3348                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3349
3350        // reader
3351        synchronized (mPackages) {
3352            final PackageParser.Package p = mPackages.get(packageName);
3353            if (p != null && p.isMatch(flags)) {
3354                return UserHandle.getUid(userId, p.applicationInfo.uid);
3355            }
3356            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3357                final PackageSetting ps = mSettings.mPackages.get(packageName);
3358                if (ps != null && ps.isMatch(flags)) {
3359                    return UserHandle.getUid(userId, ps.appId);
3360                }
3361            }
3362        }
3363
3364        return -1;
3365    }
3366
3367    @Override
3368    public int[] getPackageGids(String packageName, int flags, int userId) {
3369        if (!sUserManager.exists(userId)) return null;
3370        flags = updateFlagsForPackage(flags, userId, packageName);
3371        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3372                false /* requireFullPermission */, false /* checkShell */,
3373                "getPackageGids");
3374
3375        // reader
3376        synchronized (mPackages) {
3377            final PackageParser.Package p = mPackages.get(packageName);
3378            if (p != null && p.isMatch(flags)) {
3379                PackageSetting ps = (PackageSetting) p.mExtras;
3380                return ps.getPermissionsState().computeGids(userId);
3381            }
3382            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3383                final PackageSetting ps = mSettings.mPackages.get(packageName);
3384                if (ps != null && ps.isMatch(flags)) {
3385                    return ps.getPermissionsState().computeGids(userId);
3386                }
3387            }
3388        }
3389
3390        return null;
3391    }
3392
3393    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3394        if (bp.perm != null) {
3395            return PackageParser.generatePermissionInfo(bp.perm, flags);
3396        }
3397        PermissionInfo pi = new PermissionInfo();
3398        pi.name = bp.name;
3399        pi.packageName = bp.sourcePackage;
3400        pi.nonLocalizedLabel = bp.name;
3401        pi.protectionLevel = bp.protectionLevel;
3402        return pi;
3403    }
3404
3405    @Override
3406    public PermissionInfo getPermissionInfo(String name, int flags) {
3407        // reader
3408        synchronized (mPackages) {
3409            final BasePermission p = mSettings.mPermissions.get(name);
3410            if (p != null) {
3411                return generatePermissionInfo(p, flags);
3412            }
3413            return null;
3414        }
3415    }
3416
3417    @Override
3418    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3419            int flags) {
3420        // reader
3421        synchronized (mPackages) {
3422            if (group != null && !mPermissionGroups.containsKey(group)) {
3423                // This is thrown as NameNotFoundException
3424                return null;
3425            }
3426
3427            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3428            for (BasePermission p : mSettings.mPermissions.values()) {
3429                if (group == null) {
3430                    if (p.perm == null || p.perm.info.group == null) {
3431                        out.add(generatePermissionInfo(p, flags));
3432                    }
3433                } else {
3434                    if (p.perm != null && group.equals(p.perm.info.group)) {
3435                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3436                    }
3437                }
3438            }
3439            return new ParceledListSlice<>(out);
3440        }
3441    }
3442
3443    @Override
3444    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3445        // reader
3446        synchronized (mPackages) {
3447            return PackageParser.generatePermissionGroupInfo(
3448                    mPermissionGroups.get(name), flags);
3449        }
3450    }
3451
3452    @Override
3453    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3454        // reader
3455        synchronized (mPackages) {
3456            final int N = mPermissionGroups.size();
3457            ArrayList<PermissionGroupInfo> out
3458                    = new ArrayList<PermissionGroupInfo>(N);
3459            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3460                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3461            }
3462            return new ParceledListSlice<>(out);
3463        }
3464    }
3465
3466    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3467            int userId) {
3468        if (!sUserManager.exists(userId)) return null;
3469        PackageSetting ps = mSettings.mPackages.get(packageName);
3470        if (ps != null) {
3471            if (ps.pkg == null) {
3472                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3473                if (pInfo != null) {
3474                    return pInfo.applicationInfo;
3475                }
3476                return null;
3477            }
3478            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3479                    ps.readUserState(userId), userId);
3480        }
3481        return null;
3482    }
3483
3484    @Override
3485    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3486        if (!sUserManager.exists(userId)) return null;
3487        flags = updateFlagsForApplication(flags, userId, packageName);
3488        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3489                false /* requireFullPermission */, false /* checkShell */, "get application info");
3490        // writer
3491        synchronized (mPackages) {
3492            PackageParser.Package p = mPackages.get(packageName);
3493            if (DEBUG_PACKAGE_INFO) Log.v(
3494                    TAG, "getApplicationInfo " + packageName
3495                    + ": " + p);
3496            if (p != null) {
3497                PackageSetting ps = mSettings.mPackages.get(packageName);
3498                if (ps == null) return null;
3499                // Note: isEnabledLP() does not apply here - always return info
3500                return PackageParser.generateApplicationInfo(
3501                        p, flags, ps.readUserState(userId), userId);
3502            }
3503            if ("android".equals(packageName)||"system".equals(packageName)) {
3504                return mAndroidApplication;
3505            }
3506            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3507                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3508            }
3509        }
3510        return null;
3511    }
3512
3513    @Override
3514    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3515            final IPackageDataObserver observer) {
3516        mContext.enforceCallingOrSelfPermission(
3517                android.Manifest.permission.CLEAR_APP_CACHE, null);
3518        // Queue up an async operation since clearing cache may take a little while.
3519        mHandler.post(new Runnable() {
3520            public void run() {
3521                mHandler.removeCallbacks(this);
3522                boolean success = true;
3523                synchronized (mInstallLock) {
3524                    try {
3525                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3526                    } catch (InstallerException e) {
3527                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3528                        success = false;
3529                    }
3530                }
3531                if (observer != null) {
3532                    try {
3533                        observer.onRemoveCompleted(null, success);
3534                    } catch (RemoteException e) {
3535                        Slog.w(TAG, "RemoveException when invoking call back");
3536                    }
3537                }
3538            }
3539        });
3540    }
3541
3542    @Override
3543    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3544            final IntentSender pi) {
3545        mContext.enforceCallingOrSelfPermission(
3546                android.Manifest.permission.CLEAR_APP_CACHE, null);
3547        // Queue up an async operation since clearing cache may take a little while.
3548        mHandler.post(new Runnable() {
3549            public void run() {
3550                mHandler.removeCallbacks(this);
3551                boolean success = true;
3552                synchronized (mInstallLock) {
3553                    try {
3554                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3555                    } catch (InstallerException e) {
3556                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3557                        success = false;
3558                    }
3559                }
3560                if(pi != null) {
3561                    try {
3562                        // Callback via pending intent
3563                        int code = success ? 1 : 0;
3564                        pi.sendIntent(null, code, null,
3565                                null, null);
3566                    } catch (SendIntentException e1) {
3567                        Slog.i(TAG, "Failed to send pending intent");
3568                    }
3569                }
3570            }
3571        });
3572    }
3573
3574    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3575        synchronized (mInstallLock) {
3576            try {
3577                mInstaller.freeCache(volumeUuid, freeStorageSize);
3578            } catch (InstallerException e) {
3579                throw new IOException("Failed to free enough space", e);
3580            }
3581        }
3582    }
3583
3584    /**
3585     * Update given flags based on encryption status of current user.
3586     */
3587    private int updateFlags(int flags, int userId) {
3588        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3589                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3590            // Caller expressed an explicit opinion about what encryption
3591            // aware/unaware components they want to see, so fall through and
3592            // give them what they want
3593        } else {
3594            // Caller expressed no opinion, so match based on user state
3595            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3596                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3597            } else {
3598                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3599            }
3600        }
3601        return flags;
3602    }
3603
3604    private UserManagerInternal getUserManagerInternal() {
3605        if (mUserManagerInternal == null) {
3606            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3607        }
3608        return mUserManagerInternal;
3609    }
3610
3611    /**
3612     * Update given flags when being used to request {@link PackageInfo}.
3613     */
3614    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3615        boolean triaged = true;
3616        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3617                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3618            // Caller is asking for component details, so they'd better be
3619            // asking for specific encryption matching behavior, or be triaged
3620            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3621                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3622                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3623                triaged = false;
3624            }
3625        }
3626        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3627                | PackageManager.MATCH_SYSTEM_ONLY
3628                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3629            triaged = false;
3630        }
3631        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3632            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3633                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3634        }
3635        return updateFlags(flags, userId);
3636    }
3637
3638    /**
3639     * Update given flags when being used to request {@link ApplicationInfo}.
3640     */
3641    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3642        return updateFlagsForPackage(flags, userId, cookie);
3643    }
3644
3645    /**
3646     * Update given flags when being used to request {@link ComponentInfo}.
3647     */
3648    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3649        if (cookie instanceof Intent) {
3650            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3651                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3652            }
3653        }
3654
3655        boolean triaged = true;
3656        // Caller is asking for component details, so they'd better be
3657        // asking for specific encryption matching behavior, or be triaged
3658        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3659                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3660                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3661            triaged = false;
3662        }
3663        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3664            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3665                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3666        }
3667
3668        return updateFlags(flags, userId);
3669    }
3670
3671    /**
3672     * Update given flags when being used to request {@link ResolveInfo}.
3673     */
3674    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3675        // Safe mode means we shouldn't match any third-party components
3676        if (mSafeMode) {
3677            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3678        }
3679
3680        return updateFlagsForComponent(flags, userId, cookie);
3681    }
3682
3683    @Override
3684    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3685        if (!sUserManager.exists(userId)) return null;
3686        flags = updateFlagsForComponent(flags, userId, component);
3687        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3688                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3689        synchronized (mPackages) {
3690            PackageParser.Activity a = mActivities.mActivities.get(component);
3691
3692            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3693            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3694                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3695                if (ps == null) return null;
3696                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3697                        userId);
3698            }
3699            if (mResolveComponentName.equals(component)) {
3700                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3701                        new PackageUserState(), userId);
3702            }
3703        }
3704        return null;
3705    }
3706
3707    @Override
3708    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3709            String resolvedType) {
3710        synchronized (mPackages) {
3711            if (component.equals(mResolveComponentName)) {
3712                // The resolver supports EVERYTHING!
3713                return true;
3714            }
3715            PackageParser.Activity a = mActivities.mActivities.get(component);
3716            if (a == null) {
3717                return false;
3718            }
3719            for (int i=0; i<a.intents.size(); i++) {
3720                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3721                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3722                    return true;
3723                }
3724            }
3725            return false;
3726        }
3727    }
3728
3729    @Override
3730    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3731        if (!sUserManager.exists(userId)) return null;
3732        flags = updateFlagsForComponent(flags, userId, component);
3733        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3734                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3735        synchronized (mPackages) {
3736            PackageParser.Activity a = mReceivers.mActivities.get(component);
3737            if (DEBUG_PACKAGE_INFO) Log.v(
3738                TAG, "getReceiverInfo " + component + ": " + a);
3739            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3740                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3741                if (ps == null) return null;
3742                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3743                        userId);
3744            }
3745        }
3746        return null;
3747    }
3748
3749    @Override
3750    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3751        if (!sUserManager.exists(userId)) return null;
3752        flags = updateFlagsForComponent(flags, userId, component);
3753        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3754                false /* requireFullPermission */, false /* checkShell */, "get service info");
3755        synchronized (mPackages) {
3756            PackageParser.Service s = mServices.mServices.get(component);
3757            if (DEBUG_PACKAGE_INFO) Log.v(
3758                TAG, "getServiceInfo " + component + ": " + s);
3759            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3760                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3761                if (ps == null) return null;
3762                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3763                        userId);
3764            }
3765        }
3766        return null;
3767    }
3768
3769    @Override
3770    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3771        if (!sUserManager.exists(userId)) return null;
3772        flags = updateFlagsForComponent(flags, userId, component);
3773        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3774                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3775        synchronized (mPackages) {
3776            PackageParser.Provider p = mProviders.mProviders.get(component);
3777            if (DEBUG_PACKAGE_INFO) Log.v(
3778                TAG, "getProviderInfo " + component + ": " + p);
3779            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3780                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3781                if (ps == null) return null;
3782                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3783                        userId);
3784            }
3785        }
3786        return null;
3787    }
3788
3789    @Override
3790    public String[] getSystemSharedLibraryNames() {
3791        Set<String> libSet;
3792        synchronized (mPackages) {
3793            libSet = mSharedLibraries.keySet();
3794            int size = libSet.size();
3795            if (size > 0) {
3796                String[] libs = new String[size];
3797                libSet.toArray(libs);
3798                return libs;
3799            }
3800        }
3801        return null;
3802    }
3803
3804    @Override
3805    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3806        synchronized (mPackages) {
3807            return mServicesSystemSharedLibraryPackageName;
3808        }
3809    }
3810
3811    @Override
3812    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3813        synchronized (mPackages) {
3814            return mSharedSystemSharedLibraryPackageName;
3815        }
3816    }
3817
3818    @Override
3819    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3820        synchronized (mPackages) {
3821            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3822
3823            final FeatureInfo fi = new FeatureInfo();
3824            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3825                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3826            res.add(fi);
3827
3828            return new ParceledListSlice<>(res);
3829        }
3830    }
3831
3832    @Override
3833    public boolean hasSystemFeature(String name, int version) {
3834        synchronized (mPackages) {
3835            final FeatureInfo feat = mAvailableFeatures.get(name);
3836            if (feat == null) {
3837                return false;
3838            } else {
3839                return feat.version >= version;
3840            }
3841        }
3842    }
3843
3844    @Override
3845    public int checkPermission(String permName, String pkgName, int userId) {
3846        if (!sUserManager.exists(userId)) {
3847            return PackageManager.PERMISSION_DENIED;
3848        }
3849
3850        synchronized (mPackages) {
3851            final PackageParser.Package p = mPackages.get(pkgName);
3852            if (p != null && p.mExtras != null) {
3853                final PackageSetting ps = (PackageSetting) p.mExtras;
3854                final PermissionsState permissionsState = ps.getPermissionsState();
3855                if (permissionsState.hasPermission(permName, userId)) {
3856                    return PackageManager.PERMISSION_GRANTED;
3857                }
3858                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3859                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3860                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3861                    return PackageManager.PERMISSION_GRANTED;
3862                }
3863            }
3864        }
3865
3866        return PackageManager.PERMISSION_DENIED;
3867    }
3868
3869    @Override
3870    public int checkUidPermission(String permName, int uid) {
3871        final int userId = UserHandle.getUserId(uid);
3872
3873        if (!sUserManager.exists(userId)) {
3874            return PackageManager.PERMISSION_DENIED;
3875        }
3876
3877        synchronized (mPackages) {
3878            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3879            if (obj != null) {
3880                final SettingBase ps = (SettingBase) obj;
3881                final PermissionsState permissionsState = ps.getPermissionsState();
3882                if (permissionsState.hasPermission(permName, userId)) {
3883                    return PackageManager.PERMISSION_GRANTED;
3884                }
3885                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3886                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3887                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3888                    return PackageManager.PERMISSION_GRANTED;
3889                }
3890            } else {
3891                ArraySet<String> perms = mSystemPermissions.get(uid);
3892                if (perms != null) {
3893                    if (perms.contains(permName)) {
3894                        return PackageManager.PERMISSION_GRANTED;
3895                    }
3896                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3897                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3898                        return PackageManager.PERMISSION_GRANTED;
3899                    }
3900                }
3901            }
3902        }
3903
3904        return PackageManager.PERMISSION_DENIED;
3905    }
3906
3907    @Override
3908    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3909        if (UserHandle.getCallingUserId() != userId) {
3910            mContext.enforceCallingPermission(
3911                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3912                    "isPermissionRevokedByPolicy for user " + userId);
3913        }
3914
3915        if (checkPermission(permission, packageName, userId)
3916                == PackageManager.PERMISSION_GRANTED) {
3917            return false;
3918        }
3919
3920        final long identity = Binder.clearCallingIdentity();
3921        try {
3922            final int flags = getPermissionFlags(permission, packageName, userId);
3923            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3924        } finally {
3925            Binder.restoreCallingIdentity(identity);
3926        }
3927    }
3928
3929    @Override
3930    public String getPermissionControllerPackageName() {
3931        synchronized (mPackages) {
3932            return mRequiredInstallerPackage;
3933        }
3934    }
3935
3936    /**
3937     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3938     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3939     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3940     * @param message the message to log on security exception
3941     */
3942    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3943            boolean checkShell, String message) {
3944        if (userId < 0) {
3945            throw new IllegalArgumentException("Invalid userId " + userId);
3946        }
3947        if (checkShell) {
3948            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3949        }
3950        if (userId == UserHandle.getUserId(callingUid)) return;
3951        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3952            if (requireFullPermission) {
3953                mContext.enforceCallingOrSelfPermission(
3954                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3955            } else {
3956                try {
3957                    mContext.enforceCallingOrSelfPermission(
3958                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3959                } catch (SecurityException se) {
3960                    mContext.enforceCallingOrSelfPermission(
3961                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3962                }
3963            }
3964        }
3965    }
3966
3967    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3968        if (callingUid == Process.SHELL_UID) {
3969            if (userHandle >= 0
3970                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3971                throw new SecurityException("Shell does not have permission to access user "
3972                        + userHandle);
3973            } else if (userHandle < 0) {
3974                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3975                        + Debug.getCallers(3));
3976            }
3977        }
3978    }
3979
3980    private BasePermission findPermissionTreeLP(String permName) {
3981        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3982            if (permName.startsWith(bp.name) &&
3983                    permName.length() > bp.name.length() &&
3984                    permName.charAt(bp.name.length()) == '.') {
3985                return bp;
3986            }
3987        }
3988        return null;
3989    }
3990
3991    private BasePermission checkPermissionTreeLP(String permName) {
3992        if (permName != null) {
3993            BasePermission bp = findPermissionTreeLP(permName);
3994            if (bp != null) {
3995                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3996                    return bp;
3997                }
3998                throw new SecurityException("Calling uid "
3999                        + Binder.getCallingUid()
4000                        + " is not allowed to add to permission tree "
4001                        + bp.name + " owned by uid " + bp.uid);
4002            }
4003        }
4004        throw new SecurityException("No permission tree found for " + permName);
4005    }
4006
4007    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4008        if (s1 == null) {
4009            return s2 == null;
4010        }
4011        if (s2 == null) {
4012            return false;
4013        }
4014        if (s1.getClass() != s2.getClass()) {
4015            return false;
4016        }
4017        return s1.equals(s2);
4018    }
4019
4020    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4021        if (pi1.icon != pi2.icon) return false;
4022        if (pi1.logo != pi2.logo) return false;
4023        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4024        if (!compareStrings(pi1.name, pi2.name)) return false;
4025        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4026        // We'll take care of setting this one.
4027        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4028        // These are not currently stored in settings.
4029        //if (!compareStrings(pi1.group, pi2.group)) return false;
4030        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4031        //if (pi1.labelRes != pi2.labelRes) return false;
4032        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4033        return true;
4034    }
4035
4036    int permissionInfoFootprint(PermissionInfo info) {
4037        int size = info.name.length();
4038        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4039        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4040        return size;
4041    }
4042
4043    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4044        int size = 0;
4045        for (BasePermission perm : mSettings.mPermissions.values()) {
4046            if (perm.uid == tree.uid) {
4047                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4048            }
4049        }
4050        return size;
4051    }
4052
4053    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4054        // We calculate the max size of permissions defined by this uid and throw
4055        // if that plus the size of 'info' would exceed our stated maximum.
4056        if (tree.uid != Process.SYSTEM_UID) {
4057            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4058            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4059                throw new SecurityException("Permission tree size cap exceeded");
4060            }
4061        }
4062    }
4063
4064    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4065        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4066            throw new SecurityException("Label must be specified in permission");
4067        }
4068        BasePermission tree = checkPermissionTreeLP(info.name);
4069        BasePermission bp = mSettings.mPermissions.get(info.name);
4070        boolean added = bp == null;
4071        boolean changed = true;
4072        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4073        if (added) {
4074            enforcePermissionCapLocked(info, tree);
4075            bp = new BasePermission(info.name, tree.sourcePackage,
4076                    BasePermission.TYPE_DYNAMIC);
4077        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4078            throw new SecurityException(
4079                    "Not allowed to modify non-dynamic permission "
4080                    + info.name);
4081        } else {
4082            if (bp.protectionLevel == fixedLevel
4083                    && bp.perm.owner.equals(tree.perm.owner)
4084                    && bp.uid == tree.uid
4085                    && comparePermissionInfos(bp.perm.info, info)) {
4086                changed = false;
4087            }
4088        }
4089        bp.protectionLevel = fixedLevel;
4090        info = new PermissionInfo(info);
4091        info.protectionLevel = fixedLevel;
4092        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4093        bp.perm.info.packageName = tree.perm.info.packageName;
4094        bp.uid = tree.uid;
4095        if (added) {
4096            mSettings.mPermissions.put(info.name, bp);
4097        }
4098        if (changed) {
4099            if (!async) {
4100                mSettings.writeLPr();
4101            } else {
4102                scheduleWriteSettingsLocked();
4103            }
4104        }
4105        return added;
4106    }
4107
4108    @Override
4109    public boolean addPermission(PermissionInfo info) {
4110        synchronized (mPackages) {
4111            return addPermissionLocked(info, false);
4112        }
4113    }
4114
4115    @Override
4116    public boolean addPermissionAsync(PermissionInfo info) {
4117        synchronized (mPackages) {
4118            return addPermissionLocked(info, true);
4119        }
4120    }
4121
4122    @Override
4123    public void removePermission(String name) {
4124        synchronized (mPackages) {
4125            checkPermissionTreeLP(name);
4126            BasePermission bp = mSettings.mPermissions.get(name);
4127            if (bp != null) {
4128                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4129                    throw new SecurityException(
4130                            "Not allowed to modify non-dynamic permission "
4131                            + name);
4132                }
4133                mSettings.mPermissions.remove(name);
4134                mSettings.writeLPr();
4135            }
4136        }
4137    }
4138
4139    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4140            BasePermission bp) {
4141        int index = pkg.requestedPermissions.indexOf(bp.name);
4142        if (index == -1) {
4143            throw new SecurityException("Package " + pkg.packageName
4144                    + " has not requested permission " + bp.name);
4145        }
4146        if (!bp.isRuntime() && !bp.isDevelopment()) {
4147            throw new SecurityException("Permission " + bp.name
4148                    + " is not a changeable permission type");
4149        }
4150    }
4151
4152    @Override
4153    public void grantRuntimePermission(String packageName, String name, final int userId) {
4154        if (!sUserManager.exists(userId)) {
4155            Log.e(TAG, "No such user:" + userId);
4156            return;
4157        }
4158
4159        mContext.enforceCallingOrSelfPermission(
4160                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4161                "grantRuntimePermission");
4162
4163        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4164                true /* requireFullPermission */, true /* checkShell */,
4165                "grantRuntimePermission");
4166
4167        final int uid;
4168        final SettingBase sb;
4169
4170        synchronized (mPackages) {
4171            final PackageParser.Package pkg = mPackages.get(packageName);
4172            if (pkg == null) {
4173                throw new IllegalArgumentException("Unknown package: " + packageName);
4174            }
4175
4176            final BasePermission bp = mSettings.mPermissions.get(name);
4177            if (bp == null) {
4178                throw new IllegalArgumentException("Unknown permission: " + name);
4179            }
4180
4181            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4182
4183            // If a permission review is required for legacy apps we represent
4184            // their permissions as always granted runtime ones since we need
4185            // to keep the review required permission flag per user while an
4186            // install permission's state is shared across all users.
4187            if (Build.PERMISSIONS_REVIEW_REQUIRED
4188                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4189                    && bp.isRuntime()) {
4190                return;
4191            }
4192
4193            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4194            sb = (SettingBase) pkg.mExtras;
4195            if (sb == null) {
4196                throw new IllegalArgumentException("Unknown package: " + packageName);
4197            }
4198
4199            final PermissionsState permissionsState = sb.getPermissionsState();
4200
4201            final int flags = permissionsState.getPermissionFlags(name, userId);
4202            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4203                throw new SecurityException("Cannot grant system fixed permission "
4204                        + name + " for package " + packageName);
4205            }
4206
4207            if (bp.isDevelopment()) {
4208                // Development permissions must be handled specially, since they are not
4209                // normal runtime permissions.  For now they apply to all users.
4210                if (permissionsState.grantInstallPermission(bp) !=
4211                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4212                    scheduleWriteSettingsLocked();
4213                }
4214                return;
4215            }
4216
4217            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4218                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4219                return;
4220            }
4221
4222            final int result = permissionsState.grantRuntimePermission(bp, userId);
4223            switch (result) {
4224                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4225                    return;
4226                }
4227
4228                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4229                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4230                    mHandler.post(new Runnable() {
4231                        @Override
4232                        public void run() {
4233                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4234                        }
4235                    });
4236                }
4237                break;
4238            }
4239
4240            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4241
4242            // Not critical if that is lost - app has to request again.
4243            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4244        }
4245
4246        // Only need to do this if user is initialized. Otherwise it's a new user
4247        // and there are no processes running as the user yet and there's no need
4248        // to make an expensive call to remount processes for the changed permissions.
4249        if (READ_EXTERNAL_STORAGE.equals(name)
4250                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4251            final long token = Binder.clearCallingIdentity();
4252            try {
4253                if (sUserManager.isInitialized(userId)) {
4254                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4255                            MountServiceInternal.class);
4256                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4257                }
4258            } finally {
4259                Binder.restoreCallingIdentity(token);
4260            }
4261        }
4262    }
4263
4264    @Override
4265    public void revokeRuntimePermission(String packageName, String name, int userId) {
4266        if (!sUserManager.exists(userId)) {
4267            Log.e(TAG, "No such user:" + userId);
4268            return;
4269        }
4270
4271        mContext.enforceCallingOrSelfPermission(
4272                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4273                "revokeRuntimePermission");
4274
4275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4276                true /* requireFullPermission */, true /* checkShell */,
4277                "revokeRuntimePermission");
4278
4279        final int appId;
4280
4281        synchronized (mPackages) {
4282            final PackageParser.Package pkg = mPackages.get(packageName);
4283            if (pkg == null) {
4284                throw new IllegalArgumentException("Unknown package: " + packageName);
4285            }
4286
4287            final BasePermission bp = mSettings.mPermissions.get(name);
4288            if (bp == null) {
4289                throw new IllegalArgumentException("Unknown permission: " + name);
4290            }
4291
4292            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4293
4294            // If a permission review is required for legacy apps we represent
4295            // their permissions as always granted runtime ones since we need
4296            // to keep the review required permission flag per user while an
4297            // install permission's state is shared across all users.
4298            if (Build.PERMISSIONS_REVIEW_REQUIRED
4299                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4300                    && bp.isRuntime()) {
4301                return;
4302            }
4303
4304            SettingBase sb = (SettingBase) pkg.mExtras;
4305            if (sb == null) {
4306                throw new IllegalArgumentException("Unknown package: " + packageName);
4307            }
4308
4309            final PermissionsState permissionsState = sb.getPermissionsState();
4310
4311            final int flags = permissionsState.getPermissionFlags(name, userId);
4312            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4313                throw new SecurityException("Cannot revoke system fixed permission "
4314                        + name + " for package " + packageName);
4315            }
4316
4317            if (bp.isDevelopment()) {
4318                // Development permissions must be handled specially, since they are not
4319                // normal runtime permissions.  For now they apply to all users.
4320                if (permissionsState.revokeInstallPermission(bp) !=
4321                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4322                    scheduleWriteSettingsLocked();
4323                }
4324                return;
4325            }
4326
4327            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4328                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4329                return;
4330            }
4331
4332            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4333
4334            // Critical, after this call app should never have the permission.
4335            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4336
4337            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4338        }
4339
4340        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4341    }
4342
4343    @Override
4344    public void resetRuntimePermissions() {
4345        mContext.enforceCallingOrSelfPermission(
4346                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4347                "revokeRuntimePermission");
4348
4349        int callingUid = Binder.getCallingUid();
4350        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4351            mContext.enforceCallingOrSelfPermission(
4352                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4353                    "resetRuntimePermissions");
4354        }
4355
4356        synchronized (mPackages) {
4357            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4358            for (int userId : UserManagerService.getInstance().getUserIds()) {
4359                final int packageCount = mPackages.size();
4360                for (int i = 0; i < packageCount; i++) {
4361                    PackageParser.Package pkg = mPackages.valueAt(i);
4362                    if (!(pkg.mExtras instanceof PackageSetting)) {
4363                        continue;
4364                    }
4365                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4366                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4367                }
4368            }
4369        }
4370    }
4371
4372    @Override
4373    public int getPermissionFlags(String name, String packageName, int userId) {
4374        if (!sUserManager.exists(userId)) {
4375            return 0;
4376        }
4377
4378        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4379
4380        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4381                true /* requireFullPermission */, false /* checkShell */,
4382                "getPermissionFlags");
4383
4384        synchronized (mPackages) {
4385            final PackageParser.Package pkg = mPackages.get(packageName);
4386            if (pkg == null) {
4387                return 0;
4388            }
4389
4390            final BasePermission bp = mSettings.mPermissions.get(name);
4391            if (bp == null) {
4392                return 0;
4393            }
4394
4395            SettingBase sb = (SettingBase) pkg.mExtras;
4396            if (sb == null) {
4397                return 0;
4398            }
4399
4400            PermissionsState permissionsState = sb.getPermissionsState();
4401            return permissionsState.getPermissionFlags(name, userId);
4402        }
4403    }
4404
4405    @Override
4406    public void updatePermissionFlags(String name, String packageName, int flagMask,
4407            int flagValues, int userId) {
4408        if (!sUserManager.exists(userId)) {
4409            return;
4410        }
4411
4412        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4413
4414        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4415                true /* requireFullPermission */, true /* checkShell */,
4416                "updatePermissionFlags");
4417
4418        // Only the system can change these flags and nothing else.
4419        if (getCallingUid() != Process.SYSTEM_UID) {
4420            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4421            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4422            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4423            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4424            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4425        }
4426
4427        synchronized (mPackages) {
4428            final PackageParser.Package pkg = mPackages.get(packageName);
4429            if (pkg == null) {
4430                throw new IllegalArgumentException("Unknown package: " + packageName);
4431            }
4432
4433            final BasePermission bp = mSettings.mPermissions.get(name);
4434            if (bp == null) {
4435                throw new IllegalArgumentException("Unknown permission: " + name);
4436            }
4437
4438            SettingBase sb = (SettingBase) pkg.mExtras;
4439            if (sb == null) {
4440                throw new IllegalArgumentException("Unknown package: " + packageName);
4441            }
4442
4443            PermissionsState permissionsState = sb.getPermissionsState();
4444
4445            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4446
4447            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4448                // Install and runtime permissions are stored in different places,
4449                // so figure out what permission changed and persist the change.
4450                if (permissionsState.getInstallPermissionState(name) != null) {
4451                    scheduleWriteSettingsLocked();
4452                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4453                        || hadState) {
4454                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4455                }
4456            }
4457        }
4458    }
4459
4460    /**
4461     * Update the permission flags for all packages and runtime permissions of a user in order
4462     * to allow device or profile owner to remove POLICY_FIXED.
4463     */
4464    @Override
4465    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4466        if (!sUserManager.exists(userId)) {
4467            return;
4468        }
4469
4470        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4471
4472        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4473                true /* requireFullPermission */, true /* checkShell */,
4474                "updatePermissionFlagsForAllApps");
4475
4476        // Only the system can change system fixed flags.
4477        if (getCallingUid() != Process.SYSTEM_UID) {
4478            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4479            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4480        }
4481
4482        synchronized (mPackages) {
4483            boolean changed = false;
4484            final int packageCount = mPackages.size();
4485            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4486                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4487                SettingBase sb = (SettingBase) pkg.mExtras;
4488                if (sb == null) {
4489                    continue;
4490                }
4491                PermissionsState permissionsState = sb.getPermissionsState();
4492                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4493                        userId, flagMask, flagValues);
4494            }
4495            if (changed) {
4496                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4497            }
4498        }
4499    }
4500
4501    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4502        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4503                != PackageManager.PERMISSION_GRANTED
4504            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4505                != PackageManager.PERMISSION_GRANTED) {
4506            throw new SecurityException(message + " requires "
4507                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4508                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4509        }
4510    }
4511
4512    @Override
4513    public boolean shouldShowRequestPermissionRationale(String permissionName,
4514            String packageName, int userId) {
4515        if (UserHandle.getCallingUserId() != userId) {
4516            mContext.enforceCallingPermission(
4517                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4518                    "canShowRequestPermissionRationale for user " + userId);
4519        }
4520
4521        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4522        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4523            return false;
4524        }
4525
4526        if (checkPermission(permissionName, packageName, userId)
4527                == PackageManager.PERMISSION_GRANTED) {
4528            return false;
4529        }
4530
4531        final int flags;
4532
4533        final long identity = Binder.clearCallingIdentity();
4534        try {
4535            flags = getPermissionFlags(permissionName,
4536                    packageName, userId);
4537        } finally {
4538            Binder.restoreCallingIdentity(identity);
4539        }
4540
4541        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4542                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4543                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4544
4545        if ((flags & fixedFlags) != 0) {
4546            return false;
4547        }
4548
4549        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4550    }
4551
4552    @Override
4553    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4554        mContext.enforceCallingOrSelfPermission(
4555                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4556                "addOnPermissionsChangeListener");
4557
4558        synchronized (mPackages) {
4559            mOnPermissionChangeListeners.addListenerLocked(listener);
4560        }
4561    }
4562
4563    @Override
4564    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4565        synchronized (mPackages) {
4566            mOnPermissionChangeListeners.removeListenerLocked(listener);
4567        }
4568    }
4569
4570    @Override
4571    public boolean isProtectedBroadcast(String actionName) {
4572        synchronized (mPackages) {
4573            if (mProtectedBroadcasts.contains(actionName)) {
4574                return true;
4575            } else if (actionName != null) {
4576                // TODO: remove these terrible hacks
4577                if (actionName.startsWith("android.net.netmon.lingerExpired")
4578                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4579                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4580                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4581                    return true;
4582                }
4583            }
4584        }
4585        return false;
4586    }
4587
4588    @Override
4589    public int checkSignatures(String pkg1, String pkg2) {
4590        synchronized (mPackages) {
4591            final PackageParser.Package p1 = mPackages.get(pkg1);
4592            final PackageParser.Package p2 = mPackages.get(pkg2);
4593            if (p1 == null || p1.mExtras == null
4594                    || p2 == null || p2.mExtras == null) {
4595                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4596            }
4597            return compareSignatures(p1.mSignatures, p2.mSignatures);
4598        }
4599    }
4600
4601    @Override
4602    public int checkUidSignatures(int uid1, int uid2) {
4603        // Map to base uids.
4604        uid1 = UserHandle.getAppId(uid1);
4605        uid2 = UserHandle.getAppId(uid2);
4606        // reader
4607        synchronized (mPackages) {
4608            Signature[] s1;
4609            Signature[] s2;
4610            Object obj = mSettings.getUserIdLPr(uid1);
4611            if (obj != null) {
4612                if (obj instanceof SharedUserSetting) {
4613                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4614                } else if (obj instanceof PackageSetting) {
4615                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4616                } else {
4617                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4618                }
4619            } else {
4620                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4621            }
4622            obj = mSettings.getUserIdLPr(uid2);
4623            if (obj != null) {
4624                if (obj instanceof SharedUserSetting) {
4625                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4626                } else if (obj instanceof PackageSetting) {
4627                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4628                } else {
4629                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4630                }
4631            } else {
4632                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4633            }
4634            return compareSignatures(s1, s2);
4635        }
4636    }
4637
4638    /**
4639     * This method should typically only be used when granting or revoking
4640     * permissions, since the app may immediately restart after this call.
4641     * <p>
4642     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4643     * guard your work against the app being relaunched.
4644     */
4645    private void killUid(int appId, int userId, String reason) {
4646        final long identity = Binder.clearCallingIdentity();
4647        try {
4648            IActivityManager am = ActivityManagerNative.getDefault();
4649            if (am != null) {
4650                try {
4651                    am.killUid(appId, userId, reason);
4652                } catch (RemoteException e) {
4653                    /* ignore - same process */
4654                }
4655            }
4656        } finally {
4657            Binder.restoreCallingIdentity(identity);
4658        }
4659    }
4660
4661    /**
4662     * Compares two sets of signatures. Returns:
4663     * <br />
4664     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4665     * <br />
4666     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4667     * <br />
4668     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4669     * <br />
4670     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4671     * <br />
4672     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4673     */
4674    static int compareSignatures(Signature[] s1, Signature[] s2) {
4675        if (s1 == null) {
4676            return s2 == null
4677                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4678                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4679        }
4680
4681        if (s2 == null) {
4682            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4683        }
4684
4685        if (s1.length != s2.length) {
4686            return PackageManager.SIGNATURE_NO_MATCH;
4687        }
4688
4689        // Since both signature sets are of size 1, we can compare without HashSets.
4690        if (s1.length == 1) {
4691            return s1[0].equals(s2[0]) ?
4692                    PackageManager.SIGNATURE_MATCH :
4693                    PackageManager.SIGNATURE_NO_MATCH;
4694        }
4695
4696        ArraySet<Signature> set1 = new ArraySet<Signature>();
4697        for (Signature sig : s1) {
4698            set1.add(sig);
4699        }
4700        ArraySet<Signature> set2 = new ArraySet<Signature>();
4701        for (Signature sig : s2) {
4702            set2.add(sig);
4703        }
4704        // Make sure s2 contains all signatures in s1.
4705        if (set1.equals(set2)) {
4706            return PackageManager.SIGNATURE_MATCH;
4707        }
4708        return PackageManager.SIGNATURE_NO_MATCH;
4709    }
4710
4711    /**
4712     * If the database version for this type of package (internal storage or
4713     * external storage) is less than the version where package signatures
4714     * were updated, return true.
4715     */
4716    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4717        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4718        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4719    }
4720
4721    /**
4722     * Used for backward compatibility to make sure any packages with
4723     * certificate chains get upgraded to the new style. {@code existingSigs}
4724     * will be in the old format (since they were stored on disk from before the
4725     * system upgrade) and {@code scannedSigs} will be in the newer format.
4726     */
4727    private int compareSignaturesCompat(PackageSignatures existingSigs,
4728            PackageParser.Package scannedPkg) {
4729        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4730            return PackageManager.SIGNATURE_NO_MATCH;
4731        }
4732
4733        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4734        for (Signature sig : existingSigs.mSignatures) {
4735            existingSet.add(sig);
4736        }
4737        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4738        for (Signature sig : scannedPkg.mSignatures) {
4739            try {
4740                Signature[] chainSignatures = sig.getChainSignatures();
4741                for (Signature chainSig : chainSignatures) {
4742                    scannedCompatSet.add(chainSig);
4743                }
4744            } catch (CertificateEncodingException e) {
4745                scannedCompatSet.add(sig);
4746            }
4747        }
4748        /*
4749         * Make sure the expanded scanned set contains all signatures in the
4750         * existing one.
4751         */
4752        if (scannedCompatSet.equals(existingSet)) {
4753            // Migrate the old signatures to the new scheme.
4754            existingSigs.assignSignatures(scannedPkg.mSignatures);
4755            // The new KeySets will be re-added later in the scanning process.
4756            synchronized (mPackages) {
4757                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4758            }
4759            return PackageManager.SIGNATURE_MATCH;
4760        }
4761        return PackageManager.SIGNATURE_NO_MATCH;
4762    }
4763
4764    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4765        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4766        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4767    }
4768
4769    private int compareSignaturesRecover(PackageSignatures existingSigs,
4770            PackageParser.Package scannedPkg) {
4771        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4772            return PackageManager.SIGNATURE_NO_MATCH;
4773        }
4774
4775        String msg = null;
4776        try {
4777            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4778                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4779                        + scannedPkg.packageName);
4780                return PackageManager.SIGNATURE_MATCH;
4781            }
4782        } catch (CertificateException e) {
4783            msg = e.getMessage();
4784        }
4785
4786        logCriticalInfo(Log.INFO,
4787                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4788        return PackageManager.SIGNATURE_NO_MATCH;
4789    }
4790
4791    @Override
4792    public List<String> getAllPackages() {
4793        synchronized (mPackages) {
4794            return new ArrayList<String>(mPackages.keySet());
4795        }
4796    }
4797
4798    @Override
4799    public String[] getPackagesForUid(int uid) {
4800        uid = UserHandle.getAppId(uid);
4801        // reader
4802        synchronized (mPackages) {
4803            Object obj = mSettings.getUserIdLPr(uid);
4804            if (obj instanceof SharedUserSetting) {
4805                final SharedUserSetting sus = (SharedUserSetting) obj;
4806                final int N = sus.packages.size();
4807                final String[] res = new String[N];
4808                for (int i = 0; i < N; i++) {
4809                    res[i] = sus.packages.valueAt(i).name;
4810                }
4811                return res;
4812            } else if (obj instanceof PackageSetting) {
4813                final PackageSetting ps = (PackageSetting) obj;
4814                return new String[] { ps.name };
4815            }
4816        }
4817        return null;
4818    }
4819
4820    @Override
4821    public String getNameForUid(int uid) {
4822        // reader
4823        synchronized (mPackages) {
4824            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4825            if (obj instanceof SharedUserSetting) {
4826                final SharedUserSetting sus = (SharedUserSetting) obj;
4827                return sus.name + ":" + sus.userId;
4828            } else if (obj instanceof PackageSetting) {
4829                final PackageSetting ps = (PackageSetting) obj;
4830                return ps.name;
4831            }
4832        }
4833        return null;
4834    }
4835
4836    @Override
4837    public int getUidForSharedUser(String sharedUserName) {
4838        if(sharedUserName == null) {
4839            return -1;
4840        }
4841        // reader
4842        synchronized (mPackages) {
4843            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4844            if (suid == null) {
4845                return -1;
4846            }
4847            return suid.userId;
4848        }
4849    }
4850
4851    @Override
4852    public int getFlagsForUid(int uid) {
4853        synchronized (mPackages) {
4854            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4855            if (obj instanceof SharedUserSetting) {
4856                final SharedUserSetting sus = (SharedUserSetting) obj;
4857                return sus.pkgFlags;
4858            } else if (obj instanceof PackageSetting) {
4859                final PackageSetting ps = (PackageSetting) obj;
4860                return ps.pkgFlags;
4861            }
4862        }
4863        return 0;
4864    }
4865
4866    @Override
4867    public int getPrivateFlagsForUid(int uid) {
4868        synchronized (mPackages) {
4869            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4870            if (obj instanceof SharedUserSetting) {
4871                final SharedUserSetting sus = (SharedUserSetting) obj;
4872                return sus.pkgPrivateFlags;
4873            } else if (obj instanceof PackageSetting) {
4874                final PackageSetting ps = (PackageSetting) obj;
4875                return ps.pkgPrivateFlags;
4876            }
4877        }
4878        return 0;
4879    }
4880
4881    @Override
4882    public boolean isUidPrivileged(int uid) {
4883        uid = UserHandle.getAppId(uid);
4884        // reader
4885        synchronized (mPackages) {
4886            Object obj = mSettings.getUserIdLPr(uid);
4887            if (obj instanceof SharedUserSetting) {
4888                final SharedUserSetting sus = (SharedUserSetting) obj;
4889                final Iterator<PackageSetting> it = sus.packages.iterator();
4890                while (it.hasNext()) {
4891                    if (it.next().isPrivileged()) {
4892                        return true;
4893                    }
4894                }
4895            } else if (obj instanceof PackageSetting) {
4896                final PackageSetting ps = (PackageSetting) obj;
4897                return ps.isPrivileged();
4898            }
4899        }
4900        return false;
4901    }
4902
4903    @Override
4904    public String[] getAppOpPermissionPackages(String permissionName) {
4905        synchronized (mPackages) {
4906            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4907            if (pkgs == null) {
4908                return null;
4909            }
4910            return pkgs.toArray(new String[pkgs.size()]);
4911        }
4912    }
4913
4914    @Override
4915    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4916            int flags, int userId) {
4917        try {
4918            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4919
4920            if (!sUserManager.exists(userId)) return null;
4921            flags = updateFlagsForResolve(flags, userId, intent);
4922            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4923                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4924
4925            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4926            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4927                    flags, userId);
4928            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4929
4930            final ResolveInfo bestChoice =
4931                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4932
4933            if (isEphemeralAllowed(intent, query, userId)) {
4934                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4935                final EphemeralResolveInfo ai =
4936                        getEphemeralResolveInfo(intent, resolvedType, userId);
4937                if (ai != null) {
4938                    if (DEBUG_EPHEMERAL) {
4939                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4940                    }
4941                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4942                    bestChoice.ephemeralResolveInfo = ai;
4943                }
4944                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4945            }
4946            return bestChoice;
4947        } finally {
4948            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4949        }
4950    }
4951
4952    @Override
4953    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4954            IntentFilter filter, int match, ComponentName activity) {
4955        final int userId = UserHandle.getCallingUserId();
4956        if (DEBUG_PREFERRED) {
4957            Log.v(TAG, "setLastChosenActivity intent=" + intent
4958                + " resolvedType=" + resolvedType
4959                + " flags=" + flags
4960                + " filter=" + filter
4961                + " match=" + match
4962                + " activity=" + activity);
4963            filter.dump(new PrintStreamPrinter(System.out), "    ");
4964        }
4965        intent.setComponent(null);
4966        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4967                userId);
4968        // Find any earlier preferred or last chosen entries and nuke them
4969        findPreferredActivity(intent, resolvedType,
4970                flags, query, 0, false, true, false, userId);
4971        // Add the new activity as the last chosen for this filter
4972        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4973                "Setting last chosen");
4974    }
4975
4976    @Override
4977    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4978        final int userId = UserHandle.getCallingUserId();
4979        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4980        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4981                userId);
4982        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4983                false, false, false, userId);
4984    }
4985
4986
4987    private boolean isEphemeralAllowed(
4988            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4989        // Short circuit and return early if possible.
4990        if (DISABLE_EPHEMERAL_APPS) {
4991            return false;
4992        }
4993        final int callingUser = UserHandle.getCallingUserId();
4994        if (callingUser != UserHandle.USER_SYSTEM) {
4995            return false;
4996        }
4997        if (mEphemeralResolverConnection == null) {
4998            return false;
4999        }
5000        if (intent.getComponent() != null) {
5001            return false;
5002        }
5003        if (intent.getPackage() != null) {
5004            return false;
5005        }
5006        final boolean isWebUri = hasWebURI(intent);
5007        if (!isWebUri) {
5008            return false;
5009        }
5010        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5011        synchronized (mPackages) {
5012            final int count = resolvedActivites.size();
5013            for (int n = 0; n < count; n++) {
5014                ResolveInfo info = resolvedActivites.get(n);
5015                String packageName = info.activityInfo.packageName;
5016                PackageSetting ps = mSettings.mPackages.get(packageName);
5017                if (ps != null) {
5018                    // Try to get the status from User settings first
5019                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5020                    int status = (int) (packedStatus >> 32);
5021                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5022                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5023                        if (DEBUG_EPHEMERAL) {
5024                            Slog.v(TAG, "DENY ephemeral apps;"
5025                                + " pkg: " + packageName + ", status: " + status);
5026                        }
5027                        return false;
5028                    }
5029                }
5030            }
5031        }
5032        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5033        return true;
5034    }
5035
5036    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
5037            int userId) {
5038        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
5039                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
5040        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
5041                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
5042        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
5043                ephemeralPrefixCount);
5044        final int[] shaPrefix = digest.getDigestPrefix();
5045        final byte[][] digestBytes = digest.getDigestBytes();
5046        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5047                mEphemeralResolverConnection.getEphemeralResolveInfoList(
5048                        shaPrefix, ephemeralPrefixMask);
5049        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5050            // No hash prefix match; there are no ephemeral apps for this domain.
5051            return null;
5052        }
5053
5054        // Go in reverse order so we match the narrowest scope first.
5055        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5056            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5057                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5058                    continue;
5059                }
5060                final List<IntentFilter> filters = ephemeralApplication.getFilters();
5061                // No filters; this should never happen.
5062                if (filters.isEmpty()) {
5063                    continue;
5064                }
5065                // We have a domain match; resolve the filters to see if anything matches.
5066                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5067                for (int j = filters.size() - 1; j >= 0; --j) {
5068                    final EphemeralResolveIntentInfo intentInfo =
5069                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5070                    ephemeralResolver.addFilter(intentInfo);
5071                }
5072                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5073                        intent, resolvedType, false /*defaultOnly*/, userId);
5074                if (!matchedResolveInfoList.isEmpty()) {
5075                    return matchedResolveInfoList.get(0);
5076                }
5077            }
5078        }
5079        // Hash or filter mis-match; no ephemeral apps for this domain.
5080        return null;
5081    }
5082
5083    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5084            int flags, List<ResolveInfo> query, int userId) {
5085        if (query != null) {
5086            final int N = query.size();
5087            if (N == 1) {
5088                return query.get(0);
5089            } else if (N > 1) {
5090                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5091                // If there is more than one activity with the same priority,
5092                // then let the user decide between them.
5093                ResolveInfo r0 = query.get(0);
5094                ResolveInfo r1 = query.get(1);
5095                if (DEBUG_INTENT_MATCHING || debug) {
5096                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5097                            + r1.activityInfo.name + "=" + r1.priority);
5098                }
5099                // If the first activity has a higher priority, or a different
5100                // default, then it is always desirable to pick it.
5101                if (r0.priority != r1.priority
5102                        || r0.preferredOrder != r1.preferredOrder
5103                        || r0.isDefault != r1.isDefault) {
5104                    return query.get(0);
5105                }
5106                // If we have saved a preference for a preferred activity for
5107                // this Intent, use that.
5108                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5109                        flags, query, r0.priority, true, false, debug, userId);
5110                if (ri != null) {
5111                    return ri;
5112                }
5113                ri = new ResolveInfo(mResolveInfo);
5114                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5115                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5116                // If all of the options come from the same package, show the application's
5117                // label and icon instead of the generic resolver's.
5118                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5119                // and then throw away the ResolveInfo itself, meaning that the caller loses
5120                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5121                // a fallback for this case; we only set the target package's resources on
5122                // the ResolveInfo, not the ActivityInfo.
5123                final String intentPackage = intent.getPackage();
5124                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5125                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5126                    ri.resolvePackageName = intentPackage;
5127                    if (userNeedsBadging(userId)) {
5128                        ri.noResourceId = true;
5129                    } else {
5130                        ri.icon = appi.icon;
5131                    }
5132                    ri.iconResourceId = appi.icon;
5133                    ri.labelRes = appi.labelRes;
5134                }
5135                ri.activityInfo.applicationInfo = new ApplicationInfo(
5136                        ri.activityInfo.applicationInfo);
5137                if (userId != 0) {
5138                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5139                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5140                }
5141                // Make sure that the resolver is displayable in car mode
5142                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5143                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5144                return ri;
5145            }
5146        }
5147        return null;
5148    }
5149
5150    /**
5151     * Return true if the given list is not empty and all of its contents have
5152     * an activityInfo with the given package name.
5153     */
5154    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5155        if (ArrayUtils.isEmpty(list)) {
5156            return false;
5157        }
5158        for (int i = 0, N = list.size(); i < N; i++) {
5159            final ResolveInfo ri = list.get(i);
5160            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5161            if (ai == null || !packageName.equals(ai.packageName)) {
5162                return false;
5163            }
5164        }
5165        return true;
5166    }
5167
5168    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5169            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5170        final int N = query.size();
5171        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5172                .get(userId);
5173        // Get the list of persistent preferred activities that handle the intent
5174        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5175        List<PersistentPreferredActivity> pprefs = ppir != null
5176                ? ppir.queryIntent(intent, resolvedType,
5177                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5178                : null;
5179        if (pprefs != null && pprefs.size() > 0) {
5180            final int M = pprefs.size();
5181            for (int i=0; i<M; i++) {
5182                final PersistentPreferredActivity ppa = pprefs.get(i);
5183                if (DEBUG_PREFERRED || debug) {
5184                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5185                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5186                            + "\n  component=" + ppa.mComponent);
5187                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5188                }
5189                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5190                        flags | MATCH_DISABLED_COMPONENTS, userId);
5191                if (DEBUG_PREFERRED || debug) {
5192                    Slog.v(TAG, "Found persistent preferred activity:");
5193                    if (ai != null) {
5194                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5195                    } else {
5196                        Slog.v(TAG, "  null");
5197                    }
5198                }
5199                if (ai == null) {
5200                    // This previously registered persistent preferred activity
5201                    // component is no longer known. Ignore it and do NOT remove it.
5202                    continue;
5203                }
5204                for (int j=0; j<N; j++) {
5205                    final ResolveInfo ri = query.get(j);
5206                    if (!ri.activityInfo.applicationInfo.packageName
5207                            .equals(ai.applicationInfo.packageName)) {
5208                        continue;
5209                    }
5210                    if (!ri.activityInfo.name.equals(ai.name)) {
5211                        continue;
5212                    }
5213                    //  Found a persistent preference that can handle the intent.
5214                    if (DEBUG_PREFERRED || debug) {
5215                        Slog.v(TAG, "Returning persistent preferred activity: " +
5216                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5217                    }
5218                    return ri;
5219                }
5220            }
5221        }
5222        return null;
5223    }
5224
5225    // TODO: handle preferred activities missing while user has amnesia
5226    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5227            List<ResolveInfo> query, int priority, boolean always,
5228            boolean removeMatches, boolean debug, int userId) {
5229        if (!sUserManager.exists(userId)) return null;
5230        flags = updateFlagsForResolve(flags, userId, intent);
5231        // writer
5232        synchronized (mPackages) {
5233            if (intent.getSelector() != null) {
5234                intent = intent.getSelector();
5235            }
5236            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5237
5238            // Try to find a matching persistent preferred activity.
5239            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5240                    debug, userId);
5241
5242            // If a persistent preferred activity matched, use it.
5243            if (pri != null) {
5244                return pri;
5245            }
5246
5247            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5248            // Get the list of preferred activities that handle the intent
5249            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5250            List<PreferredActivity> prefs = pir != null
5251                    ? pir.queryIntent(intent, resolvedType,
5252                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5253                    : null;
5254            if (prefs != null && prefs.size() > 0) {
5255                boolean changed = false;
5256                try {
5257                    // First figure out how good the original match set is.
5258                    // We will only allow preferred activities that came
5259                    // from the same match quality.
5260                    int match = 0;
5261
5262                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5263
5264                    final int N = query.size();
5265                    for (int j=0; j<N; j++) {
5266                        final ResolveInfo ri = query.get(j);
5267                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5268                                + ": 0x" + Integer.toHexString(match));
5269                        if (ri.match > match) {
5270                            match = ri.match;
5271                        }
5272                    }
5273
5274                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5275                            + Integer.toHexString(match));
5276
5277                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5278                    final int M = prefs.size();
5279                    for (int i=0; i<M; i++) {
5280                        final PreferredActivity pa = prefs.get(i);
5281                        if (DEBUG_PREFERRED || debug) {
5282                            Slog.v(TAG, "Checking PreferredActivity ds="
5283                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5284                                    + "\n  component=" + pa.mPref.mComponent);
5285                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5286                        }
5287                        if (pa.mPref.mMatch != match) {
5288                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5289                                    + Integer.toHexString(pa.mPref.mMatch));
5290                            continue;
5291                        }
5292                        // If it's not an "always" type preferred activity and that's what we're
5293                        // looking for, skip it.
5294                        if (always && !pa.mPref.mAlways) {
5295                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5296                            continue;
5297                        }
5298                        final ActivityInfo ai = getActivityInfo(
5299                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5300                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5301                                userId);
5302                        if (DEBUG_PREFERRED || debug) {
5303                            Slog.v(TAG, "Found preferred activity:");
5304                            if (ai != null) {
5305                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5306                            } else {
5307                                Slog.v(TAG, "  null");
5308                            }
5309                        }
5310                        if (ai == null) {
5311                            // This previously registered preferred activity
5312                            // component is no longer known.  Most likely an update
5313                            // to the app was installed and in the new version this
5314                            // component no longer exists.  Clean it up by removing
5315                            // it from the preferred activities list, and skip it.
5316                            Slog.w(TAG, "Removing dangling preferred activity: "
5317                                    + pa.mPref.mComponent);
5318                            pir.removeFilter(pa);
5319                            changed = true;
5320                            continue;
5321                        }
5322                        for (int j=0; j<N; j++) {
5323                            final ResolveInfo ri = query.get(j);
5324                            if (!ri.activityInfo.applicationInfo.packageName
5325                                    .equals(ai.applicationInfo.packageName)) {
5326                                continue;
5327                            }
5328                            if (!ri.activityInfo.name.equals(ai.name)) {
5329                                continue;
5330                            }
5331
5332                            if (removeMatches) {
5333                                pir.removeFilter(pa);
5334                                changed = true;
5335                                if (DEBUG_PREFERRED) {
5336                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5337                                }
5338                                break;
5339                            }
5340
5341                            // Okay we found a previously set preferred or last chosen app.
5342                            // If the result set is different from when this
5343                            // was created, we need to clear it and re-ask the
5344                            // user their preference, if we're looking for an "always" type entry.
5345                            if (always && !pa.mPref.sameSet(query)) {
5346                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5347                                        + intent + " type " + resolvedType);
5348                                if (DEBUG_PREFERRED) {
5349                                    Slog.v(TAG, "Removing preferred activity since set changed "
5350                                            + pa.mPref.mComponent);
5351                                }
5352                                pir.removeFilter(pa);
5353                                // Re-add the filter as a "last chosen" entry (!always)
5354                                PreferredActivity lastChosen = new PreferredActivity(
5355                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5356                                pir.addFilter(lastChosen);
5357                                changed = true;
5358                                return null;
5359                            }
5360
5361                            // Yay! Either the set matched or we're looking for the last chosen
5362                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5363                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5364                            return ri;
5365                        }
5366                    }
5367                } finally {
5368                    if (changed) {
5369                        if (DEBUG_PREFERRED) {
5370                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5371                        }
5372                        scheduleWritePackageRestrictionsLocked(userId);
5373                    }
5374                }
5375            }
5376        }
5377        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5378        return null;
5379    }
5380
5381    /*
5382     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5383     */
5384    @Override
5385    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5386            int targetUserId) {
5387        mContext.enforceCallingOrSelfPermission(
5388                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5389        List<CrossProfileIntentFilter> matches =
5390                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5391        if (matches != null) {
5392            int size = matches.size();
5393            for (int i = 0; i < size; i++) {
5394                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5395            }
5396        }
5397        if (hasWebURI(intent)) {
5398            // cross-profile app linking works only towards the parent.
5399            final UserInfo parent = getProfileParent(sourceUserId);
5400            synchronized(mPackages) {
5401                int flags = updateFlagsForResolve(0, parent.id, intent);
5402                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5403                        intent, resolvedType, flags, sourceUserId, parent.id);
5404                return xpDomainInfo != null;
5405            }
5406        }
5407        return false;
5408    }
5409
5410    private UserInfo getProfileParent(int userId) {
5411        final long identity = Binder.clearCallingIdentity();
5412        try {
5413            return sUserManager.getProfileParent(userId);
5414        } finally {
5415            Binder.restoreCallingIdentity(identity);
5416        }
5417    }
5418
5419    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5420            String resolvedType, int userId) {
5421        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5422        if (resolver != null) {
5423            return resolver.queryIntent(intent, resolvedType, false, userId);
5424        }
5425        return null;
5426    }
5427
5428    @Override
5429    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5430            String resolvedType, int flags, int userId) {
5431        try {
5432            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5433
5434            return new ParceledListSlice<>(
5435                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5436        } finally {
5437            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5438        }
5439    }
5440
5441    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5442            String resolvedType, int flags, int userId) {
5443        if (!sUserManager.exists(userId)) return Collections.emptyList();
5444        flags = updateFlagsForResolve(flags, userId, intent);
5445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5446                false /* requireFullPermission */, false /* checkShell */,
5447                "query intent activities");
5448        ComponentName comp = intent.getComponent();
5449        if (comp == null) {
5450            if (intent.getSelector() != null) {
5451                intent = intent.getSelector();
5452                comp = intent.getComponent();
5453            }
5454        }
5455
5456        if (comp != null) {
5457            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5458            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5459            if (ai != null) {
5460                final ResolveInfo ri = new ResolveInfo();
5461                ri.activityInfo = ai;
5462                list.add(ri);
5463            }
5464            return list;
5465        }
5466
5467        // reader
5468        synchronized (mPackages) {
5469            final String pkgName = intent.getPackage();
5470            if (pkgName == null) {
5471                List<CrossProfileIntentFilter> matchingFilters =
5472                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5473                // Check for results that need to skip the current profile.
5474                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5475                        resolvedType, flags, userId);
5476                if (xpResolveInfo != null) {
5477                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5478                    result.add(xpResolveInfo);
5479                    return filterIfNotSystemUser(result, userId);
5480                }
5481
5482                // Check for results in the current profile.
5483                List<ResolveInfo> result = mActivities.queryIntent(
5484                        intent, resolvedType, flags, userId);
5485                result = filterIfNotSystemUser(result, userId);
5486
5487                // Check for cross profile results.
5488                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5489                xpResolveInfo = queryCrossProfileIntents(
5490                        matchingFilters, intent, resolvedType, flags, userId,
5491                        hasNonNegativePriorityResult);
5492                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5493                    boolean isVisibleToUser = filterIfNotSystemUser(
5494                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5495                    if (isVisibleToUser) {
5496                        result.add(xpResolveInfo);
5497                        Collections.sort(result, mResolvePrioritySorter);
5498                    }
5499                }
5500                if (hasWebURI(intent)) {
5501                    CrossProfileDomainInfo xpDomainInfo = null;
5502                    final UserInfo parent = getProfileParent(userId);
5503                    if (parent != null) {
5504                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5505                                flags, userId, parent.id);
5506                    }
5507                    if (xpDomainInfo != null) {
5508                        if (xpResolveInfo != null) {
5509                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5510                            // in the result.
5511                            result.remove(xpResolveInfo);
5512                        }
5513                        if (result.size() == 0) {
5514                            result.add(xpDomainInfo.resolveInfo);
5515                            return result;
5516                        }
5517                    } else if (result.size() <= 1) {
5518                        return result;
5519                    }
5520                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5521                            xpDomainInfo, userId);
5522                    Collections.sort(result, mResolvePrioritySorter);
5523                }
5524                return result;
5525            }
5526            final PackageParser.Package pkg = mPackages.get(pkgName);
5527            if (pkg != null) {
5528                return filterIfNotSystemUser(
5529                        mActivities.queryIntentForPackage(
5530                                intent, resolvedType, flags, pkg.activities, userId),
5531                        userId);
5532            }
5533            return new ArrayList<ResolveInfo>();
5534        }
5535    }
5536
5537    private static class CrossProfileDomainInfo {
5538        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5539        ResolveInfo resolveInfo;
5540        /* Best domain verification status of the activities found in the other profile */
5541        int bestDomainVerificationStatus;
5542    }
5543
5544    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5545            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5546        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5547                sourceUserId)) {
5548            return null;
5549        }
5550        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5551                resolvedType, flags, parentUserId);
5552
5553        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5554            return null;
5555        }
5556        CrossProfileDomainInfo result = null;
5557        int size = resultTargetUser.size();
5558        for (int i = 0; i < size; i++) {
5559            ResolveInfo riTargetUser = resultTargetUser.get(i);
5560            // Intent filter verification is only for filters that specify a host. So don't return
5561            // those that handle all web uris.
5562            if (riTargetUser.handleAllWebDataURI) {
5563                continue;
5564            }
5565            String packageName = riTargetUser.activityInfo.packageName;
5566            PackageSetting ps = mSettings.mPackages.get(packageName);
5567            if (ps == null) {
5568                continue;
5569            }
5570            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5571            int status = (int)(verificationState >> 32);
5572            if (result == null) {
5573                result = new CrossProfileDomainInfo();
5574                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5575                        sourceUserId, parentUserId);
5576                result.bestDomainVerificationStatus = status;
5577            } else {
5578                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5579                        result.bestDomainVerificationStatus);
5580            }
5581        }
5582        // Don't consider matches with status NEVER across profiles.
5583        if (result != null && result.bestDomainVerificationStatus
5584                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5585            return null;
5586        }
5587        return result;
5588    }
5589
5590    /**
5591     * Verification statuses are ordered from the worse to the best, except for
5592     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5593     */
5594    private int bestDomainVerificationStatus(int status1, int status2) {
5595        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5596            return status2;
5597        }
5598        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5599            return status1;
5600        }
5601        return (int) MathUtils.max(status1, status2);
5602    }
5603
5604    private boolean isUserEnabled(int userId) {
5605        long callingId = Binder.clearCallingIdentity();
5606        try {
5607            UserInfo userInfo = sUserManager.getUserInfo(userId);
5608            return userInfo != null && userInfo.isEnabled();
5609        } finally {
5610            Binder.restoreCallingIdentity(callingId);
5611        }
5612    }
5613
5614    /**
5615     * Filter out activities with systemUserOnly flag set, when current user is not System.
5616     *
5617     * @return filtered list
5618     */
5619    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5620        if (userId == UserHandle.USER_SYSTEM) {
5621            return resolveInfos;
5622        }
5623        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5624            ResolveInfo info = resolveInfos.get(i);
5625            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5626                resolveInfos.remove(i);
5627            }
5628        }
5629        return resolveInfos;
5630    }
5631
5632    /**
5633     * @param resolveInfos list of resolve infos in descending priority order
5634     * @return if the list contains a resolve info with non-negative priority
5635     */
5636    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5637        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5638    }
5639
5640    private static boolean hasWebURI(Intent intent) {
5641        if (intent.getData() == null) {
5642            return false;
5643        }
5644        final String scheme = intent.getScheme();
5645        if (TextUtils.isEmpty(scheme)) {
5646            return false;
5647        }
5648        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5649    }
5650
5651    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5652            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5653            int userId) {
5654        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5655
5656        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5657            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5658                    candidates.size());
5659        }
5660
5661        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5662        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5663        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5664        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5665        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5666        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5667
5668        synchronized (mPackages) {
5669            final int count = candidates.size();
5670            // First, try to use linked apps. Partition the candidates into four lists:
5671            // one for the final results, one for the "do not use ever", one for "undefined status"
5672            // and finally one for "browser app type".
5673            for (int n=0; n<count; n++) {
5674                ResolveInfo info = candidates.get(n);
5675                String packageName = info.activityInfo.packageName;
5676                PackageSetting ps = mSettings.mPackages.get(packageName);
5677                if (ps != null) {
5678                    // Add to the special match all list (Browser use case)
5679                    if (info.handleAllWebDataURI) {
5680                        matchAllList.add(info);
5681                        continue;
5682                    }
5683                    // Try to get the status from User settings first
5684                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5685                    int status = (int)(packedStatus >> 32);
5686                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5687                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5688                        if (DEBUG_DOMAIN_VERIFICATION) {
5689                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5690                                    + " : linkgen=" + linkGeneration);
5691                        }
5692                        // Use link-enabled generation as preferredOrder, i.e.
5693                        // prefer newly-enabled over earlier-enabled.
5694                        info.preferredOrder = linkGeneration;
5695                        alwaysList.add(info);
5696                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5697                        if (DEBUG_DOMAIN_VERIFICATION) {
5698                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5699                        }
5700                        neverList.add(info);
5701                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5702                        if (DEBUG_DOMAIN_VERIFICATION) {
5703                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5704                        }
5705                        alwaysAskList.add(info);
5706                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5707                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5708                        if (DEBUG_DOMAIN_VERIFICATION) {
5709                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5710                        }
5711                        undefinedList.add(info);
5712                    }
5713                }
5714            }
5715
5716            // We'll want to include browser possibilities in a few cases
5717            boolean includeBrowser = false;
5718
5719            // First try to add the "always" resolution(s) for the current user, if any
5720            if (alwaysList.size() > 0) {
5721                result.addAll(alwaysList);
5722            } else {
5723                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5724                result.addAll(undefinedList);
5725                // Maybe add one for the other profile.
5726                if (xpDomainInfo != null && (
5727                        xpDomainInfo.bestDomainVerificationStatus
5728                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5729                    result.add(xpDomainInfo.resolveInfo);
5730                }
5731                includeBrowser = true;
5732            }
5733
5734            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5735            // If there were 'always' entries their preferred order has been set, so we also
5736            // back that off to make the alternatives equivalent
5737            if (alwaysAskList.size() > 0) {
5738                for (ResolveInfo i : result) {
5739                    i.preferredOrder = 0;
5740                }
5741                result.addAll(alwaysAskList);
5742                includeBrowser = true;
5743            }
5744
5745            if (includeBrowser) {
5746                // Also add browsers (all of them or only the default one)
5747                if (DEBUG_DOMAIN_VERIFICATION) {
5748                    Slog.v(TAG, "   ...including browsers in candidate set");
5749                }
5750                if ((matchFlags & MATCH_ALL) != 0) {
5751                    result.addAll(matchAllList);
5752                } else {
5753                    // Browser/generic handling case.  If there's a default browser, go straight
5754                    // to that (but only if there is no other higher-priority match).
5755                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5756                    int maxMatchPrio = 0;
5757                    ResolveInfo defaultBrowserMatch = null;
5758                    final int numCandidates = matchAllList.size();
5759                    for (int n = 0; n < numCandidates; n++) {
5760                        ResolveInfo info = matchAllList.get(n);
5761                        // track the highest overall match priority...
5762                        if (info.priority > maxMatchPrio) {
5763                            maxMatchPrio = info.priority;
5764                        }
5765                        // ...and the highest-priority default browser match
5766                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5767                            if (defaultBrowserMatch == null
5768                                    || (defaultBrowserMatch.priority < info.priority)) {
5769                                if (debug) {
5770                                    Slog.v(TAG, "Considering default browser match " + info);
5771                                }
5772                                defaultBrowserMatch = info;
5773                            }
5774                        }
5775                    }
5776                    if (defaultBrowserMatch != null
5777                            && defaultBrowserMatch.priority >= maxMatchPrio
5778                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5779                    {
5780                        if (debug) {
5781                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5782                        }
5783                        result.add(defaultBrowserMatch);
5784                    } else {
5785                        result.addAll(matchAllList);
5786                    }
5787                }
5788
5789                // If there is nothing selected, add all candidates and remove the ones that the user
5790                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5791                if (result.size() == 0) {
5792                    result.addAll(candidates);
5793                    result.removeAll(neverList);
5794                }
5795            }
5796        }
5797        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5798            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5799                    result.size());
5800            for (ResolveInfo info : result) {
5801                Slog.v(TAG, "  + " + info.activityInfo);
5802            }
5803        }
5804        return result;
5805    }
5806
5807    // Returns a packed value as a long:
5808    //
5809    // high 'int'-sized word: link status: undefined/ask/never/always.
5810    // low 'int'-sized word: relative priority among 'always' results.
5811    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5812        long result = ps.getDomainVerificationStatusForUser(userId);
5813        // if none available, get the master status
5814        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5815            if (ps.getIntentFilterVerificationInfo() != null) {
5816                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5817            }
5818        }
5819        return result;
5820    }
5821
5822    private ResolveInfo querySkipCurrentProfileIntents(
5823            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5824            int flags, int sourceUserId) {
5825        if (matchingFilters != null) {
5826            int size = matchingFilters.size();
5827            for (int i = 0; i < size; i ++) {
5828                CrossProfileIntentFilter filter = matchingFilters.get(i);
5829                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5830                    // Checking if there are activities in the target user that can handle the
5831                    // intent.
5832                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5833                            resolvedType, flags, sourceUserId);
5834                    if (resolveInfo != null) {
5835                        return resolveInfo;
5836                    }
5837                }
5838            }
5839        }
5840        return null;
5841    }
5842
5843    // Return matching ResolveInfo in target user if any.
5844    private ResolveInfo queryCrossProfileIntents(
5845            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5846            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5847        if (matchingFilters != null) {
5848            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5849            // match the same intent. For performance reasons, it is better not to
5850            // run queryIntent twice for the same userId
5851            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5852            int size = matchingFilters.size();
5853            for (int i = 0; i < size; i++) {
5854                CrossProfileIntentFilter filter = matchingFilters.get(i);
5855                int targetUserId = filter.getTargetUserId();
5856                boolean skipCurrentProfile =
5857                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5858                boolean skipCurrentProfileIfNoMatchFound =
5859                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5860                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5861                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5862                    // Checking if there are activities in the target user that can handle the
5863                    // intent.
5864                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5865                            resolvedType, flags, sourceUserId);
5866                    if (resolveInfo != null) return resolveInfo;
5867                    alreadyTriedUserIds.put(targetUserId, true);
5868                }
5869            }
5870        }
5871        return null;
5872    }
5873
5874    /**
5875     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5876     * will forward the intent to the filter's target user.
5877     * Otherwise, returns null.
5878     */
5879    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5880            String resolvedType, int flags, int sourceUserId) {
5881        int targetUserId = filter.getTargetUserId();
5882        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5883                resolvedType, flags, targetUserId);
5884        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5885            // If all the matches in the target profile are suspended, return null.
5886            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5887                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5888                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5889                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5890                            targetUserId);
5891                }
5892            }
5893        }
5894        return null;
5895    }
5896
5897    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5898            int sourceUserId, int targetUserId) {
5899        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5900        long ident = Binder.clearCallingIdentity();
5901        boolean targetIsProfile;
5902        try {
5903            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5904        } finally {
5905            Binder.restoreCallingIdentity(ident);
5906        }
5907        String className;
5908        if (targetIsProfile) {
5909            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5910        } else {
5911            className = FORWARD_INTENT_TO_PARENT;
5912        }
5913        ComponentName forwardingActivityComponentName = new ComponentName(
5914                mAndroidApplication.packageName, className);
5915        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5916                sourceUserId);
5917        if (!targetIsProfile) {
5918            forwardingActivityInfo.showUserIcon = targetUserId;
5919            forwardingResolveInfo.noResourceId = true;
5920        }
5921        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5922        forwardingResolveInfo.priority = 0;
5923        forwardingResolveInfo.preferredOrder = 0;
5924        forwardingResolveInfo.match = 0;
5925        forwardingResolveInfo.isDefault = true;
5926        forwardingResolveInfo.filter = filter;
5927        forwardingResolveInfo.targetUserId = targetUserId;
5928        return forwardingResolveInfo;
5929    }
5930
5931    @Override
5932    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5933            Intent[] specifics, String[] specificTypes, Intent intent,
5934            String resolvedType, int flags, int userId) {
5935        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5936                specificTypes, intent, resolvedType, flags, userId));
5937    }
5938
5939    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5940            Intent[] specifics, String[] specificTypes, Intent intent,
5941            String resolvedType, int flags, int userId) {
5942        if (!sUserManager.exists(userId)) return Collections.emptyList();
5943        flags = updateFlagsForResolve(flags, userId, intent);
5944        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5945                false /* requireFullPermission */, false /* checkShell */,
5946                "query intent activity options");
5947        final String resultsAction = intent.getAction();
5948
5949        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5950                | PackageManager.GET_RESOLVED_FILTER, userId);
5951
5952        if (DEBUG_INTENT_MATCHING) {
5953            Log.v(TAG, "Query " + intent + ": " + results);
5954        }
5955
5956        int specificsPos = 0;
5957        int N;
5958
5959        // todo: note that the algorithm used here is O(N^2).  This
5960        // isn't a problem in our current environment, but if we start running
5961        // into situations where we have more than 5 or 10 matches then this
5962        // should probably be changed to something smarter...
5963
5964        // First we go through and resolve each of the specific items
5965        // that were supplied, taking care of removing any corresponding
5966        // duplicate items in the generic resolve list.
5967        if (specifics != null) {
5968            for (int i=0; i<specifics.length; i++) {
5969                final Intent sintent = specifics[i];
5970                if (sintent == null) {
5971                    continue;
5972                }
5973
5974                if (DEBUG_INTENT_MATCHING) {
5975                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5976                }
5977
5978                String action = sintent.getAction();
5979                if (resultsAction != null && resultsAction.equals(action)) {
5980                    // If this action was explicitly requested, then don't
5981                    // remove things that have it.
5982                    action = null;
5983                }
5984
5985                ResolveInfo ri = null;
5986                ActivityInfo ai = null;
5987
5988                ComponentName comp = sintent.getComponent();
5989                if (comp == null) {
5990                    ri = resolveIntent(
5991                        sintent,
5992                        specificTypes != null ? specificTypes[i] : null,
5993                            flags, userId);
5994                    if (ri == null) {
5995                        continue;
5996                    }
5997                    if (ri == mResolveInfo) {
5998                        // ACK!  Must do something better with this.
5999                    }
6000                    ai = ri.activityInfo;
6001                    comp = new ComponentName(ai.applicationInfo.packageName,
6002                            ai.name);
6003                } else {
6004                    ai = getActivityInfo(comp, flags, userId);
6005                    if (ai == null) {
6006                        continue;
6007                    }
6008                }
6009
6010                // Look for any generic query activities that are duplicates
6011                // of this specific one, and remove them from the results.
6012                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6013                N = results.size();
6014                int j;
6015                for (j=specificsPos; j<N; j++) {
6016                    ResolveInfo sri = results.get(j);
6017                    if ((sri.activityInfo.name.equals(comp.getClassName())
6018                            && sri.activityInfo.applicationInfo.packageName.equals(
6019                                    comp.getPackageName()))
6020                        || (action != null && sri.filter.matchAction(action))) {
6021                        results.remove(j);
6022                        if (DEBUG_INTENT_MATCHING) Log.v(
6023                            TAG, "Removing duplicate item from " + j
6024                            + " due to specific " + specificsPos);
6025                        if (ri == null) {
6026                            ri = sri;
6027                        }
6028                        j--;
6029                        N--;
6030                    }
6031                }
6032
6033                // Add this specific item to its proper place.
6034                if (ri == null) {
6035                    ri = new ResolveInfo();
6036                    ri.activityInfo = ai;
6037                }
6038                results.add(specificsPos, ri);
6039                ri.specificIndex = i;
6040                specificsPos++;
6041            }
6042        }
6043
6044        // Now we go through the remaining generic results and remove any
6045        // duplicate actions that are found here.
6046        N = results.size();
6047        for (int i=specificsPos; i<N-1; i++) {
6048            final ResolveInfo rii = results.get(i);
6049            if (rii.filter == null) {
6050                continue;
6051            }
6052
6053            // Iterate over all of the actions of this result's intent
6054            // filter...  typically this should be just one.
6055            final Iterator<String> it = rii.filter.actionsIterator();
6056            if (it == null) {
6057                continue;
6058            }
6059            while (it.hasNext()) {
6060                final String action = it.next();
6061                if (resultsAction != null && resultsAction.equals(action)) {
6062                    // If this action was explicitly requested, then don't
6063                    // remove things that have it.
6064                    continue;
6065                }
6066                for (int j=i+1; j<N; j++) {
6067                    final ResolveInfo rij = results.get(j);
6068                    if (rij.filter != null && rij.filter.hasAction(action)) {
6069                        results.remove(j);
6070                        if (DEBUG_INTENT_MATCHING) Log.v(
6071                            TAG, "Removing duplicate item from " + j
6072                            + " due to action " + action + " at " + i);
6073                        j--;
6074                        N--;
6075                    }
6076                }
6077            }
6078
6079            // If the caller didn't request filter information, drop it now
6080            // so we don't have to marshall/unmarshall it.
6081            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6082                rii.filter = null;
6083            }
6084        }
6085
6086        // Filter out the caller activity if so requested.
6087        if (caller != null) {
6088            N = results.size();
6089            for (int i=0; i<N; i++) {
6090                ActivityInfo ainfo = results.get(i).activityInfo;
6091                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6092                        && caller.getClassName().equals(ainfo.name)) {
6093                    results.remove(i);
6094                    break;
6095                }
6096            }
6097        }
6098
6099        // If the caller didn't request filter information,
6100        // drop them now so we don't have to
6101        // marshall/unmarshall it.
6102        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6103            N = results.size();
6104            for (int i=0; i<N; i++) {
6105                results.get(i).filter = null;
6106            }
6107        }
6108
6109        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6110        return results;
6111    }
6112
6113    @Override
6114    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6115            String resolvedType, int flags, int userId) {
6116        return new ParceledListSlice<>(
6117                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6118    }
6119
6120    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6121            String resolvedType, int flags, int userId) {
6122        if (!sUserManager.exists(userId)) return Collections.emptyList();
6123        flags = updateFlagsForResolve(flags, userId, intent);
6124        ComponentName comp = intent.getComponent();
6125        if (comp == null) {
6126            if (intent.getSelector() != null) {
6127                intent = intent.getSelector();
6128                comp = intent.getComponent();
6129            }
6130        }
6131        if (comp != null) {
6132            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6133            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6134            if (ai != null) {
6135                ResolveInfo ri = new ResolveInfo();
6136                ri.activityInfo = ai;
6137                list.add(ri);
6138            }
6139            return list;
6140        }
6141
6142        // reader
6143        synchronized (mPackages) {
6144            String pkgName = intent.getPackage();
6145            if (pkgName == null) {
6146                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6147            }
6148            final PackageParser.Package pkg = mPackages.get(pkgName);
6149            if (pkg != null) {
6150                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6151                        userId);
6152            }
6153            return Collections.emptyList();
6154        }
6155    }
6156
6157    @Override
6158    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6159        if (!sUserManager.exists(userId)) return null;
6160        flags = updateFlagsForResolve(flags, userId, intent);
6161        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6162        if (query != null) {
6163            if (query.size() >= 1) {
6164                // If there is more than one service with the same priority,
6165                // just arbitrarily pick the first one.
6166                return query.get(0);
6167            }
6168        }
6169        return null;
6170    }
6171
6172    @Override
6173    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6174            String resolvedType, int flags, int userId) {
6175        return new ParceledListSlice<>(
6176                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6177    }
6178
6179    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6180            String resolvedType, int flags, int userId) {
6181        if (!sUserManager.exists(userId)) return Collections.emptyList();
6182        flags = updateFlagsForResolve(flags, userId, intent);
6183        ComponentName comp = intent.getComponent();
6184        if (comp == null) {
6185            if (intent.getSelector() != null) {
6186                intent = intent.getSelector();
6187                comp = intent.getComponent();
6188            }
6189        }
6190        if (comp != null) {
6191            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6192            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6193            if (si != null) {
6194                final ResolveInfo ri = new ResolveInfo();
6195                ri.serviceInfo = si;
6196                list.add(ri);
6197            }
6198            return list;
6199        }
6200
6201        // reader
6202        synchronized (mPackages) {
6203            String pkgName = intent.getPackage();
6204            if (pkgName == null) {
6205                return mServices.queryIntent(intent, resolvedType, flags, userId);
6206            }
6207            final PackageParser.Package pkg = mPackages.get(pkgName);
6208            if (pkg != null) {
6209                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6210                        userId);
6211            }
6212            return Collections.emptyList();
6213        }
6214    }
6215
6216    @Override
6217    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6218            String resolvedType, int flags, int userId) {
6219        return new ParceledListSlice<>(
6220                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6221    }
6222
6223    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6224            Intent intent, String resolvedType, int flags, int userId) {
6225        if (!sUserManager.exists(userId)) return Collections.emptyList();
6226        flags = updateFlagsForResolve(flags, userId, intent);
6227        ComponentName comp = intent.getComponent();
6228        if (comp == null) {
6229            if (intent.getSelector() != null) {
6230                intent = intent.getSelector();
6231                comp = intent.getComponent();
6232            }
6233        }
6234        if (comp != null) {
6235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6236            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6237            if (pi != null) {
6238                final ResolveInfo ri = new ResolveInfo();
6239                ri.providerInfo = pi;
6240                list.add(ri);
6241            }
6242            return list;
6243        }
6244
6245        // reader
6246        synchronized (mPackages) {
6247            String pkgName = intent.getPackage();
6248            if (pkgName == null) {
6249                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6250            }
6251            final PackageParser.Package pkg = mPackages.get(pkgName);
6252            if (pkg != null) {
6253                return mProviders.queryIntentForPackage(
6254                        intent, resolvedType, flags, pkg.providers, userId);
6255            }
6256            return Collections.emptyList();
6257        }
6258    }
6259
6260    @Override
6261    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6262        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6263        flags = updateFlagsForPackage(flags, userId, null);
6264        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6265        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6266                true /* requireFullPermission */, false /* checkShell */,
6267                "get installed packages");
6268
6269        // writer
6270        synchronized (mPackages) {
6271            ArrayList<PackageInfo> list;
6272            if (listUninstalled) {
6273                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6274                for (PackageSetting ps : mSettings.mPackages.values()) {
6275                    final PackageInfo pi;
6276                    if (ps.pkg != null) {
6277                        pi = generatePackageInfo(ps, flags, userId);
6278                    } else {
6279                        pi = generatePackageInfo(ps, flags, userId);
6280                    }
6281                    if (pi != null) {
6282                        list.add(pi);
6283                    }
6284                }
6285            } else {
6286                list = new ArrayList<PackageInfo>(mPackages.size());
6287                for (PackageParser.Package p : mPackages.values()) {
6288                    final PackageInfo pi =
6289                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6290                    if (pi != null) {
6291                        list.add(pi);
6292                    }
6293                }
6294            }
6295
6296            return new ParceledListSlice<PackageInfo>(list);
6297        }
6298    }
6299
6300    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6301            String[] permissions, boolean[] tmp, int flags, int userId) {
6302        int numMatch = 0;
6303        final PermissionsState permissionsState = ps.getPermissionsState();
6304        for (int i=0; i<permissions.length; i++) {
6305            final String permission = permissions[i];
6306            if (permissionsState.hasPermission(permission, userId)) {
6307                tmp[i] = true;
6308                numMatch++;
6309            } else {
6310                tmp[i] = false;
6311            }
6312        }
6313        if (numMatch == 0) {
6314            return;
6315        }
6316        final PackageInfo pi;
6317        if (ps.pkg != null) {
6318            pi = generatePackageInfo(ps, flags, userId);
6319        } else {
6320            pi = generatePackageInfo(ps, flags, userId);
6321        }
6322        // The above might return null in cases of uninstalled apps or install-state
6323        // skew across users/profiles.
6324        if (pi != null) {
6325            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6326                if (numMatch == permissions.length) {
6327                    pi.requestedPermissions = permissions;
6328                } else {
6329                    pi.requestedPermissions = new String[numMatch];
6330                    numMatch = 0;
6331                    for (int i=0; i<permissions.length; i++) {
6332                        if (tmp[i]) {
6333                            pi.requestedPermissions[numMatch] = permissions[i];
6334                            numMatch++;
6335                        }
6336                    }
6337                }
6338            }
6339            list.add(pi);
6340        }
6341    }
6342
6343    @Override
6344    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6345            String[] permissions, int flags, int userId) {
6346        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6347        flags = updateFlagsForPackage(flags, userId, permissions);
6348        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6349
6350        // writer
6351        synchronized (mPackages) {
6352            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6353            boolean[] tmpBools = new boolean[permissions.length];
6354            if (listUninstalled) {
6355                for (PackageSetting ps : mSettings.mPackages.values()) {
6356                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6357                }
6358            } else {
6359                for (PackageParser.Package pkg : mPackages.values()) {
6360                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6361                    if (ps != null) {
6362                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6363                                userId);
6364                    }
6365                }
6366            }
6367
6368            return new ParceledListSlice<PackageInfo>(list);
6369        }
6370    }
6371
6372    @Override
6373    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6374        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6375        flags = updateFlagsForApplication(flags, userId, null);
6376        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6377
6378        // writer
6379        synchronized (mPackages) {
6380            ArrayList<ApplicationInfo> list;
6381            if (listUninstalled) {
6382                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6383                for (PackageSetting ps : mSettings.mPackages.values()) {
6384                    ApplicationInfo ai;
6385                    if (ps.pkg != null) {
6386                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6387                                ps.readUserState(userId), userId);
6388                    } else {
6389                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6390                    }
6391                    if (ai != null) {
6392                        list.add(ai);
6393                    }
6394                }
6395            } else {
6396                list = new ArrayList<ApplicationInfo>(mPackages.size());
6397                for (PackageParser.Package p : mPackages.values()) {
6398                    if (p.mExtras != null) {
6399                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6400                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6401                        if (ai != null) {
6402                            list.add(ai);
6403                        }
6404                    }
6405                }
6406            }
6407
6408            return new ParceledListSlice<ApplicationInfo>(list);
6409        }
6410    }
6411
6412    @Override
6413    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6414        if (DISABLE_EPHEMERAL_APPS) {
6415            return null;
6416        }
6417
6418        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6419                "getEphemeralApplications");
6420        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6421                true /* requireFullPermission */, false /* checkShell */,
6422                "getEphemeralApplications");
6423        synchronized (mPackages) {
6424            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6425                    .getEphemeralApplicationsLPw(userId);
6426            if (ephemeralApps != null) {
6427                return new ParceledListSlice<>(ephemeralApps);
6428            }
6429        }
6430        return null;
6431    }
6432
6433    @Override
6434    public boolean isEphemeralApplication(String packageName, int userId) {
6435        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6436                true /* requireFullPermission */, false /* checkShell */,
6437                "isEphemeral");
6438        if (DISABLE_EPHEMERAL_APPS) {
6439            return false;
6440        }
6441
6442        if (!isCallerSameApp(packageName)) {
6443            return false;
6444        }
6445        synchronized (mPackages) {
6446            PackageParser.Package pkg = mPackages.get(packageName);
6447            if (pkg != null) {
6448                return pkg.applicationInfo.isEphemeralApp();
6449            }
6450        }
6451        return false;
6452    }
6453
6454    @Override
6455    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6456        if (DISABLE_EPHEMERAL_APPS) {
6457            return null;
6458        }
6459
6460        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6461                true /* requireFullPermission */, false /* checkShell */,
6462                "getCookie");
6463        if (!isCallerSameApp(packageName)) {
6464            return null;
6465        }
6466        synchronized (mPackages) {
6467            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6468                    packageName, userId);
6469        }
6470    }
6471
6472    @Override
6473    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6474        if (DISABLE_EPHEMERAL_APPS) {
6475            return true;
6476        }
6477
6478        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6479                true /* requireFullPermission */, true /* checkShell */,
6480                "setCookie");
6481        if (!isCallerSameApp(packageName)) {
6482            return false;
6483        }
6484        synchronized (mPackages) {
6485            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6486                    packageName, cookie, userId);
6487        }
6488    }
6489
6490    @Override
6491    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6492        if (DISABLE_EPHEMERAL_APPS) {
6493            return null;
6494        }
6495
6496        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6497                "getEphemeralApplicationIcon");
6498        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6499                true /* requireFullPermission */, false /* checkShell */,
6500                "getEphemeralApplicationIcon");
6501        synchronized (mPackages) {
6502            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6503                    packageName, userId);
6504        }
6505    }
6506
6507    private boolean isCallerSameApp(String packageName) {
6508        PackageParser.Package pkg = mPackages.get(packageName);
6509        return pkg != null
6510                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6511    }
6512
6513    @Override
6514    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6515        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6516    }
6517
6518    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6519        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6520
6521        // reader
6522        synchronized (mPackages) {
6523            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6524            final int userId = UserHandle.getCallingUserId();
6525            while (i.hasNext()) {
6526                final PackageParser.Package p = i.next();
6527                if (p.applicationInfo == null) continue;
6528
6529                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6530                        && !p.applicationInfo.isDirectBootAware();
6531                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6532                        && p.applicationInfo.isDirectBootAware();
6533
6534                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6535                        && (!mSafeMode || isSystemApp(p))
6536                        && (matchesUnaware || matchesAware)) {
6537                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6538                    if (ps != null) {
6539                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6540                                ps.readUserState(userId), userId);
6541                        if (ai != null) {
6542                            finalList.add(ai);
6543                        }
6544                    }
6545                }
6546            }
6547        }
6548
6549        return finalList;
6550    }
6551
6552    @Override
6553    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6554        if (!sUserManager.exists(userId)) return null;
6555        flags = updateFlagsForComponent(flags, userId, name);
6556        // reader
6557        synchronized (mPackages) {
6558            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6559            PackageSetting ps = provider != null
6560                    ? mSettings.mPackages.get(provider.owner.packageName)
6561                    : null;
6562            return ps != null
6563                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6564                    ? PackageParser.generateProviderInfo(provider, flags,
6565                            ps.readUserState(userId), userId)
6566                    : null;
6567        }
6568    }
6569
6570    /**
6571     * @deprecated
6572     */
6573    @Deprecated
6574    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6575        // reader
6576        synchronized (mPackages) {
6577            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6578                    .entrySet().iterator();
6579            final int userId = UserHandle.getCallingUserId();
6580            while (i.hasNext()) {
6581                Map.Entry<String, PackageParser.Provider> entry = i.next();
6582                PackageParser.Provider p = entry.getValue();
6583                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6584
6585                if (ps != null && p.syncable
6586                        && (!mSafeMode || (p.info.applicationInfo.flags
6587                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6588                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6589                            ps.readUserState(userId), userId);
6590                    if (info != null) {
6591                        outNames.add(entry.getKey());
6592                        outInfo.add(info);
6593                    }
6594                }
6595            }
6596        }
6597    }
6598
6599    @Override
6600    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6601            int uid, int flags) {
6602        final int userId = processName != null ? UserHandle.getUserId(uid)
6603                : UserHandle.getCallingUserId();
6604        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6605        flags = updateFlagsForComponent(flags, userId, processName);
6606
6607        ArrayList<ProviderInfo> finalList = null;
6608        // reader
6609        synchronized (mPackages) {
6610            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6611            while (i.hasNext()) {
6612                final PackageParser.Provider p = i.next();
6613                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6614                if (ps != null && p.info.authority != null
6615                        && (processName == null
6616                                || (p.info.processName.equals(processName)
6617                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6618                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6619                    if (finalList == null) {
6620                        finalList = new ArrayList<ProviderInfo>(3);
6621                    }
6622                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6623                            ps.readUserState(userId), userId);
6624                    if (info != null) {
6625                        finalList.add(info);
6626                    }
6627                }
6628            }
6629        }
6630
6631        if (finalList != null) {
6632            Collections.sort(finalList, mProviderInitOrderSorter);
6633            return new ParceledListSlice<ProviderInfo>(finalList);
6634        }
6635
6636        return ParceledListSlice.emptyList();
6637    }
6638
6639    @Override
6640    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6641        // reader
6642        synchronized (mPackages) {
6643            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6644            return PackageParser.generateInstrumentationInfo(i, flags);
6645        }
6646    }
6647
6648    @Override
6649    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6650            String targetPackage, int flags) {
6651        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6652    }
6653
6654    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6655            int flags) {
6656        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6657
6658        // reader
6659        synchronized (mPackages) {
6660            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6661            while (i.hasNext()) {
6662                final PackageParser.Instrumentation p = i.next();
6663                if (targetPackage == null
6664                        || targetPackage.equals(p.info.targetPackage)) {
6665                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6666                            flags);
6667                    if (ii != null) {
6668                        finalList.add(ii);
6669                    }
6670                }
6671            }
6672        }
6673
6674        return finalList;
6675    }
6676
6677    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6678        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6679        if (overlays == null) {
6680            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6681            return;
6682        }
6683        for (PackageParser.Package opkg : overlays.values()) {
6684            // Not much to do if idmap fails: we already logged the error
6685            // and we certainly don't want to abort installation of pkg simply
6686            // because an overlay didn't fit properly. For these reasons,
6687            // ignore the return value of createIdmapForPackagePairLI.
6688            createIdmapForPackagePairLI(pkg, opkg);
6689        }
6690    }
6691
6692    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6693            PackageParser.Package opkg) {
6694        if (!opkg.mTrustedOverlay) {
6695            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6696                    opkg.baseCodePath + ": overlay not trusted");
6697            return false;
6698        }
6699        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6700        if (overlaySet == null) {
6701            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6702                    opkg.baseCodePath + " but target package has no known overlays");
6703            return false;
6704        }
6705        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6706        // TODO: generate idmap for split APKs
6707        try {
6708            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6709        } catch (InstallerException e) {
6710            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6711                    + opkg.baseCodePath);
6712            return false;
6713        }
6714        PackageParser.Package[] overlayArray =
6715            overlaySet.values().toArray(new PackageParser.Package[0]);
6716        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6717            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6718                return p1.mOverlayPriority - p2.mOverlayPriority;
6719            }
6720        };
6721        Arrays.sort(overlayArray, cmp);
6722
6723        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6724        int i = 0;
6725        for (PackageParser.Package p : overlayArray) {
6726            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6727        }
6728        return true;
6729    }
6730
6731    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6732        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6733        try {
6734            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6735        } finally {
6736            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6737        }
6738    }
6739
6740    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6741        final File[] files = dir.listFiles();
6742        if (ArrayUtils.isEmpty(files)) {
6743            Log.d(TAG, "No files in app dir " + dir);
6744            return;
6745        }
6746
6747        if (DEBUG_PACKAGE_SCANNING) {
6748            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6749                    + " flags=0x" + Integer.toHexString(parseFlags));
6750        }
6751
6752        for (File file : files) {
6753            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6754                    && !PackageInstallerService.isStageName(file.getName());
6755            if (!isPackage) {
6756                // Ignore entries which are not packages
6757                continue;
6758            }
6759            try {
6760                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6761                        scanFlags, currentTime, null);
6762            } catch (PackageManagerException e) {
6763                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6764
6765                // Delete invalid userdata apps
6766                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6767                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6768                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6769                    removeCodePathLI(file);
6770                }
6771            }
6772        }
6773    }
6774
6775    private static File getSettingsProblemFile() {
6776        File dataDir = Environment.getDataDirectory();
6777        File systemDir = new File(dataDir, "system");
6778        File fname = new File(systemDir, "uiderrors.txt");
6779        return fname;
6780    }
6781
6782    static void reportSettingsProblem(int priority, String msg) {
6783        logCriticalInfo(priority, msg);
6784    }
6785
6786    static void logCriticalInfo(int priority, String msg) {
6787        Slog.println(priority, TAG, msg);
6788        EventLogTags.writePmCriticalInfo(msg);
6789        try {
6790            File fname = getSettingsProblemFile();
6791            FileOutputStream out = new FileOutputStream(fname, true);
6792            PrintWriter pw = new FastPrintWriter(out);
6793            SimpleDateFormat formatter = new SimpleDateFormat();
6794            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6795            pw.println(dateString + ": " + msg);
6796            pw.close();
6797            FileUtils.setPermissions(
6798                    fname.toString(),
6799                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6800                    -1, -1);
6801        } catch (java.io.IOException e) {
6802        }
6803    }
6804
6805    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6806        if (srcFile.isDirectory()) {
6807            final File baseFile = new File(pkg.baseCodePath);
6808            long maxModifiedTime = baseFile.lastModified();
6809            if (pkg.splitCodePaths != null) {
6810                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6811                    final File splitFile = new File(pkg.splitCodePaths[i]);
6812                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6813                }
6814            }
6815            return maxModifiedTime;
6816        }
6817        return srcFile.lastModified();
6818    }
6819
6820    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6821            final int policyFlags) throws PackageManagerException {
6822        if (ps != null
6823                && ps.codePath.equals(srcFile)
6824                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6825                && !isCompatSignatureUpdateNeeded(pkg)
6826                && !isRecoverSignatureUpdateNeeded(pkg)) {
6827            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6828            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6829            ArraySet<PublicKey> signingKs;
6830            synchronized (mPackages) {
6831                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6832            }
6833            if (ps.signatures.mSignatures != null
6834                    && ps.signatures.mSignatures.length != 0
6835                    && signingKs != null) {
6836                // Optimization: reuse the existing cached certificates
6837                // if the package appears to be unchanged.
6838                pkg.mSignatures = ps.signatures.mSignatures;
6839                pkg.mSigningKeys = signingKs;
6840                return;
6841            }
6842
6843            Slog.w(TAG, "PackageSetting for " + ps.name
6844                    + " is missing signatures.  Collecting certs again to recover them.");
6845        } else {
6846            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6847        }
6848
6849        try {
6850            PackageParser.collectCertificates(pkg, policyFlags);
6851        } catch (PackageParserException e) {
6852            throw PackageManagerException.from(e);
6853        }
6854    }
6855
6856    /**
6857     *  Traces a package scan.
6858     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6859     */
6860    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6861            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6862        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6863        try {
6864            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6865        } finally {
6866            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6867        }
6868    }
6869
6870    /**
6871     *  Scans a package and returns the newly parsed package.
6872     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6873     */
6874    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6875            long currentTime, UserHandle user) throws PackageManagerException {
6876        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6877        PackageParser pp = new PackageParser();
6878        pp.setSeparateProcesses(mSeparateProcesses);
6879        pp.setOnlyCoreApps(mOnlyCore);
6880        pp.setDisplayMetrics(mMetrics);
6881
6882        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6883            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6884        }
6885
6886        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6887        final PackageParser.Package pkg;
6888        try {
6889            pkg = pp.parsePackage(scanFile, parseFlags);
6890        } catch (PackageParserException e) {
6891            throw PackageManagerException.from(e);
6892        } finally {
6893            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6894        }
6895
6896        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6897    }
6898
6899    /**
6900     *  Scans a package and returns the newly parsed package.
6901     *  @throws PackageManagerException on a parse error.
6902     */
6903    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6904            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6905            throws PackageManagerException {
6906        // If the package has children and this is the first dive in the function
6907        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6908        // packages (parent and children) would be successfully scanned before the
6909        // actual scan since scanning mutates internal state and we want to atomically
6910        // install the package and its children.
6911        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6912            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6913                scanFlags |= SCAN_CHECK_ONLY;
6914            }
6915        } else {
6916            scanFlags &= ~SCAN_CHECK_ONLY;
6917        }
6918
6919        // Scan the parent
6920        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6921                scanFlags, currentTime, user);
6922
6923        // Scan the children
6924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6925        for (int i = 0; i < childCount; i++) {
6926            PackageParser.Package childPackage = pkg.childPackages.get(i);
6927            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6928                    currentTime, user);
6929        }
6930
6931
6932        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6933            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6934        }
6935
6936        return scannedPkg;
6937    }
6938
6939    /**
6940     *  Scans a package and returns the newly parsed package.
6941     *  @throws PackageManagerException on a parse error.
6942     */
6943    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6944            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6945            throws PackageManagerException {
6946        PackageSetting ps = null;
6947        PackageSetting updatedPkg;
6948        // reader
6949        synchronized (mPackages) {
6950            // Look to see if we already know about this package.
6951            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6952            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6953                // This package has been renamed to its original name.  Let's
6954                // use that.
6955                ps = mSettings.peekPackageLPr(oldName);
6956            }
6957            // If there was no original package, see one for the real package name.
6958            if (ps == null) {
6959                ps = mSettings.peekPackageLPr(pkg.packageName);
6960            }
6961            // Check to see if this package could be hiding/updating a system
6962            // package.  Must look for it either under the original or real
6963            // package name depending on our state.
6964            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6965            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6966
6967            // If this is a package we don't know about on the system partition, we
6968            // may need to remove disabled child packages on the system partition
6969            // or may need to not add child packages if the parent apk is updated
6970            // on the data partition and no longer defines this child package.
6971            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6972                // If this is a parent package for an updated system app and this system
6973                // app got an OTA update which no longer defines some of the child packages
6974                // we have to prune them from the disabled system packages.
6975                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6976                if (disabledPs != null) {
6977                    final int scannedChildCount = (pkg.childPackages != null)
6978                            ? pkg.childPackages.size() : 0;
6979                    final int disabledChildCount = disabledPs.childPackageNames != null
6980                            ? disabledPs.childPackageNames.size() : 0;
6981                    for (int i = 0; i < disabledChildCount; i++) {
6982                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6983                        boolean disabledPackageAvailable = false;
6984                        for (int j = 0; j < scannedChildCount; j++) {
6985                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6986                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6987                                disabledPackageAvailable = true;
6988                                break;
6989                            }
6990                         }
6991                         if (!disabledPackageAvailable) {
6992                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6993                         }
6994                    }
6995                }
6996            }
6997        }
6998
6999        boolean updatedPkgBetter = false;
7000        // First check if this is a system package that may involve an update
7001        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7002            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7003            // it needs to drop FLAG_PRIVILEGED.
7004            if (locationIsPrivileged(scanFile)) {
7005                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7006            } else {
7007                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7008            }
7009
7010            if (ps != null && !ps.codePath.equals(scanFile)) {
7011                // The path has changed from what was last scanned...  check the
7012                // version of the new path against what we have stored to determine
7013                // what to do.
7014                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7015                if (pkg.mVersionCode <= ps.versionCode) {
7016                    // The system package has been updated and the code path does not match
7017                    // Ignore entry. Skip it.
7018                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7019                            + " ignored: updated version " + ps.versionCode
7020                            + " better than this " + pkg.mVersionCode);
7021                    if (!updatedPkg.codePath.equals(scanFile)) {
7022                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7023                                + ps.name + " changing from " + updatedPkg.codePathString
7024                                + " to " + scanFile);
7025                        updatedPkg.codePath = scanFile;
7026                        updatedPkg.codePathString = scanFile.toString();
7027                        updatedPkg.resourcePath = scanFile;
7028                        updatedPkg.resourcePathString = scanFile.toString();
7029                    }
7030                    updatedPkg.pkg = pkg;
7031                    updatedPkg.versionCode = pkg.mVersionCode;
7032
7033                    // Update the disabled system child packages to point to the package too.
7034                    final int childCount = updatedPkg.childPackageNames != null
7035                            ? updatedPkg.childPackageNames.size() : 0;
7036                    for (int i = 0; i < childCount; i++) {
7037                        String childPackageName = updatedPkg.childPackageNames.get(i);
7038                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7039                                childPackageName);
7040                        if (updatedChildPkg != null) {
7041                            updatedChildPkg.pkg = pkg;
7042                            updatedChildPkg.versionCode = pkg.mVersionCode;
7043                        }
7044                    }
7045
7046                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7047                            + scanFile + " ignored: updated version " + ps.versionCode
7048                            + " better than this " + pkg.mVersionCode);
7049                } else {
7050                    // The current app on the system partition is better than
7051                    // what we have updated to on the data partition; switch
7052                    // back to the system partition version.
7053                    // At this point, its safely assumed that package installation for
7054                    // apps in system partition will go through. If not there won't be a working
7055                    // version of the app
7056                    // writer
7057                    synchronized (mPackages) {
7058                        // Just remove the loaded entries from package lists.
7059                        mPackages.remove(ps.name);
7060                    }
7061
7062                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7063                            + " reverting from " + ps.codePathString
7064                            + ": new version " + pkg.mVersionCode
7065                            + " better than installed " + ps.versionCode);
7066
7067                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7068                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7069                    synchronized (mInstallLock) {
7070                        args.cleanUpResourcesLI();
7071                    }
7072                    synchronized (mPackages) {
7073                        mSettings.enableSystemPackageLPw(ps.name);
7074                    }
7075                    updatedPkgBetter = true;
7076                }
7077            }
7078        }
7079
7080        if (updatedPkg != null) {
7081            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7082            // initially
7083            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7084
7085            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7086            // flag set initially
7087            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7088                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7089            }
7090        }
7091
7092        // Verify certificates against what was last scanned
7093        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7094
7095        /*
7096         * A new system app appeared, but we already had a non-system one of the
7097         * same name installed earlier.
7098         */
7099        boolean shouldHideSystemApp = false;
7100        if (updatedPkg == null && ps != null
7101                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7102            /*
7103             * Check to make sure the signatures match first. If they don't,
7104             * wipe the installed application and its data.
7105             */
7106            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7107                    != PackageManager.SIGNATURE_MATCH) {
7108                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7109                        + " signatures don't match existing userdata copy; removing");
7110                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7111                        "scanPackageInternalLI")) {
7112                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7113                }
7114                ps = null;
7115            } else {
7116                /*
7117                 * If the newly-added system app is an older version than the
7118                 * already installed version, hide it. It will be scanned later
7119                 * and re-added like an update.
7120                 */
7121                if (pkg.mVersionCode <= ps.versionCode) {
7122                    shouldHideSystemApp = true;
7123                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7124                            + " but new version " + pkg.mVersionCode + " better than installed "
7125                            + ps.versionCode + "; hiding system");
7126                } else {
7127                    /*
7128                     * The newly found system app is a newer version that the
7129                     * one previously installed. Simply remove the
7130                     * already-installed application and replace it with our own
7131                     * while keeping the application data.
7132                     */
7133                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7134                            + " reverting from " + ps.codePathString + ": new version "
7135                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7136                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7137                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7138                    synchronized (mInstallLock) {
7139                        args.cleanUpResourcesLI();
7140                    }
7141                }
7142            }
7143        }
7144
7145        // The apk is forward locked (not public) if its code and resources
7146        // are kept in different files. (except for app in either system or
7147        // vendor path).
7148        // TODO grab this value from PackageSettings
7149        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7150            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7151                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7152            }
7153        }
7154
7155        // TODO: extend to support forward-locked splits
7156        String resourcePath = null;
7157        String baseResourcePath = null;
7158        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7159            if (ps != null && ps.resourcePathString != null) {
7160                resourcePath = ps.resourcePathString;
7161                baseResourcePath = ps.resourcePathString;
7162            } else {
7163                // Should not happen at all. Just log an error.
7164                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7165            }
7166        } else {
7167            resourcePath = pkg.codePath;
7168            baseResourcePath = pkg.baseCodePath;
7169        }
7170
7171        // Set application objects path explicitly.
7172        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7173        pkg.setApplicationInfoCodePath(pkg.codePath);
7174        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7175        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7176        pkg.setApplicationInfoResourcePath(resourcePath);
7177        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7178        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7179
7180        // Note that we invoke the following method only if we are about to unpack an application
7181        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7182                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7183
7184        /*
7185         * If the system app should be overridden by a previously installed
7186         * data, hide the system app now and let the /data/app scan pick it up
7187         * again.
7188         */
7189        if (shouldHideSystemApp) {
7190            synchronized (mPackages) {
7191                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7192            }
7193        }
7194
7195        return scannedPkg;
7196    }
7197
7198    private static String fixProcessName(String defProcessName,
7199            String processName, int uid) {
7200        if (processName == null) {
7201            return defProcessName;
7202        }
7203        return processName;
7204    }
7205
7206    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7207            throws PackageManagerException {
7208        if (pkgSetting.signatures.mSignatures != null) {
7209            // Already existing package. Make sure signatures match
7210            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7211                    == PackageManager.SIGNATURE_MATCH;
7212            if (!match) {
7213                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7214                        == PackageManager.SIGNATURE_MATCH;
7215            }
7216            if (!match) {
7217                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7218                        == PackageManager.SIGNATURE_MATCH;
7219            }
7220            if (!match) {
7221                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7222                        + pkg.packageName + " signatures do not match the "
7223                        + "previously installed version; ignoring!");
7224            }
7225        }
7226
7227        // Check for shared user signatures
7228        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7229            // Already existing package. Make sure signatures match
7230            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7231                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7232            if (!match) {
7233                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7234                        == PackageManager.SIGNATURE_MATCH;
7235            }
7236            if (!match) {
7237                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7238                        == PackageManager.SIGNATURE_MATCH;
7239            }
7240            if (!match) {
7241                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7242                        "Package " + pkg.packageName
7243                        + " has no signatures that match those in shared user "
7244                        + pkgSetting.sharedUser.name + "; ignoring!");
7245            }
7246        }
7247    }
7248
7249    /**
7250     * Enforces that only the system UID or root's UID can call a method exposed
7251     * via Binder.
7252     *
7253     * @param message used as message if SecurityException is thrown
7254     * @throws SecurityException if the caller is not system or root
7255     */
7256    private static final void enforceSystemOrRoot(String message) {
7257        final int uid = Binder.getCallingUid();
7258        if (uid != Process.SYSTEM_UID && uid != 0) {
7259            throw new SecurityException(message);
7260        }
7261    }
7262
7263    @Override
7264    public void performFstrimIfNeeded() {
7265        enforceSystemOrRoot("Only the system can request fstrim");
7266
7267        // Before everything else, see whether we need to fstrim.
7268        try {
7269            IMountService ms = PackageHelper.getMountService();
7270            if (ms != null) {
7271                final boolean isUpgrade = isUpgrade();
7272                boolean doTrim = isUpgrade;
7273                if (doTrim) {
7274                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7275                } else {
7276                    final long interval = android.provider.Settings.Global.getLong(
7277                            mContext.getContentResolver(),
7278                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7279                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7280                    if (interval > 0) {
7281                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7282                        if (timeSinceLast > interval) {
7283                            doTrim = true;
7284                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7285                                    + "; running immediately");
7286                        }
7287                    }
7288                }
7289                if (doTrim) {
7290                    if (!isFirstBoot()) {
7291                        try {
7292                            ActivityManagerNative.getDefault().showBootMessage(
7293                                    mContext.getResources().getString(
7294                                            R.string.android_upgrading_fstrim), true);
7295                        } catch (RemoteException e) {
7296                        }
7297                    }
7298                    ms.runMaintenance();
7299                }
7300            } else {
7301                Slog.e(TAG, "Mount service unavailable!");
7302            }
7303        } catch (RemoteException e) {
7304            // Can't happen; MountService is local
7305        }
7306    }
7307
7308    @Override
7309    public void updatePackagesIfNeeded() {
7310        enforceSystemOrRoot("Only the system can request package update");
7311
7312        // We need to re-extract after an OTA.
7313        boolean causeUpgrade = isUpgrade();
7314
7315        // First boot or factory reset.
7316        // Note: we also handle devices that are upgrading to N right now as if it is their
7317        //       first boot, as they do not have profile data.
7318        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7319
7320        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7321        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7322
7323        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7324            return;
7325        }
7326
7327        List<PackageParser.Package> pkgs;
7328        synchronized (mPackages) {
7329            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7330        }
7331
7332        final long startTime = System.nanoTime();
7333        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7334                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7335
7336        final int elapsedTimeSeconds =
7337                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7338
7339        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7340        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7341        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7342        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7343        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7344    }
7345
7346    /**
7347     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7348     * containing statistics about the invocation. The array consists of three elements,
7349     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7350     * and {@code numberOfPackagesFailed}.
7351     */
7352    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7353            String compilerFilter) {
7354
7355        int numberOfPackagesVisited = 0;
7356        int numberOfPackagesOptimized = 0;
7357        int numberOfPackagesSkipped = 0;
7358        int numberOfPackagesFailed = 0;
7359        final int numberOfPackagesToDexopt = pkgs.size();
7360
7361        for (PackageParser.Package pkg : pkgs) {
7362            numberOfPackagesVisited++;
7363
7364            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7365                if (DEBUG_DEXOPT) {
7366                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7367                }
7368                numberOfPackagesSkipped++;
7369                continue;
7370            }
7371
7372            if (DEBUG_DEXOPT) {
7373                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7374                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7375            }
7376
7377            if (showDialog) {
7378                try {
7379                    ActivityManagerNative.getDefault().showBootMessage(
7380                            mContext.getResources().getString(R.string.android_upgrading_apk,
7381                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7382                } catch (RemoteException e) {
7383                }
7384            }
7385
7386            // checkProfiles is false to avoid merging profiles during boot which
7387            // might interfere with background compilation (b/28612421).
7388            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7389            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7390            // trade-off worth doing to save boot time work.
7391            int dexOptStatus = performDexOptTraced(pkg.packageName,
7392                    false /* checkProfiles */,
7393                    compilerFilter,
7394                    false /* force */);
7395            switch (dexOptStatus) {
7396                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7397                    numberOfPackagesOptimized++;
7398                    break;
7399                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7400                    numberOfPackagesSkipped++;
7401                    break;
7402                case PackageDexOptimizer.DEX_OPT_FAILED:
7403                    numberOfPackagesFailed++;
7404                    break;
7405                default:
7406                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7407                    break;
7408            }
7409        }
7410
7411        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7412                numberOfPackagesFailed };
7413    }
7414
7415    @Override
7416    public void notifyPackageUse(String packageName, int reason) {
7417        synchronized (mPackages) {
7418            PackageParser.Package p = mPackages.get(packageName);
7419            if (p == null) {
7420                return;
7421            }
7422            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7423        }
7424    }
7425
7426    // TODO: this is not used nor needed. Delete it.
7427    @Override
7428    public boolean performDexOptIfNeeded(String packageName) {
7429        int dexOptStatus = performDexOptTraced(packageName,
7430                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7431        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7432    }
7433
7434    @Override
7435    public boolean performDexOpt(String packageName,
7436            boolean checkProfiles, int compileReason, boolean force) {
7437        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7438                getCompilerFilterForReason(compileReason), force);
7439        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7440    }
7441
7442    @Override
7443    public boolean performDexOptMode(String packageName,
7444            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7445        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7446                targetCompilerFilter, force);
7447        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7448    }
7449
7450    private int performDexOptTraced(String packageName,
7451                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7452        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7453        try {
7454            return performDexOptInternal(packageName, checkProfiles,
7455                    targetCompilerFilter, force);
7456        } finally {
7457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7458        }
7459    }
7460
7461    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7462    // if the package can now be considered up to date for the given filter.
7463    private int performDexOptInternal(String packageName,
7464                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7465        PackageParser.Package p;
7466        synchronized (mPackages) {
7467            p = mPackages.get(packageName);
7468            if (p == null) {
7469                // Package could not be found. Report failure.
7470                return PackageDexOptimizer.DEX_OPT_FAILED;
7471            }
7472            mPackageUsage.write(false);
7473        }
7474        long callingId = Binder.clearCallingIdentity();
7475        try {
7476            synchronized (mInstallLock) {
7477                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7478                        targetCompilerFilter, force);
7479            }
7480        } finally {
7481            Binder.restoreCallingIdentity(callingId);
7482        }
7483    }
7484
7485    public ArraySet<String> getOptimizablePackages() {
7486        ArraySet<String> pkgs = new ArraySet<String>();
7487        synchronized (mPackages) {
7488            for (PackageParser.Package p : mPackages.values()) {
7489                if (PackageDexOptimizer.canOptimizePackage(p)) {
7490                    pkgs.add(p.packageName);
7491                }
7492            }
7493        }
7494        return pkgs;
7495    }
7496
7497    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7498            boolean checkProfiles, String targetCompilerFilter,
7499            boolean force) {
7500        // Select the dex optimizer based on the force parameter.
7501        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7502        //       allocate an object here.
7503        PackageDexOptimizer pdo = force
7504                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7505                : mPackageDexOptimizer;
7506
7507        // Optimize all dependencies first. Note: we ignore the return value and march on
7508        // on errors.
7509        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7510        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7511        if (!deps.isEmpty()) {
7512            for (PackageParser.Package depPackage : deps) {
7513                // TODO: Analyze and investigate if we (should) profile libraries.
7514                // Currently this will do a full compilation of the library by default.
7515                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7516                        false /* checkProfiles */,
7517                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7518            }
7519        }
7520        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7521                targetCompilerFilter);
7522    }
7523
7524    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7525        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7526            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7527            Set<String> collectedNames = new HashSet<>();
7528            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7529
7530            retValue.remove(p);
7531
7532            return retValue;
7533        } else {
7534            return Collections.emptyList();
7535        }
7536    }
7537
7538    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7539            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7540        if (!collectedNames.contains(p.packageName)) {
7541            collectedNames.add(p.packageName);
7542            collected.add(p);
7543
7544            if (p.usesLibraries != null) {
7545                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7546            }
7547            if (p.usesOptionalLibraries != null) {
7548                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7549                        collectedNames);
7550            }
7551        }
7552    }
7553
7554    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7555            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7556        for (String libName : libs) {
7557            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7558            if (libPkg != null) {
7559                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7560            }
7561        }
7562    }
7563
7564    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7565        synchronized (mPackages) {
7566            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7567            if (lib != null && lib.apk != null) {
7568                return mPackages.get(lib.apk);
7569            }
7570        }
7571        return null;
7572    }
7573
7574    public void shutdown() {
7575        mPackageUsage.write(true);
7576    }
7577
7578    @Override
7579    public void dumpProfiles(String packageName) {
7580        PackageParser.Package pkg;
7581        synchronized (mPackages) {
7582            pkg = mPackages.get(packageName);
7583            if (pkg == null) {
7584                throw new IllegalArgumentException("Unknown package: " + packageName);
7585            }
7586        }
7587        /* Only the shell, root, or the app user should be able to dump profiles. */
7588        int callingUid = Binder.getCallingUid();
7589        if (callingUid != Process.SHELL_UID &&
7590            callingUid != Process.ROOT_UID &&
7591            callingUid != pkg.applicationInfo.uid) {
7592            throw new SecurityException("dumpProfiles");
7593        }
7594
7595        synchronized (mInstallLock) {
7596            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7597            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7598            try {
7599                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7600                String gid = Integer.toString(sharedGid);
7601                String codePaths = TextUtils.join(";", allCodePaths);
7602                mInstaller.dumpProfiles(gid, packageName, codePaths);
7603            } catch (InstallerException e) {
7604                Slog.w(TAG, "Failed to dump profiles", e);
7605            }
7606            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7607        }
7608    }
7609
7610    @Override
7611    public void forceDexOpt(String packageName) {
7612        enforceSystemOrRoot("forceDexOpt");
7613
7614        PackageParser.Package pkg;
7615        synchronized (mPackages) {
7616            pkg = mPackages.get(packageName);
7617            if (pkg == null) {
7618                throw new IllegalArgumentException("Unknown package: " + packageName);
7619            }
7620        }
7621
7622        synchronized (mInstallLock) {
7623            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7624
7625            // Whoever is calling forceDexOpt wants a fully compiled package.
7626            // Don't use profiles since that may cause compilation to be skipped.
7627            final int res = performDexOptInternalWithDependenciesLI(pkg,
7628                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7629                    true /* force */);
7630
7631            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7632            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7633                throw new IllegalStateException("Failed to dexopt: " + res);
7634            }
7635        }
7636    }
7637
7638    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7639        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7640            Slog.w(TAG, "Unable to update from " + oldPkg.name
7641                    + " to " + newPkg.packageName
7642                    + ": old package not in system partition");
7643            return false;
7644        } else if (mPackages.get(oldPkg.name) != null) {
7645            Slog.w(TAG, "Unable to update from " + oldPkg.name
7646                    + " to " + newPkg.packageName
7647                    + ": old package still exists");
7648            return false;
7649        }
7650        return true;
7651    }
7652
7653    void removeCodePathLI(File codePath) {
7654        if (codePath.isDirectory()) {
7655            try {
7656                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7657            } catch (InstallerException e) {
7658                Slog.w(TAG, "Failed to remove code path", e);
7659            }
7660        } else {
7661            codePath.delete();
7662        }
7663    }
7664
7665    private int[] resolveUserIds(int userId) {
7666        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7667    }
7668
7669    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7670        if (pkg == null) {
7671            Slog.wtf(TAG, "Package was null!", new Throwable());
7672            return;
7673        }
7674        clearAppDataLeafLIF(pkg, userId, flags);
7675        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7676        for (int i = 0; i < childCount; i++) {
7677            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7678        }
7679    }
7680
7681    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7682        final PackageSetting ps;
7683        synchronized (mPackages) {
7684            ps = mSettings.mPackages.get(pkg.packageName);
7685        }
7686        for (int realUserId : resolveUserIds(userId)) {
7687            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7688            try {
7689                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7690                        ceDataInode);
7691            } catch (InstallerException e) {
7692                Slog.w(TAG, String.valueOf(e));
7693            }
7694        }
7695    }
7696
7697    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7698        if (pkg == null) {
7699            Slog.wtf(TAG, "Package was null!", new Throwable());
7700            return;
7701        }
7702        destroyAppDataLeafLIF(pkg, userId, flags);
7703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7704        for (int i = 0; i < childCount; i++) {
7705            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7706        }
7707    }
7708
7709    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7710        final PackageSetting ps;
7711        synchronized (mPackages) {
7712            ps = mSettings.mPackages.get(pkg.packageName);
7713        }
7714        for (int realUserId : resolveUserIds(userId)) {
7715            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7716            try {
7717                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7718                        ceDataInode);
7719            } catch (InstallerException e) {
7720                Slog.w(TAG, String.valueOf(e));
7721            }
7722        }
7723    }
7724
7725    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7726        if (pkg == null) {
7727            Slog.wtf(TAG, "Package was null!", new Throwable());
7728            return;
7729        }
7730        destroyAppProfilesLeafLIF(pkg);
7731        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7732        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7733        for (int i = 0; i < childCount; i++) {
7734            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7735            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7736                    true /* removeBaseMarker */);
7737        }
7738    }
7739
7740    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7741            boolean removeBaseMarker) {
7742        if (pkg.isForwardLocked()) {
7743            return;
7744        }
7745
7746        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7747            try {
7748                path = PackageManagerServiceUtils.realpath(new File(path));
7749            } catch (IOException e) {
7750                // TODO: Should we return early here ?
7751                Slog.w(TAG, "Failed to get canonical path", e);
7752                continue;
7753            }
7754
7755            final String useMarker = path.replace('/', '@');
7756            for (int realUserId : resolveUserIds(userId)) {
7757                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7758                if (removeBaseMarker) {
7759                    File foreignUseMark = new File(profileDir, useMarker);
7760                    if (foreignUseMark.exists()) {
7761                        if (!foreignUseMark.delete()) {
7762                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7763                                    + pkg.packageName);
7764                        }
7765                    }
7766                }
7767
7768                File[] markers = profileDir.listFiles();
7769                if (markers != null) {
7770                    final String searchString = "@" + pkg.packageName + "@";
7771                    // We also delete all markers that contain the package name we're
7772                    // uninstalling. These are associated with secondary dex-files belonging
7773                    // to the package. Reconstructing the path of these dex files is messy
7774                    // in general.
7775                    for (File marker : markers) {
7776                        if (marker.getName().indexOf(searchString) > 0) {
7777                            if (!marker.delete()) {
7778                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7779                                    + pkg.packageName);
7780                            }
7781                        }
7782                    }
7783                }
7784            }
7785        }
7786    }
7787
7788    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7789        try {
7790            mInstaller.destroyAppProfiles(pkg.packageName);
7791        } catch (InstallerException e) {
7792            Slog.w(TAG, String.valueOf(e));
7793        }
7794    }
7795
7796    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7797        if (pkg == null) {
7798            Slog.wtf(TAG, "Package was null!", new Throwable());
7799            return;
7800        }
7801        clearAppProfilesLeafLIF(pkg);
7802        // We don't remove the base foreign use marker when clearing profiles because
7803        // we will rename it when the app is updated. Unlike the actual profile contents,
7804        // the foreign use marker is good across installs.
7805        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7806        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7807        for (int i = 0; i < childCount; i++) {
7808            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7809        }
7810    }
7811
7812    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7813        try {
7814            mInstaller.clearAppProfiles(pkg.packageName);
7815        } catch (InstallerException e) {
7816            Slog.w(TAG, String.valueOf(e));
7817        }
7818    }
7819
7820    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7821            long lastUpdateTime) {
7822        // Set parent install/update time
7823        PackageSetting ps = (PackageSetting) pkg.mExtras;
7824        if (ps != null) {
7825            ps.firstInstallTime = firstInstallTime;
7826            ps.lastUpdateTime = lastUpdateTime;
7827        }
7828        // Set children install/update time
7829        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7830        for (int i = 0; i < childCount; i++) {
7831            PackageParser.Package childPkg = pkg.childPackages.get(i);
7832            ps = (PackageSetting) childPkg.mExtras;
7833            if (ps != null) {
7834                ps.firstInstallTime = firstInstallTime;
7835                ps.lastUpdateTime = lastUpdateTime;
7836            }
7837        }
7838    }
7839
7840    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7841            PackageParser.Package changingLib) {
7842        if (file.path != null) {
7843            usesLibraryFiles.add(file.path);
7844            return;
7845        }
7846        PackageParser.Package p = mPackages.get(file.apk);
7847        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7848            // If we are doing this while in the middle of updating a library apk,
7849            // then we need to make sure to use that new apk for determining the
7850            // dependencies here.  (We haven't yet finished committing the new apk
7851            // to the package manager state.)
7852            if (p == null || p.packageName.equals(changingLib.packageName)) {
7853                p = changingLib;
7854            }
7855        }
7856        if (p != null) {
7857            usesLibraryFiles.addAll(p.getAllCodePaths());
7858        }
7859    }
7860
7861    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7862            PackageParser.Package changingLib) throws PackageManagerException {
7863        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7864            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7865            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7866            for (int i=0; i<N; i++) {
7867                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7868                if (file == null) {
7869                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7870                            "Package " + pkg.packageName + " requires unavailable shared library "
7871                            + pkg.usesLibraries.get(i) + "; failing!");
7872                }
7873                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7874            }
7875            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7876            for (int i=0; i<N; i++) {
7877                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7878                if (file == null) {
7879                    Slog.w(TAG, "Package " + pkg.packageName
7880                            + " desires unavailable shared library "
7881                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7882                } else {
7883                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7884                }
7885            }
7886            N = usesLibraryFiles.size();
7887            if (N > 0) {
7888                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7889            } else {
7890                pkg.usesLibraryFiles = null;
7891            }
7892        }
7893    }
7894
7895    private static boolean hasString(List<String> list, List<String> which) {
7896        if (list == null) {
7897            return false;
7898        }
7899        for (int i=list.size()-1; i>=0; i--) {
7900            for (int j=which.size()-1; j>=0; j--) {
7901                if (which.get(j).equals(list.get(i))) {
7902                    return true;
7903                }
7904            }
7905        }
7906        return false;
7907    }
7908
7909    private void updateAllSharedLibrariesLPw() {
7910        for (PackageParser.Package pkg : mPackages.values()) {
7911            try {
7912                updateSharedLibrariesLPw(pkg, null);
7913            } catch (PackageManagerException e) {
7914                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7915            }
7916        }
7917    }
7918
7919    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7920            PackageParser.Package changingPkg) {
7921        ArrayList<PackageParser.Package> res = null;
7922        for (PackageParser.Package pkg : mPackages.values()) {
7923            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7924                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7925                if (res == null) {
7926                    res = new ArrayList<PackageParser.Package>();
7927                }
7928                res.add(pkg);
7929                try {
7930                    updateSharedLibrariesLPw(pkg, changingPkg);
7931                } catch (PackageManagerException e) {
7932                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7933                }
7934            }
7935        }
7936        return res;
7937    }
7938
7939    /**
7940     * Derive the value of the {@code cpuAbiOverride} based on the provided
7941     * value and an optional stored value from the package settings.
7942     */
7943    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7944        String cpuAbiOverride = null;
7945
7946        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7947            cpuAbiOverride = null;
7948        } else if (abiOverride != null) {
7949            cpuAbiOverride = abiOverride;
7950        } else if (settings != null) {
7951            cpuAbiOverride = settings.cpuAbiOverrideString;
7952        }
7953
7954        return cpuAbiOverride;
7955    }
7956
7957    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7958            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7959                    throws PackageManagerException {
7960        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7961        // If the package has children and this is the first dive in the function
7962        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7963        // whether all packages (parent and children) would be successfully scanned
7964        // before the actual scan since scanning mutates internal state and we want
7965        // to atomically install the package and its children.
7966        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7967            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7968                scanFlags |= SCAN_CHECK_ONLY;
7969            }
7970        } else {
7971            scanFlags &= ~SCAN_CHECK_ONLY;
7972        }
7973
7974        final PackageParser.Package scannedPkg;
7975        try {
7976            // Scan the parent
7977            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7978            // Scan the children
7979            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7980            for (int i = 0; i < childCount; i++) {
7981                PackageParser.Package childPkg = pkg.childPackages.get(i);
7982                scanPackageLI(childPkg, policyFlags,
7983                        scanFlags, currentTime, user);
7984            }
7985        } finally {
7986            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7987        }
7988
7989        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7990            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7991        }
7992
7993        return scannedPkg;
7994    }
7995
7996    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7997            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7998        boolean success = false;
7999        try {
8000            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8001                    currentTime, user);
8002            success = true;
8003            return res;
8004        } finally {
8005            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8006                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8007                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8008                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8009                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8010            }
8011        }
8012    }
8013
8014    /**
8015     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8016     */
8017    private static boolean apkHasCode(String fileName) {
8018        StrictJarFile jarFile = null;
8019        try {
8020            jarFile = new StrictJarFile(fileName,
8021                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8022            return jarFile.findEntry("classes.dex") != null;
8023        } catch (IOException ignore) {
8024        } finally {
8025            try {
8026                if (jarFile != null) {
8027                    jarFile.close();
8028                }
8029            } catch (IOException ignore) {}
8030        }
8031        return false;
8032    }
8033
8034    /**
8035     * Enforces code policy for the package. This ensures that if an APK has
8036     * declared hasCode="true" in its manifest that the APK actually contains
8037     * code.
8038     *
8039     * @throws PackageManagerException If bytecode could not be found when it should exist
8040     */
8041    private static void enforceCodePolicy(PackageParser.Package pkg)
8042            throws PackageManagerException {
8043        final boolean shouldHaveCode =
8044                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8045        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8046            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8047                    "Package " + pkg.baseCodePath + " code is missing");
8048        }
8049
8050        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8051            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8052                final boolean splitShouldHaveCode =
8053                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8054                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8055                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8056                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8057                }
8058            }
8059        }
8060    }
8061
8062    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8063            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8064            throws PackageManagerException {
8065        final File scanFile = new File(pkg.codePath);
8066        if (pkg.applicationInfo.getCodePath() == null ||
8067                pkg.applicationInfo.getResourcePath() == null) {
8068            // Bail out. The resource and code paths haven't been set.
8069            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8070                    "Code and resource paths haven't been set correctly");
8071        }
8072
8073        // Apply policy
8074        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8075            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8076            if (pkg.applicationInfo.isDirectBootAware()) {
8077                // we're direct boot aware; set for all components
8078                for (PackageParser.Service s : pkg.services) {
8079                    s.info.encryptionAware = s.info.directBootAware = true;
8080                }
8081                for (PackageParser.Provider p : pkg.providers) {
8082                    p.info.encryptionAware = p.info.directBootAware = true;
8083                }
8084                for (PackageParser.Activity a : pkg.activities) {
8085                    a.info.encryptionAware = a.info.directBootAware = true;
8086                }
8087                for (PackageParser.Activity r : pkg.receivers) {
8088                    r.info.encryptionAware = r.info.directBootAware = true;
8089                }
8090            }
8091        } else {
8092            // Only allow system apps to be flagged as core apps.
8093            pkg.coreApp = false;
8094            // clear flags not applicable to regular apps
8095            pkg.applicationInfo.privateFlags &=
8096                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8097            pkg.applicationInfo.privateFlags &=
8098                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8099        }
8100        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8101
8102        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8103            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8104        }
8105
8106        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8107            enforceCodePolicy(pkg);
8108        }
8109
8110        if (mCustomResolverComponentName != null &&
8111                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8112            setUpCustomResolverActivity(pkg);
8113        }
8114
8115        if (pkg.packageName.equals("android")) {
8116            synchronized (mPackages) {
8117                if (mAndroidApplication != null) {
8118                    Slog.w(TAG, "*************************************************");
8119                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8120                    Slog.w(TAG, " file=" + scanFile);
8121                    Slog.w(TAG, "*************************************************");
8122                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8123                            "Core android package being redefined.  Skipping.");
8124                }
8125
8126                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8127                    // Set up information for our fall-back user intent resolution activity.
8128                    mPlatformPackage = pkg;
8129                    pkg.mVersionCode = mSdkVersion;
8130                    mAndroidApplication = pkg.applicationInfo;
8131
8132                    if (!mResolverReplaced) {
8133                        mResolveActivity.applicationInfo = mAndroidApplication;
8134                        mResolveActivity.name = ResolverActivity.class.getName();
8135                        mResolveActivity.packageName = mAndroidApplication.packageName;
8136                        mResolveActivity.processName = "system:ui";
8137                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8138                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8139                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8140                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8141                        mResolveActivity.exported = true;
8142                        mResolveActivity.enabled = true;
8143                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8144                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8145                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8146                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8147                                | ActivityInfo.CONFIG_ORIENTATION
8148                                | ActivityInfo.CONFIG_KEYBOARD
8149                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8150                        mResolveInfo.activityInfo = mResolveActivity;
8151                        mResolveInfo.priority = 0;
8152                        mResolveInfo.preferredOrder = 0;
8153                        mResolveInfo.match = 0;
8154                        mResolveComponentName = new ComponentName(
8155                                mAndroidApplication.packageName, mResolveActivity.name);
8156                    }
8157                }
8158            }
8159        }
8160
8161        if (DEBUG_PACKAGE_SCANNING) {
8162            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8163                Log.d(TAG, "Scanning package " + pkg.packageName);
8164        }
8165
8166        synchronized (mPackages) {
8167            if (mPackages.containsKey(pkg.packageName)
8168                    || mSharedLibraries.containsKey(pkg.packageName)) {
8169                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8170                        "Application package " + pkg.packageName
8171                                + " already installed.  Skipping duplicate.");
8172            }
8173
8174            // If we're only installing presumed-existing packages, require that the
8175            // scanned APK is both already known and at the path previously established
8176            // for it.  Previously unknown packages we pick up normally, but if we have an
8177            // a priori expectation about this package's install presence, enforce it.
8178            // With a singular exception for new system packages. When an OTA contains
8179            // a new system package, we allow the codepath to change from a system location
8180            // to the user-installed location. If we don't allow this change, any newer,
8181            // user-installed version of the application will be ignored.
8182            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8183                if (mExpectingBetter.containsKey(pkg.packageName)) {
8184                    logCriticalInfo(Log.WARN,
8185                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8186                } else {
8187                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8188                    if (known != null) {
8189                        if (DEBUG_PACKAGE_SCANNING) {
8190                            Log.d(TAG, "Examining " + pkg.codePath
8191                                    + " and requiring known paths " + known.codePathString
8192                                    + " & " + known.resourcePathString);
8193                        }
8194                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8195                                || !pkg.applicationInfo.getResourcePath().equals(
8196                                known.resourcePathString)) {
8197                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8198                                    "Application package " + pkg.packageName
8199                                            + " found at " + pkg.applicationInfo.getCodePath()
8200                                            + " but expected at " + known.codePathString
8201                                            + "; ignoring.");
8202                        }
8203                    }
8204                }
8205            }
8206        }
8207
8208        // Initialize package source and resource directories
8209        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8210        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8211
8212        SharedUserSetting suid = null;
8213        PackageSetting pkgSetting = null;
8214
8215        if (!isSystemApp(pkg)) {
8216            // Only system apps can use these features.
8217            pkg.mOriginalPackages = null;
8218            pkg.mRealPackage = null;
8219            pkg.mAdoptPermissions = null;
8220        }
8221
8222        // Getting the package setting may have a side-effect, so if we
8223        // are only checking if scan would succeed, stash a copy of the
8224        // old setting to restore at the end.
8225        PackageSetting nonMutatedPs = null;
8226
8227        // writer
8228        synchronized (mPackages) {
8229            if (pkg.mSharedUserId != null) {
8230                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8231                if (suid == null) {
8232                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8233                            "Creating application package " + pkg.packageName
8234                            + " for shared user failed");
8235                }
8236                if (DEBUG_PACKAGE_SCANNING) {
8237                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8238                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8239                                + "): packages=" + suid.packages);
8240                }
8241            }
8242
8243            // Check if we are renaming from an original package name.
8244            PackageSetting origPackage = null;
8245            String realName = null;
8246            if (pkg.mOriginalPackages != null) {
8247                // This package may need to be renamed to a previously
8248                // installed name.  Let's check on that...
8249                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8250                if (pkg.mOriginalPackages.contains(renamed)) {
8251                    // This package had originally been installed as the
8252                    // original name, and we have already taken care of
8253                    // transitioning to the new one.  Just update the new
8254                    // one to continue using the old name.
8255                    realName = pkg.mRealPackage;
8256                    if (!pkg.packageName.equals(renamed)) {
8257                        // Callers into this function may have already taken
8258                        // care of renaming the package; only do it here if
8259                        // it is not already done.
8260                        pkg.setPackageName(renamed);
8261                    }
8262
8263                } else {
8264                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8265                        if ((origPackage = mSettings.peekPackageLPr(
8266                                pkg.mOriginalPackages.get(i))) != null) {
8267                            // We do have the package already installed under its
8268                            // original name...  should we use it?
8269                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8270                                // New package is not compatible with original.
8271                                origPackage = null;
8272                                continue;
8273                            } else if (origPackage.sharedUser != null) {
8274                                // Make sure uid is compatible between packages.
8275                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8276                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8277                                            + " to " + pkg.packageName + ": old uid "
8278                                            + origPackage.sharedUser.name
8279                                            + " differs from " + pkg.mSharedUserId);
8280                                    origPackage = null;
8281                                    continue;
8282                                }
8283                                // TODO: Add case when shared user id is added [b/28144775]
8284                            } else {
8285                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8286                                        + pkg.packageName + " to old name " + origPackage.name);
8287                            }
8288                            break;
8289                        }
8290                    }
8291                }
8292            }
8293
8294            if (mTransferedPackages.contains(pkg.packageName)) {
8295                Slog.w(TAG, "Package " + pkg.packageName
8296                        + " was transferred to another, but its .apk remains");
8297            }
8298
8299            // See comments in nonMutatedPs declaration
8300            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8301                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8302                if (foundPs != null) {
8303                    nonMutatedPs = new PackageSetting(foundPs);
8304                }
8305            }
8306
8307            // Just create the setting, don't add it yet. For already existing packages
8308            // the PkgSetting exists already and doesn't have to be created.
8309            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8310                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8311                    pkg.applicationInfo.primaryCpuAbi,
8312                    pkg.applicationInfo.secondaryCpuAbi,
8313                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8314                    user, false);
8315            if (pkgSetting == null) {
8316                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8317                        "Creating application package " + pkg.packageName + " failed");
8318            }
8319
8320            if (pkgSetting.origPackage != null) {
8321                // If we are first transitioning from an original package,
8322                // fix up the new package's name now.  We need to do this after
8323                // looking up the package under its new name, so getPackageLP
8324                // can take care of fiddling things correctly.
8325                pkg.setPackageName(origPackage.name);
8326
8327                // File a report about this.
8328                String msg = "New package " + pkgSetting.realName
8329                        + " renamed to replace old package " + pkgSetting.name;
8330                reportSettingsProblem(Log.WARN, msg);
8331
8332                // Make a note of it.
8333                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8334                    mTransferedPackages.add(origPackage.name);
8335                }
8336
8337                // No longer need to retain this.
8338                pkgSetting.origPackage = null;
8339            }
8340
8341            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8342                // Make a note of it.
8343                mTransferedPackages.add(pkg.packageName);
8344            }
8345
8346            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8347                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8348            }
8349
8350            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8351                // Check all shared libraries and map to their actual file path.
8352                // We only do this here for apps not on a system dir, because those
8353                // are the only ones that can fail an install due to this.  We
8354                // will take care of the system apps by updating all of their
8355                // library paths after the scan is done.
8356                updateSharedLibrariesLPw(pkg, null);
8357            }
8358
8359            if (mFoundPolicyFile) {
8360                SELinuxMMAC.assignSeinfoValue(pkg);
8361            }
8362
8363            pkg.applicationInfo.uid = pkgSetting.appId;
8364            pkg.mExtras = pkgSetting;
8365            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8366                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8367                    // We just determined the app is signed correctly, so bring
8368                    // over the latest parsed certs.
8369                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8370                } else {
8371                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8372                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8373                                "Package " + pkg.packageName + " upgrade keys do not match the "
8374                                + "previously installed version");
8375                    } else {
8376                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8377                        String msg = "System package " + pkg.packageName
8378                            + " signature changed; retaining data.";
8379                        reportSettingsProblem(Log.WARN, msg);
8380                    }
8381                }
8382            } else {
8383                try {
8384                    verifySignaturesLP(pkgSetting, pkg);
8385                    // We just determined the app is signed correctly, so bring
8386                    // over the latest parsed certs.
8387                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8388                } catch (PackageManagerException e) {
8389                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8390                        throw e;
8391                    }
8392                    // The signature has changed, but this package is in the system
8393                    // image...  let's recover!
8394                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8395                    // However...  if this package is part of a shared user, but it
8396                    // doesn't match the signature of the shared user, let's fail.
8397                    // What this means is that you can't change the signatures
8398                    // associated with an overall shared user, which doesn't seem all
8399                    // that unreasonable.
8400                    if (pkgSetting.sharedUser != null) {
8401                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8402                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8403                            throw new PackageManagerException(
8404                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8405                                            "Signature mismatch for shared user: "
8406                                            + pkgSetting.sharedUser);
8407                        }
8408                    }
8409                    // File a report about this.
8410                    String msg = "System package " + pkg.packageName
8411                        + " signature changed; retaining data.";
8412                    reportSettingsProblem(Log.WARN, msg);
8413                }
8414            }
8415            // Verify that this new package doesn't have any content providers
8416            // that conflict with existing packages.  Only do this if the
8417            // package isn't already installed, since we don't want to break
8418            // things that are installed.
8419            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8420                final int N = pkg.providers.size();
8421                int i;
8422                for (i=0; i<N; i++) {
8423                    PackageParser.Provider p = pkg.providers.get(i);
8424                    if (p.info.authority != null) {
8425                        String names[] = p.info.authority.split(";");
8426                        for (int j = 0; j < names.length; j++) {
8427                            if (mProvidersByAuthority.containsKey(names[j])) {
8428                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8429                                final String otherPackageName =
8430                                        ((other != null && other.getComponentName() != null) ?
8431                                                other.getComponentName().getPackageName() : "?");
8432                                throw new PackageManagerException(
8433                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8434                                                "Can't install because provider name " + names[j]
8435                                                + " (in package " + pkg.applicationInfo.packageName
8436                                                + ") is already used by " + otherPackageName);
8437                            }
8438                        }
8439                    }
8440                }
8441            }
8442
8443            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8444                // This package wants to adopt ownership of permissions from
8445                // another package.
8446                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8447                    final String origName = pkg.mAdoptPermissions.get(i);
8448                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8449                    if (orig != null) {
8450                        if (verifyPackageUpdateLPr(orig, pkg)) {
8451                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8452                                    + pkg.packageName);
8453                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8454                        }
8455                    }
8456                }
8457            }
8458        }
8459
8460        final String pkgName = pkg.packageName;
8461
8462        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8463        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8464        pkg.applicationInfo.processName = fixProcessName(
8465                pkg.applicationInfo.packageName,
8466                pkg.applicationInfo.processName,
8467                pkg.applicationInfo.uid);
8468
8469        if (pkg != mPlatformPackage) {
8470            // Get all of our default paths setup
8471            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8472        }
8473
8474        final String path = scanFile.getPath();
8475        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8476
8477        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8478            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8479
8480            // Some system apps still use directory structure for native libraries
8481            // in which case we might end up not detecting abi solely based on apk
8482            // structure. Try to detect abi based on directory structure.
8483            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8484                    pkg.applicationInfo.primaryCpuAbi == null) {
8485                setBundledAppAbisAndRoots(pkg, pkgSetting);
8486                setNativeLibraryPaths(pkg);
8487            }
8488
8489        } else {
8490            if ((scanFlags & SCAN_MOVE) != 0) {
8491                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8492                // but we already have this packages package info in the PackageSetting. We just
8493                // use that and derive the native library path based on the new codepath.
8494                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8495                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8496            }
8497
8498            // Set native library paths again. For moves, the path will be updated based on the
8499            // ABIs we've determined above. For non-moves, the path will be updated based on the
8500            // ABIs we determined during compilation, but the path will depend on the final
8501            // package path (after the rename away from the stage path).
8502            setNativeLibraryPaths(pkg);
8503        }
8504
8505        // This is a special case for the "system" package, where the ABI is
8506        // dictated by the zygote configuration (and init.rc). We should keep track
8507        // of this ABI so that we can deal with "normal" applications that run under
8508        // the same UID correctly.
8509        if (mPlatformPackage == pkg) {
8510            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8511                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8512        }
8513
8514        // If there's a mismatch between the abi-override in the package setting
8515        // and the abiOverride specified for the install. Warn about this because we
8516        // would've already compiled the app without taking the package setting into
8517        // account.
8518        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8519            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8520                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8521                        " for package " + pkg.packageName);
8522            }
8523        }
8524
8525        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8526        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8527        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8528
8529        // Copy the derived override back to the parsed package, so that we can
8530        // update the package settings accordingly.
8531        pkg.cpuAbiOverride = cpuAbiOverride;
8532
8533        if (DEBUG_ABI_SELECTION) {
8534            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8535                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8536                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8537        }
8538
8539        // Push the derived path down into PackageSettings so we know what to
8540        // clean up at uninstall time.
8541        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8542
8543        if (DEBUG_ABI_SELECTION) {
8544            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8545                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8546                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8547        }
8548
8549        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8550            // We don't do this here during boot because we can do it all
8551            // at once after scanning all existing packages.
8552            //
8553            // We also do this *before* we perform dexopt on this package, so that
8554            // we can avoid redundant dexopts, and also to make sure we've got the
8555            // code and package path correct.
8556            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8557                    pkg, true /* boot complete */);
8558        }
8559
8560        if (mFactoryTest && pkg.requestedPermissions.contains(
8561                android.Manifest.permission.FACTORY_TEST)) {
8562            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8563        }
8564
8565        ArrayList<PackageParser.Package> clientLibPkgs = null;
8566
8567        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8568            if (nonMutatedPs != null) {
8569                synchronized (mPackages) {
8570                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8571                }
8572            }
8573            return pkg;
8574        }
8575
8576        // Only privileged apps and updated privileged apps can add child packages.
8577        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8578            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8579                throw new PackageManagerException("Only privileged apps and updated "
8580                        + "privileged apps can add child packages. Ignoring package "
8581                        + pkg.packageName);
8582            }
8583            final int childCount = pkg.childPackages.size();
8584            for (int i = 0; i < childCount; i++) {
8585                PackageParser.Package childPkg = pkg.childPackages.get(i);
8586                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8587                        childPkg.packageName)) {
8588                    throw new PackageManagerException("Cannot override a child package of "
8589                            + "another disabled system app. Ignoring package " + pkg.packageName);
8590                }
8591            }
8592        }
8593
8594        // writer
8595        synchronized (mPackages) {
8596            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8597                // Only system apps can add new shared libraries.
8598                if (pkg.libraryNames != null) {
8599                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8600                        String name = pkg.libraryNames.get(i);
8601                        boolean allowed = false;
8602                        if (pkg.isUpdatedSystemApp()) {
8603                            // New library entries can only be added through the
8604                            // system image.  This is important to get rid of a lot
8605                            // of nasty edge cases: for example if we allowed a non-
8606                            // system update of the app to add a library, then uninstalling
8607                            // the update would make the library go away, and assumptions
8608                            // we made such as through app install filtering would now
8609                            // have allowed apps on the device which aren't compatible
8610                            // with it.  Better to just have the restriction here, be
8611                            // conservative, and create many fewer cases that can negatively
8612                            // impact the user experience.
8613                            final PackageSetting sysPs = mSettings
8614                                    .getDisabledSystemPkgLPr(pkg.packageName);
8615                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8616                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8617                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8618                                        allowed = true;
8619                                        break;
8620                                    }
8621                                }
8622                            }
8623                        } else {
8624                            allowed = true;
8625                        }
8626                        if (allowed) {
8627                            if (!mSharedLibraries.containsKey(name)) {
8628                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8629                            } else if (!name.equals(pkg.packageName)) {
8630                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8631                                        + name + " already exists; skipping");
8632                            }
8633                        } else {
8634                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8635                                    + name + " that is not declared on system image; skipping");
8636                        }
8637                    }
8638                    if ((scanFlags & SCAN_BOOTING) == 0) {
8639                        // If we are not booting, we need to update any applications
8640                        // that are clients of our shared library.  If we are booting,
8641                        // this will all be done once the scan is complete.
8642                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8643                    }
8644                }
8645            }
8646        }
8647
8648        if ((scanFlags & SCAN_BOOTING) != 0) {
8649            // No apps can run during boot scan, so they don't need to be frozen
8650        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8651            // Caller asked to not kill app, so it's probably not frozen
8652        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8653            // Caller asked us to ignore frozen check for some reason; they
8654            // probably didn't know the package name
8655        } else {
8656            // We're doing major surgery on this package, so it better be frozen
8657            // right now to keep it from launching
8658            checkPackageFrozen(pkgName);
8659        }
8660
8661        // Also need to kill any apps that are dependent on the library.
8662        if (clientLibPkgs != null) {
8663            for (int i=0; i<clientLibPkgs.size(); i++) {
8664                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8665                killApplication(clientPkg.applicationInfo.packageName,
8666                        clientPkg.applicationInfo.uid, "update lib");
8667            }
8668        }
8669
8670        // Make sure we're not adding any bogus keyset info
8671        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8672        ksms.assertScannedPackageValid(pkg);
8673
8674        // writer
8675        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8676
8677        boolean createIdmapFailed = false;
8678        synchronized (mPackages) {
8679            // We don't expect installation to fail beyond this point
8680
8681            if (pkgSetting.pkg != null) {
8682                // Note that |user| might be null during the initial boot scan. If a codePath
8683                // for an app has changed during a boot scan, it's due to an app update that's
8684                // part of the system partition and marker changes must be applied to all users.
8685                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8686                    (user != null) ? user : UserHandle.ALL);
8687            }
8688
8689            // Add the new setting to mSettings
8690            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8691            // Add the new setting to mPackages
8692            mPackages.put(pkg.applicationInfo.packageName, pkg);
8693            // Make sure we don't accidentally delete its data.
8694            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8695            while (iter.hasNext()) {
8696                PackageCleanItem item = iter.next();
8697                if (pkgName.equals(item.packageName)) {
8698                    iter.remove();
8699                }
8700            }
8701
8702            // Take care of first install / last update times.
8703            if (currentTime != 0) {
8704                if (pkgSetting.firstInstallTime == 0) {
8705                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8706                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8707                    pkgSetting.lastUpdateTime = currentTime;
8708                }
8709            } else if (pkgSetting.firstInstallTime == 0) {
8710                // We need *something*.  Take time time stamp of the file.
8711                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8712            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8713                if (scanFileTime != pkgSetting.timeStamp) {
8714                    // A package on the system image has changed; consider this
8715                    // to be an update.
8716                    pkgSetting.lastUpdateTime = scanFileTime;
8717                }
8718            }
8719
8720            // Add the package's KeySets to the global KeySetManagerService
8721            ksms.addScannedPackageLPw(pkg);
8722
8723            int N = pkg.providers.size();
8724            StringBuilder r = null;
8725            int i;
8726            for (i=0; i<N; i++) {
8727                PackageParser.Provider p = pkg.providers.get(i);
8728                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8729                        p.info.processName, pkg.applicationInfo.uid);
8730                mProviders.addProvider(p);
8731                p.syncable = p.info.isSyncable;
8732                if (p.info.authority != null) {
8733                    String names[] = p.info.authority.split(";");
8734                    p.info.authority = null;
8735                    for (int j = 0; j < names.length; j++) {
8736                        if (j == 1 && p.syncable) {
8737                            // We only want the first authority for a provider to possibly be
8738                            // syncable, so if we already added this provider using a different
8739                            // authority clear the syncable flag. We copy the provider before
8740                            // changing it because the mProviders object contains a reference
8741                            // to a provider that we don't want to change.
8742                            // Only do this for the second authority since the resulting provider
8743                            // object can be the same for all future authorities for this provider.
8744                            p = new PackageParser.Provider(p);
8745                            p.syncable = false;
8746                        }
8747                        if (!mProvidersByAuthority.containsKey(names[j])) {
8748                            mProvidersByAuthority.put(names[j], p);
8749                            if (p.info.authority == null) {
8750                                p.info.authority = names[j];
8751                            } else {
8752                                p.info.authority = p.info.authority + ";" + names[j];
8753                            }
8754                            if (DEBUG_PACKAGE_SCANNING) {
8755                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8756                                    Log.d(TAG, "Registered content provider: " + names[j]
8757                                            + ", className = " + p.info.name + ", isSyncable = "
8758                                            + p.info.isSyncable);
8759                            }
8760                        } else {
8761                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8762                            Slog.w(TAG, "Skipping provider name " + names[j] +
8763                                    " (in package " + pkg.applicationInfo.packageName +
8764                                    "): name already used by "
8765                                    + ((other != null && other.getComponentName() != null)
8766                                            ? other.getComponentName().getPackageName() : "?"));
8767                        }
8768                    }
8769                }
8770                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8771                    if (r == null) {
8772                        r = new StringBuilder(256);
8773                    } else {
8774                        r.append(' ');
8775                    }
8776                    r.append(p.info.name);
8777                }
8778            }
8779            if (r != null) {
8780                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8781            }
8782
8783            N = pkg.services.size();
8784            r = null;
8785            for (i=0; i<N; i++) {
8786                PackageParser.Service s = pkg.services.get(i);
8787                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8788                        s.info.processName, pkg.applicationInfo.uid);
8789                mServices.addService(s);
8790                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8791                    if (r == null) {
8792                        r = new StringBuilder(256);
8793                    } else {
8794                        r.append(' ');
8795                    }
8796                    r.append(s.info.name);
8797                }
8798            }
8799            if (r != null) {
8800                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8801            }
8802
8803            N = pkg.receivers.size();
8804            r = null;
8805            for (i=0; i<N; i++) {
8806                PackageParser.Activity a = pkg.receivers.get(i);
8807                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8808                        a.info.processName, pkg.applicationInfo.uid);
8809                mReceivers.addActivity(a, "receiver");
8810                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8811                    if (r == null) {
8812                        r = new StringBuilder(256);
8813                    } else {
8814                        r.append(' ');
8815                    }
8816                    r.append(a.info.name);
8817                }
8818            }
8819            if (r != null) {
8820                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8821            }
8822
8823            N = pkg.activities.size();
8824            r = null;
8825            for (i=0; i<N; i++) {
8826                PackageParser.Activity a = pkg.activities.get(i);
8827                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8828                        a.info.processName, pkg.applicationInfo.uid);
8829                mActivities.addActivity(a, "activity");
8830                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8831                    if (r == null) {
8832                        r = new StringBuilder(256);
8833                    } else {
8834                        r.append(' ');
8835                    }
8836                    r.append(a.info.name);
8837                }
8838            }
8839            if (r != null) {
8840                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8841            }
8842
8843            N = pkg.permissionGroups.size();
8844            r = null;
8845            for (i=0; i<N; i++) {
8846                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8847                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8848                if (cur == null) {
8849                    mPermissionGroups.put(pg.info.name, pg);
8850                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8851                        if (r == null) {
8852                            r = new StringBuilder(256);
8853                        } else {
8854                            r.append(' ');
8855                        }
8856                        r.append(pg.info.name);
8857                    }
8858                } else {
8859                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8860                            + pg.info.packageName + " ignored: original from "
8861                            + cur.info.packageName);
8862                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8863                        if (r == null) {
8864                            r = new StringBuilder(256);
8865                        } else {
8866                            r.append(' ');
8867                        }
8868                        r.append("DUP:");
8869                        r.append(pg.info.name);
8870                    }
8871                }
8872            }
8873            if (r != null) {
8874                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8875            }
8876
8877            N = pkg.permissions.size();
8878            r = null;
8879            for (i=0; i<N; i++) {
8880                PackageParser.Permission p = pkg.permissions.get(i);
8881
8882                // Assume by default that we did not install this permission into the system.
8883                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8884
8885                // Now that permission groups have a special meaning, we ignore permission
8886                // groups for legacy apps to prevent unexpected behavior. In particular,
8887                // permissions for one app being granted to someone just becase they happen
8888                // to be in a group defined by another app (before this had no implications).
8889                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8890                    p.group = mPermissionGroups.get(p.info.group);
8891                    // Warn for a permission in an unknown group.
8892                    if (p.info.group != null && p.group == null) {
8893                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8894                                + p.info.packageName + " in an unknown group " + p.info.group);
8895                    }
8896                }
8897
8898                ArrayMap<String, BasePermission> permissionMap =
8899                        p.tree ? mSettings.mPermissionTrees
8900                                : mSettings.mPermissions;
8901                BasePermission bp = permissionMap.get(p.info.name);
8902
8903                // Allow system apps to redefine non-system permissions
8904                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8905                    final boolean currentOwnerIsSystem = (bp.perm != null
8906                            && isSystemApp(bp.perm.owner));
8907                    if (isSystemApp(p.owner)) {
8908                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8909                            // It's a built-in permission and no owner, take ownership now
8910                            bp.packageSetting = pkgSetting;
8911                            bp.perm = p;
8912                            bp.uid = pkg.applicationInfo.uid;
8913                            bp.sourcePackage = p.info.packageName;
8914                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8915                        } else if (!currentOwnerIsSystem) {
8916                            String msg = "New decl " + p.owner + " of permission  "
8917                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8918                            reportSettingsProblem(Log.WARN, msg);
8919                            bp = null;
8920                        }
8921                    }
8922                }
8923
8924                if (bp == null) {
8925                    bp = new BasePermission(p.info.name, p.info.packageName,
8926                            BasePermission.TYPE_NORMAL);
8927                    permissionMap.put(p.info.name, bp);
8928                }
8929
8930                if (bp.perm == null) {
8931                    if (bp.sourcePackage == null
8932                            || bp.sourcePackage.equals(p.info.packageName)) {
8933                        BasePermission tree = findPermissionTreeLP(p.info.name);
8934                        if (tree == null
8935                                || tree.sourcePackage.equals(p.info.packageName)) {
8936                            bp.packageSetting = pkgSetting;
8937                            bp.perm = p;
8938                            bp.uid = pkg.applicationInfo.uid;
8939                            bp.sourcePackage = p.info.packageName;
8940                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8941                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8942                                if (r == null) {
8943                                    r = new StringBuilder(256);
8944                                } else {
8945                                    r.append(' ');
8946                                }
8947                                r.append(p.info.name);
8948                            }
8949                        } else {
8950                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8951                                    + p.info.packageName + " ignored: base tree "
8952                                    + tree.name + " is from package "
8953                                    + tree.sourcePackage);
8954                        }
8955                    } else {
8956                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8957                                + p.info.packageName + " ignored: original from "
8958                                + bp.sourcePackage);
8959                    }
8960                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8961                    if (r == null) {
8962                        r = new StringBuilder(256);
8963                    } else {
8964                        r.append(' ');
8965                    }
8966                    r.append("DUP:");
8967                    r.append(p.info.name);
8968                }
8969                if (bp.perm == p) {
8970                    bp.protectionLevel = p.info.protectionLevel;
8971                }
8972            }
8973
8974            if (r != null) {
8975                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8976            }
8977
8978            N = pkg.instrumentation.size();
8979            r = null;
8980            for (i=0; i<N; i++) {
8981                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8982                a.info.packageName = pkg.applicationInfo.packageName;
8983                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8984                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8985                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8986                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8987                a.info.dataDir = pkg.applicationInfo.dataDir;
8988                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8989                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8990
8991                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8992                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8993                mInstrumentation.put(a.getComponentName(), a);
8994                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8995                    if (r == null) {
8996                        r = new StringBuilder(256);
8997                    } else {
8998                        r.append(' ');
8999                    }
9000                    r.append(a.info.name);
9001                }
9002            }
9003            if (r != null) {
9004                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9005            }
9006
9007            if (pkg.protectedBroadcasts != null) {
9008                N = pkg.protectedBroadcasts.size();
9009                for (i=0; i<N; i++) {
9010                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9011                }
9012            }
9013
9014            pkgSetting.setTimeStamp(scanFileTime);
9015
9016            // Create idmap files for pairs of (packages, overlay packages).
9017            // Note: "android", ie framework-res.apk, is handled by native layers.
9018            if (pkg.mOverlayTarget != null) {
9019                // This is an overlay package.
9020                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9021                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9022                        mOverlays.put(pkg.mOverlayTarget,
9023                                new ArrayMap<String, PackageParser.Package>());
9024                    }
9025                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9026                    map.put(pkg.packageName, pkg);
9027                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9028                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9029                        createIdmapFailed = true;
9030                    }
9031                }
9032            } else if (mOverlays.containsKey(pkg.packageName) &&
9033                    !pkg.packageName.equals("android")) {
9034                // This is a regular package, with one or more known overlay packages.
9035                createIdmapsForPackageLI(pkg);
9036            }
9037        }
9038
9039        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9040
9041        if (createIdmapFailed) {
9042            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9043                    "scanPackageLI failed to createIdmap");
9044        }
9045        return pkg;
9046    }
9047
9048    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9049            PackageParser.Package update, UserHandle user) {
9050        if (existing.applicationInfo == null || update.applicationInfo == null) {
9051            // This isn't due to an app installation.
9052            return;
9053        }
9054
9055        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9056        final File newCodePath = new File(update.applicationInfo.getCodePath());
9057
9058        // The codePath hasn't changed, so there's nothing for us to do.
9059        if (Objects.equals(oldCodePath, newCodePath)) {
9060            return;
9061        }
9062
9063        File canonicalNewCodePath;
9064        try {
9065            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9066        } catch (IOException e) {
9067            Slog.w(TAG, "Failed to get canonical path.", e);
9068            return;
9069        }
9070
9071        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9072        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9073        // that the last component of the path (i.e, the name) doesn't need canonicalization
9074        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9075        // but may change in the future. Hopefully this function won't exist at that point.
9076        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9077                oldCodePath.getName());
9078
9079        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9080        // with "@".
9081        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9082        if (!oldMarkerPrefix.endsWith("@")) {
9083            oldMarkerPrefix += "@";
9084        }
9085        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9086        if (!newMarkerPrefix.endsWith("@")) {
9087            newMarkerPrefix += "@";
9088        }
9089
9090        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9091        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9092        for (String updatedPath : updatedPaths) {
9093            String updatedPathName = new File(updatedPath).getName();
9094            markerSuffixes.add(updatedPathName.replace('/', '@'));
9095        }
9096
9097        for (int userId : resolveUserIds(user.getIdentifier())) {
9098            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9099
9100            for (String markerSuffix : markerSuffixes) {
9101                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9102                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9103                if (oldForeignUseMark.exists()) {
9104                    try {
9105                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9106                                newForeignUseMark.getAbsolutePath());
9107                    } catch (ErrnoException e) {
9108                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9109                        oldForeignUseMark.delete();
9110                    }
9111                }
9112            }
9113        }
9114    }
9115
9116    /**
9117     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9118     * is derived purely on the basis of the contents of {@code scanFile} and
9119     * {@code cpuAbiOverride}.
9120     *
9121     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9122     */
9123    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9124                                 String cpuAbiOverride, boolean extractLibs)
9125            throws PackageManagerException {
9126        // TODO: We can probably be smarter about this stuff. For installed apps,
9127        // we can calculate this information at install time once and for all. For
9128        // system apps, we can probably assume that this information doesn't change
9129        // after the first boot scan. As things stand, we do lots of unnecessary work.
9130
9131        // Give ourselves some initial paths; we'll come back for another
9132        // pass once we've determined ABI below.
9133        setNativeLibraryPaths(pkg);
9134
9135        // We would never need to extract libs for forward-locked and external packages,
9136        // since the container service will do it for us. We shouldn't attempt to
9137        // extract libs from system app when it was not updated.
9138        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9139                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9140            extractLibs = false;
9141        }
9142
9143        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9144        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9145
9146        NativeLibraryHelper.Handle handle = null;
9147        try {
9148            handle = NativeLibraryHelper.Handle.create(pkg);
9149            // TODO(multiArch): This can be null for apps that didn't go through the
9150            // usual installation process. We can calculate it again, like we
9151            // do during install time.
9152            //
9153            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9154            // unnecessary.
9155            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9156
9157            // Null out the abis so that they can be recalculated.
9158            pkg.applicationInfo.primaryCpuAbi = null;
9159            pkg.applicationInfo.secondaryCpuAbi = null;
9160            if (isMultiArch(pkg.applicationInfo)) {
9161                // Warn if we've set an abiOverride for multi-lib packages..
9162                // By definition, we need to copy both 32 and 64 bit libraries for
9163                // such packages.
9164                if (pkg.cpuAbiOverride != null
9165                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9166                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9167                }
9168
9169                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9170                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9171                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9172                    if (extractLibs) {
9173                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9174                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9175                                useIsaSpecificSubdirs);
9176                    } else {
9177                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9178                    }
9179                }
9180
9181                maybeThrowExceptionForMultiArchCopy(
9182                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9183
9184                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9185                    if (extractLibs) {
9186                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9187                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9188                                useIsaSpecificSubdirs);
9189                    } else {
9190                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9191                    }
9192                }
9193
9194                maybeThrowExceptionForMultiArchCopy(
9195                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9196
9197                if (abi64 >= 0) {
9198                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9199                }
9200
9201                if (abi32 >= 0) {
9202                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9203                    if (abi64 >= 0) {
9204                        if (pkg.use32bitAbi) {
9205                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9206                            pkg.applicationInfo.primaryCpuAbi = abi;
9207                        } else {
9208                            pkg.applicationInfo.secondaryCpuAbi = abi;
9209                        }
9210                    } else {
9211                        pkg.applicationInfo.primaryCpuAbi = abi;
9212                    }
9213                }
9214
9215            } else {
9216                String[] abiList = (cpuAbiOverride != null) ?
9217                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9218
9219                // Enable gross and lame hacks for apps that are built with old
9220                // SDK tools. We must scan their APKs for renderscript bitcode and
9221                // not launch them if it's present. Don't bother checking on devices
9222                // that don't have 64 bit support.
9223                boolean needsRenderScriptOverride = false;
9224                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9225                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9226                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9227                    needsRenderScriptOverride = true;
9228                }
9229
9230                final int copyRet;
9231                if (extractLibs) {
9232                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9233                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9234                } else {
9235                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9236                }
9237
9238                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9239                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9240                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9241                }
9242
9243                if (copyRet >= 0) {
9244                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9245                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9246                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9247                } else if (needsRenderScriptOverride) {
9248                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9249                }
9250            }
9251        } catch (IOException ioe) {
9252            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9253        } finally {
9254            IoUtils.closeQuietly(handle);
9255        }
9256
9257        // Now that we've calculated the ABIs and determined if it's an internal app,
9258        // we will go ahead and populate the nativeLibraryPath.
9259        setNativeLibraryPaths(pkg);
9260    }
9261
9262    /**
9263     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9264     * i.e, so that all packages can be run inside a single process if required.
9265     *
9266     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9267     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9268     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9269     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9270     * updating a package that belongs to a shared user.
9271     *
9272     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9273     * adds unnecessary complexity.
9274     */
9275    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9276            PackageParser.Package scannedPackage, boolean bootComplete) {
9277        String requiredInstructionSet = null;
9278        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9279            requiredInstructionSet = VMRuntime.getInstructionSet(
9280                     scannedPackage.applicationInfo.primaryCpuAbi);
9281        }
9282
9283        PackageSetting requirer = null;
9284        for (PackageSetting ps : packagesForUser) {
9285            // If packagesForUser contains scannedPackage, we skip it. This will happen
9286            // when scannedPackage is an update of an existing package. Without this check,
9287            // we will never be able to change the ABI of any package belonging to a shared
9288            // user, even if it's compatible with other packages.
9289            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9290                if (ps.primaryCpuAbiString == null) {
9291                    continue;
9292                }
9293
9294                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9295                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9296                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9297                    // this but there's not much we can do.
9298                    String errorMessage = "Instruction set mismatch, "
9299                            + ((requirer == null) ? "[caller]" : requirer)
9300                            + " requires " + requiredInstructionSet + " whereas " + ps
9301                            + " requires " + instructionSet;
9302                    Slog.w(TAG, errorMessage);
9303                }
9304
9305                if (requiredInstructionSet == null) {
9306                    requiredInstructionSet = instructionSet;
9307                    requirer = ps;
9308                }
9309            }
9310        }
9311
9312        if (requiredInstructionSet != null) {
9313            String adjustedAbi;
9314            if (requirer != null) {
9315                // requirer != null implies that either scannedPackage was null or that scannedPackage
9316                // did not require an ABI, in which case we have to adjust scannedPackage to match
9317                // the ABI of the set (which is the same as requirer's ABI)
9318                adjustedAbi = requirer.primaryCpuAbiString;
9319                if (scannedPackage != null) {
9320                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9321                }
9322            } else {
9323                // requirer == null implies that we're updating all ABIs in the set to
9324                // match scannedPackage.
9325                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9326            }
9327
9328            for (PackageSetting ps : packagesForUser) {
9329                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9330                    if (ps.primaryCpuAbiString != null) {
9331                        continue;
9332                    }
9333
9334                    ps.primaryCpuAbiString = adjustedAbi;
9335                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9336                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9337                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9338                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9339                                + " (requirer="
9340                                + (requirer == null ? "null" : requirer.pkg.packageName)
9341                                + ", scannedPackage="
9342                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9343                                + ")");
9344                        try {
9345                            mInstaller.rmdex(ps.codePathString,
9346                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9347                        } catch (InstallerException ignored) {
9348                        }
9349                    }
9350                }
9351            }
9352        }
9353    }
9354
9355    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9356        synchronized (mPackages) {
9357            mResolverReplaced = true;
9358            // Set up information for custom user intent resolution activity.
9359            mResolveActivity.applicationInfo = pkg.applicationInfo;
9360            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9361            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9362            mResolveActivity.processName = pkg.applicationInfo.packageName;
9363            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9364            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9365                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9366            mResolveActivity.theme = 0;
9367            mResolveActivity.exported = true;
9368            mResolveActivity.enabled = true;
9369            mResolveInfo.activityInfo = mResolveActivity;
9370            mResolveInfo.priority = 0;
9371            mResolveInfo.preferredOrder = 0;
9372            mResolveInfo.match = 0;
9373            mResolveComponentName = mCustomResolverComponentName;
9374            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9375                    mResolveComponentName);
9376        }
9377    }
9378
9379    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9380        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9381
9382        // Set up information for ephemeral installer activity
9383        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9384        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9385        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9386        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9387        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9388        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9389                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9390        mEphemeralInstallerActivity.theme = 0;
9391        mEphemeralInstallerActivity.exported = true;
9392        mEphemeralInstallerActivity.enabled = true;
9393        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9394        mEphemeralInstallerInfo.priority = 0;
9395        mEphemeralInstallerInfo.preferredOrder = 0;
9396        mEphemeralInstallerInfo.match = 0;
9397
9398        if (DEBUG_EPHEMERAL) {
9399            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9400        }
9401    }
9402
9403    private static String calculateBundledApkRoot(final String codePathString) {
9404        final File codePath = new File(codePathString);
9405        final File codeRoot;
9406        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9407            codeRoot = Environment.getRootDirectory();
9408        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9409            codeRoot = Environment.getOemDirectory();
9410        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9411            codeRoot = Environment.getVendorDirectory();
9412        } else {
9413            // Unrecognized code path; take its top real segment as the apk root:
9414            // e.g. /something/app/blah.apk => /something
9415            try {
9416                File f = codePath.getCanonicalFile();
9417                File parent = f.getParentFile();    // non-null because codePath is a file
9418                File tmp;
9419                while ((tmp = parent.getParentFile()) != null) {
9420                    f = parent;
9421                    parent = tmp;
9422                }
9423                codeRoot = f;
9424                Slog.w(TAG, "Unrecognized code path "
9425                        + codePath + " - using " + codeRoot);
9426            } catch (IOException e) {
9427                // Can't canonicalize the code path -- shenanigans?
9428                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9429                return Environment.getRootDirectory().getPath();
9430            }
9431        }
9432        return codeRoot.getPath();
9433    }
9434
9435    /**
9436     * Derive and set the location of native libraries for the given package,
9437     * which varies depending on where and how the package was installed.
9438     */
9439    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9440        final ApplicationInfo info = pkg.applicationInfo;
9441        final String codePath = pkg.codePath;
9442        final File codeFile = new File(codePath);
9443        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9444        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9445
9446        info.nativeLibraryRootDir = null;
9447        info.nativeLibraryRootRequiresIsa = false;
9448        info.nativeLibraryDir = null;
9449        info.secondaryNativeLibraryDir = null;
9450
9451        if (isApkFile(codeFile)) {
9452            // Monolithic install
9453            if (bundledApp) {
9454                // If "/system/lib64/apkname" exists, assume that is the per-package
9455                // native library directory to use; otherwise use "/system/lib/apkname".
9456                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9457                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9458                        getPrimaryInstructionSet(info));
9459
9460                // This is a bundled system app so choose the path based on the ABI.
9461                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9462                // is just the default path.
9463                final String apkName = deriveCodePathName(codePath);
9464                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9465                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9466                        apkName).getAbsolutePath();
9467
9468                if (info.secondaryCpuAbi != null) {
9469                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9470                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9471                            secondaryLibDir, apkName).getAbsolutePath();
9472                }
9473            } else if (asecApp) {
9474                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9475                        .getAbsolutePath();
9476            } else {
9477                final String apkName = deriveCodePathName(codePath);
9478                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9479                        .getAbsolutePath();
9480            }
9481
9482            info.nativeLibraryRootRequiresIsa = false;
9483            info.nativeLibraryDir = info.nativeLibraryRootDir;
9484        } else {
9485            // Cluster install
9486            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9487            info.nativeLibraryRootRequiresIsa = true;
9488
9489            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9490                    getPrimaryInstructionSet(info)).getAbsolutePath();
9491
9492            if (info.secondaryCpuAbi != null) {
9493                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9494                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9495            }
9496        }
9497    }
9498
9499    /**
9500     * Calculate the abis and roots for a bundled app. These can uniquely
9501     * be determined from the contents of the system partition, i.e whether
9502     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9503     * of this information, and instead assume that the system was built
9504     * sensibly.
9505     */
9506    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9507                                           PackageSetting pkgSetting) {
9508        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9509
9510        // If "/system/lib64/apkname" exists, assume that is the per-package
9511        // native library directory to use; otherwise use "/system/lib/apkname".
9512        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9513        setBundledAppAbi(pkg, apkRoot, apkName);
9514        // pkgSetting might be null during rescan following uninstall of updates
9515        // to a bundled app, so accommodate that possibility.  The settings in
9516        // that case will be established later from the parsed package.
9517        //
9518        // If the settings aren't null, sync them up with what we've just derived.
9519        // note that apkRoot isn't stored in the package settings.
9520        if (pkgSetting != null) {
9521            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9522            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9523        }
9524    }
9525
9526    /**
9527     * Deduces the ABI of a bundled app and sets the relevant fields on the
9528     * parsed pkg object.
9529     *
9530     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9531     *        under which system libraries are installed.
9532     * @param apkName the name of the installed package.
9533     */
9534    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9535        final File codeFile = new File(pkg.codePath);
9536
9537        final boolean has64BitLibs;
9538        final boolean has32BitLibs;
9539        if (isApkFile(codeFile)) {
9540            // Monolithic install
9541            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9542            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9543        } else {
9544            // Cluster install
9545            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9546            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9547                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9548                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9549                has64BitLibs = (new File(rootDir, isa)).exists();
9550            } else {
9551                has64BitLibs = false;
9552            }
9553            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9554                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9555                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9556                has32BitLibs = (new File(rootDir, isa)).exists();
9557            } else {
9558                has32BitLibs = false;
9559            }
9560        }
9561
9562        if (has64BitLibs && !has32BitLibs) {
9563            // The package has 64 bit libs, but not 32 bit libs. Its primary
9564            // ABI should be 64 bit. We can safely assume here that the bundled
9565            // native libraries correspond to the most preferred ABI in the list.
9566
9567            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9568            pkg.applicationInfo.secondaryCpuAbi = null;
9569        } else if (has32BitLibs && !has64BitLibs) {
9570            // The package has 32 bit libs but not 64 bit libs. Its primary
9571            // ABI should be 32 bit.
9572
9573            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9574            pkg.applicationInfo.secondaryCpuAbi = null;
9575        } else if (has32BitLibs && has64BitLibs) {
9576            // The application has both 64 and 32 bit bundled libraries. We check
9577            // here that the app declares multiArch support, and warn if it doesn't.
9578            //
9579            // We will be lenient here and record both ABIs. The primary will be the
9580            // ABI that's higher on the list, i.e, a device that's configured to prefer
9581            // 64 bit apps will see a 64 bit primary ABI,
9582
9583            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9584                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9585            }
9586
9587            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9588                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9589                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9590            } else {
9591                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9592                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9593            }
9594        } else {
9595            pkg.applicationInfo.primaryCpuAbi = null;
9596            pkg.applicationInfo.secondaryCpuAbi = null;
9597        }
9598    }
9599
9600    private void killApplication(String pkgName, int appId, String reason) {
9601        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9602    }
9603
9604    private void killApplication(String pkgName, int appId, int userId, String reason) {
9605        // Request the ActivityManager to kill the process(only for existing packages)
9606        // so that we do not end up in a confused state while the user is still using the older
9607        // version of the application while the new one gets installed.
9608        final long token = Binder.clearCallingIdentity();
9609        try {
9610            IActivityManager am = ActivityManagerNative.getDefault();
9611            if (am != null) {
9612                try {
9613                    am.killApplication(pkgName, appId, userId, reason);
9614                } catch (RemoteException e) {
9615                }
9616            }
9617        } finally {
9618            Binder.restoreCallingIdentity(token);
9619        }
9620    }
9621
9622    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9623        // Remove the parent package setting
9624        PackageSetting ps = (PackageSetting) pkg.mExtras;
9625        if (ps != null) {
9626            removePackageLI(ps, chatty);
9627        }
9628        // Remove the child package setting
9629        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9630        for (int i = 0; i < childCount; i++) {
9631            PackageParser.Package childPkg = pkg.childPackages.get(i);
9632            ps = (PackageSetting) childPkg.mExtras;
9633            if (ps != null) {
9634                removePackageLI(ps, chatty);
9635            }
9636        }
9637    }
9638
9639    void removePackageLI(PackageSetting ps, boolean chatty) {
9640        if (DEBUG_INSTALL) {
9641            if (chatty)
9642                Log.d(TAG, "Removing package " + ps.name);
9643        }
9644
9645        // writer
9646        synchronized (mPackages) {
9647            mPackages.remove(ps.name);
9648            final PackageParser.Package pkg = ps.pkg;
9649            if (pkg != null) {
9650                cleanPackageDataStructuresLILPw(pkg, chatty);
9651            }
9652        }
9653    }
9654
9655    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9656        if (DEBUG_INSTALL) {
9657            if (chatty)
9658                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9659        }
9660
9661        // writer
9662        synchronized (mPackages) {
9663            // Remove the parent package
9664            mPackages.remove(pkg.applicationInfo.packageName);
9665            cleanPackageDataStructuresLILPw(pkg, chatty);
9666
9667            // Remove the child packages
9668            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9669            for (int i = 0; i < childCount; i++) {
9670                PackageParser.Package childPkg = pkg.childPackages.get(i);
9671                mPackages.remove(childPkg.applicationInfo.packageName);
9672                cleanPackageDataStructuresLILPw(childPkg, chatty);
9673            }
9674        }
9675    }
9676
9677    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9678        int N = pkg.providers.size();
9679        StringBuilder r = null;
9680        int i;
9681        for (i=0; i<N; i++) {
9682            PackageParser.Provider p = pkg.providers.get(i);
9683            mProviders.removeProvider(p);
9684            if (p.info.authority == null) {
9685
9686                /* There was another ContentProvider with this authority when
9687                 * this app was installed so this authority is null,
9688                 * Ignore it as we don't have to unregister the provider.
9689                 */
9690                continue;
9691            }
9692            String names[] = p.info.authority.split(";");
9693            for (int j = 0; j < names.length; j++) {
9694                if (mProvidersByAuthority.get(names[j]) == p) {
9695                    mProvidersByAuthority.remove(names[j]);
9696                    if (DEBUG_REMOVE) {
9697                        if (chatty)
9698                            Log.d(TAG, "Unregistered content provider: " + names[j]
9699                                    + ", className = " + p.info.name + ", isSyncable = "
9700                                    + p.info.isSyncable);
9701                    }
9702                }
9703            }
9704            if (DEBUG_REMOVE && chatty) {
9705                if (r == null) {
9706                    r = new StringBuilder(256);
9707                } else {
9708                    r.append(' ');
9709                }
9710                r.append(p.info.name);
9711            }
9712        }
9713        if (r != null) {
9714            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9715        }
9716
9717        N = pkg.services.size();
9718        r = null;
9719        for (i=0; i<N; i++) {
9720            PackageParser.Service s = pkg.services.get(i);
9721            mServices.removeService(s);
9722            if (chatty) {
9723                if (r == null) {
9724                    r = new StringBuilder(256);
9725                } else {
9726                    r.append(' ');
9727                }
9728                r.append(s.info.name);
9729            }
9730        }
9731        if (r != null) {
9732            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9733        }
9734
9735        N = pkg.receivers.size();
9736        r = null;
9737        for (i=0; i<N; i++) {
9738            PackageParser.Activity a = pkg.receivers.get(i);
9739            mReceivers.removeActivity(a, "receiver");
9740            if (DEBUG_REMOVE && chatty) {
9741                if (r == null) {
9742                    r = new StringBuilder(256);
9743                } else {
9744                    r.append(' ');
9745                }
9746                r.append(a.info.name);
9747            }
9748        }
9749        if (r != null) {
9750            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9751        }
9752
9753        N = pkg.activities.size();
9754        r = null;
9755        for (i=0; i<N; i++) {
9756            PackageParser.Activity a = pkg.activities.get(i);
9757            mActivities.removeActivity(a, "activity");
9758            if (DEBUG_REMOVE && chatty) {
9759                if (r == null) {
9760                    r = new StringBuilder(256);
9761                } else {
9762                    r.append(' ');
9763                }
9764                r.append(a.info.name);
9765            }
9766        }
9767        if (r != null) {
9768            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9769        }
9770
9771        N = pkg.permissions.size();
9772        r = null;
9773        for (i=0; i<N; i++) {
9774            PackageParser.Permission p = pkg.permissions.get(i);
9775            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9776            if (bp == null) {
9777                bp = mSettings.mPermissionTrees.get(p.info.name);
9778            }
9779            if (bp != null && bp.perm == p) {
9780                bp.perm = null;
9781                if (DEBUG_REMOVE && chatty) {
9782                    if (r == null) {
9783                        r = new StringBuilder(256);
9784                    } else {
9785                        r.append(' ');
9786                    }
9787                    r.append(p.info.name);
9788                }
9789            }
9790            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9791                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9792                if (appOpPkgs != null) {
9793                    appOpPkgs.remove(pkg.packageName);
9794                }
9795            }
9796        }
9797        if (r != null) {
9798            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9799        }
9800
9801        N = pkg.requestedPermissions.size();
9802        r = null;
9803        for (i=0; i<N; i++) {
9804            String perm = pkg.requestedPermissions.get(i);
9805            BasePermission bp = mSettings.mPermissions.get(perm);
9806            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9807                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9808                if (appOpPkgs != null) {
9809                    appOpPkgs.remove(pkg.packageName);
9810                    if (appOpPkgs.isEmpty()) {
9811                        mAppOpPermissionPackages.remove(perm);
9812                    }
9813                }
9814            }
9815        }
9816        if (r != null) {
9817            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9818        }
9819
9820        N = pkg.instrumentation.size();
9821        r = null;
9822        for (i=0; i<N; i++) {
9823            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9824            mInstrumentation.remove(a.getComponentName());
9825            if (DEBUG_REMOVE && chatty) {
9826                if (r == null) {
9827                    r = new StringBuilder(256);
9828                } else {
9829                    r.append(' ');
9830                }
9831                r.append(a.info.name);
9832            }
9833        }
9834        if (r != null) {
9835            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9836        }
9837
9838        r = null;
9839        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9840            // Only system apps can hold shared libraries.
9841            if (pkg.libraryNames != null) {
9842                for (i=0; i<pkg.libraryNames.size(); i++) {
9843                    String name = pkg.libraryNames.get(i);
9844                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9845                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9846                        mSharedLibraries.remove(name);
9847                        if (DEBUG_REMOVE && chatty) {
9848                            if (r == null) {
9849                                r = new StringBuilder(256);
9850                            } else {
9851                                r.append(' ');
9852                            }
9853                            r.append(name);
9854                        }
9855                    }
9856                }
9857            }
9858        }
9859        if (r != null) {
9860            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9861        }
9862    }
9863
9864    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9865        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9866            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9867                return true;
9868            }
9869        }
9870        return false;
9871    }
9872
9873    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9874    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9875    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9876
9877    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9878        // Update the parent permissions
9879        updatePermissionsLPw(pkg.packageName, pkg, flags);
9880        // Update the child permissions
9881        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9882        for (int i = 0; i < childCount; i++) {
9883            PackageParser.Package childPkg = pkg.childPackages.get(i);
9884            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9885        }
9886    }
9887
9888    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9889            int flags) {
9890        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9891        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9892    }
9893
9894    private void updatePermissionsLPw(String changingPkg,
9895            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9896        // Make sure there are no dangling permission trees.
9897        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9898        while (it.hasNext()) {
9899            final BasePermission bp = it.next();
9900            if (bp.packageSetting == null) {
9901                // We may not yet have parsed the package, so just see if
9902                // we still know about its settings.
9903                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9904            }
9905            if (bp.packageSetting == null) {
9906                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9907                        + " from package " + bp.sourcePackage);
9908                it.remove();
9909            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9910                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9911                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9912                            + " from package " + bp.sourcePackage);
9913                    flags |= UPDATE_PERMISSIONS_ALL;
9914                    it.remove();
9915                }
9916            }
9917        }
9918
9919        // Make sure all dynamic permissions have been assigned to a package,
9920        // and make sure there are no dangling permissions.
9921        it = mSettings.mPermissions.values().iterator();
9922        while (it.hasNext()) {
9923            final BasePermission bp = it.next();
9924            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9925                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9926                        + bp.name + " pkg=" + bp.sourcePackage
9927                        + " info=" + bp.pendingInfo);
9928                if (bp.packageSetting == null && bp.pendingInfo != null) {
9929                    final BasePermission tree = findPermissionTreeLP(bp.name);
9930                    if (tree != null && tree.perm != null) {
9931                        bp.packageSetting = tree.packageSetting;
9932                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9933                                new PermissionInfo(bp.pendingInfo));
9934                        bp.perm.info.packageName = tree.perm.info.packageName;
9935                        bp.perm.info.name = bp.name;
9936                        bp.uid = tree.uid;
9937                    }
9938                }
9939            }
9940            if (bp.packageSetting == null) {
9941                // We may not yet have parsed the package, so just see if
9942                // we still know about its settings.
9943                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9944            }
9945            if (bp.packageSetting == null) {
9946                Slog.w(TAG, "Removing dangling permission: " + bp.name
9947                        + " from package " + bp.sourcePackage);
9948                it.remove();
9949            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9950                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9951                    Slog.i(TAG, "Removing old permission: " + bp.name
9952                            + " from package " + bp.sourcePackage);
9953                    flags |= UPDATE_PERMISSIONS_ALL;
9954                    it.remove();
9955                }
9956            }
9957        }
9958
9959        // Now update the permissions for all packages, in particular
9960        // replace the granted permissions of the system packages.
9961        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9962            for (PackageParser.Package pkg : mPackages.values()) {
9963                if (pkg != pkgInfo) {
9964                    // Only replace for packages on requested volume
9965                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9966                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9967                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9968                    grantPermissionsLPw(pkg, replace, changingPkg);
9969                }
9970            }
9971        }
9972
9973        if (pkgInfo != null) {
9974            // Only replace for packages on requested volume
9975            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9976            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9977                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9978            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9979        }
9980    }
9981
9982    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9983            String packageOfInterest) {
9984        // IMPORTANT: There are two types of permissions: install and runtime.
9985        // Install time permissions are granted when the app is installed to
9986        // all device users and users added in the future. Runtime permissions
9987        // are granted at runtime explicitly to specific users. Normal and signature
9988        // protected permissions are install time permissions. Dangerous permissions
9989        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9990        // otherwise they are runtime permissions. This function does not manage
9991        // runtime permissions except for the case an app targeting Lollipop MR1
9992        // being upgraded to target a newer SDK, in which case dangerous permissions
9993        // are transformed from install time to runtime ones.
9994
9995        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9996        if (ps == null) {
9997            return;
9998        }
9999
10000        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10001
10002        PermissionsState permissionsState = ps.getPermissionsState();
10003        PermissionsState origPermissions = permissionsState;
10004
10005        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10006
10007        boolean runtimePermissionsRevoked = false;
10008        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10009
10010        boolean changedInstallPermission = false;
10011
10012        if (replace) {
10013            ps.installPermissionsFixed = false;
10014            if (!ps.isSharedUser()) {
10015                origPermissions = new PermissionsState(permissionsState);
10016                permissionsState.reset();
10017            } else {
10018                // We need to know only about runtime permission changes since the
10019                // calling code always writes the install permissions state but
10020                // the runtime ones are written only if changed. The only cases of
10021                // changed runtime permissions here are promotion of an install to
10022                // runtime and revocation of a runtime from a shared user.
10023                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10024                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10025                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10026                    runtimePermissionsRevoked = true;
10027                }
10028            }
10029        }
10030
10031        permissionsState.setGlobalGids(mGlobalGids);
10032
10033        final int N = pkg.requestedPermissions.size();
10034        for (int i=0; i<N; i++) {
10035            final String name = pkg.requestedPermissions.get(i);
10036            final BasePermission bp = mSettings.mPermissions.get(name);
10037
10038            if (DEBUG_INSTALL) {
10039                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10040            }
10041
10042            if (bp == null || bp.packageSetting == null) {
10043                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10044                    Slog.w(TAG, "Unknown permission " + name
10045                            + " in package " + pkg.packageName);
10046                }
10047                continue;
10048            }
10049
10050            final String perm = bp.name;
10051            boolean allowedSig = false;
10052            int grant = GRANT_DENIED;
10053
10054            // Keep track of app op permissions.
10055            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10056                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10057                if (pkgs == null) {
10058                    pkgs = new ArraySet<>();
10059                    mAppOpPermissionPackages.put(bp.name, pkgs);
10060                }
10061                pkgs.add(pkg.packageName);
10062            }
10063
10064            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10065            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10066                    >= Build.VERSION_CODES.M;
10067            switch (level) {
10068                case PermissionInfo.PROTECTION_NORMAL: {
10069                    // For all apps normal permissions are install time ones.
10070                    grant = GRANT_INSTALL;
10071                } break;
10072
10073                case PermissionInfo.PROTECTION_DANGEROUS: {
10074                    // If a permission review is required for legacy apps we represent
10075                    // their permissions as always granted runtime ones since we need
10076                    // to keep the review required permission flag per user while an
10077                    // install permission's state is shared across all users.
10078                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10079                        // For legacy apps dangerous permissions are install time ones.
10080                        grant = GRANT_INSTALL;
10081                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10082                        // For legacy apps that became modern, install becomes runtime.
10083                        grant = GRANT_UPGRADE;
10084                    } else if (mPromoteSystemApps
10085                            && isSystemApp(ps)
10086                            && mExistingSystemPackages.contains(ps.name)) {
10087                        // For legacy system apps, install becomes runtime.
10088                        // We cannot check hasInstallPermission() for system apps since those
10089                        // permissions were granted implicitly and not persisted pre-M.
10090                        grant = GRANT_UPGRADE;
10091                    } else {
10092                        // For modern apps keep runtime permissions unchanged.
10093                        grant = GRANT_RUNTIME;
10094                    }
10095                } break;
10096
10097                case PermissionInfo.PROTECTION_SIGNATURE: {
10098                    // For all apps signature permissions are install time ones.
10099                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10100                    if (allowedSig) {
10101                        grant = GRANT_INSTALL;
10102                    }
10103                } break;
10104            }
10105
10106            if (DEBUG_INSTALL) {
10107                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10108            }
10109
10110            if (grant != GRANT_DENIED) {
10111                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10112                    // If this is an existing, non-system package, then
10113                    // we can't add any new permissions to it.
10114                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10115                        // Except...  if this is a permission that was added
10116                        // to the platform (note: need to only do this when
10117                        // updating the platform).
10118                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10119                            grant = GRANT_DENIED;
10120                        }
10121                    }
10122                }
10123
10124                switch (grant) {
10125                    case GRANT_INSTALL: {
10126                        // Revoke this as runtime permission to handle the case of
10127                        // a runtime permission being downgraded to an install one.
10128                        // Also in permission review mode we keep dangerous permissions
10129                        // for legacy apps
10130                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10131                            if (origPermissions.getRuntimePermissionState(
10132                                    bp.name, userId) != null) {
10133                                // Revoke the runtime permission and clear the flags.
10134                                origPermissions.revokeRuntimePermission(bp, userId);
10135                                origPermissions.updatePermissionFlags(bp, userId,
10136                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10137                                // If we revoked a permission permission, we have to write.
10138                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10139                                        changedRuntimePermissionUserIds, userId);
10140                            }
10141                        }
10142                        // Grant an install permission.
10143                        if (permissionsState.grantInstallPermission(bp) !=
10144                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10145                            changedInstallPermission = true;
10146                        }
10147                    } break;
10148
10149                    case GRANT_RUNTIME: {
10150                        // Grant previously granted runtime permissions.
10151                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10152                            PermissionState permissionState = origPermissions
10153                                    .getRuntimePermissionState(bp.name, userId);
10154                            int flags = permissionState != null
10155                                    ? permissionState.getFlags() : 0;
10156                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10157                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10158                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10159                                    // If we cannot put the permission as it was, we have to write.
10160                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10161                                            changedRuntimePermissionUserIds, userId);
10162                                }
10163                                // If the app supports runtime permissions no need for a review.
10164                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10165                                        && appSupportsRuntimePermissions
10166                                        && (flags & PackageManager
10167                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10168                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10169                                    // Since we changed the flags, we have to write.
10170                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10171                                            changedRuntimePermissionUserIds, userId);
10172                                }
10173                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10174                                    && !appSupportsRuntimePermissions) {
10175                                // For legacy apps that need a permission review, every new
10176                                // runtime permission is granted but it is pending a review.
10177                                // We also need to review only platform defined runtime
10178                                // permissions as these are the only ones the platform knows
10179                                // how to disable the API to simulate revocation as legacy
10180                                // apps don't expect to run with revoked permissions.
10181                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10182                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10183                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10184                                        // We changed the flags, hence have to write.
10185                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10186                                                changedRuntimePermissionUserIds, userId);
10187                                    }
10188                                }
10189                                if (permissionsState.grantRuntimePermission(bp, userId)
10190                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10191                                    // We changed the permission, hence have to write.
10192                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10193                                            changedRuntimePermissionUserIds, userId);
10194                                }
10195                            }
10196                            // Propagate the permission flags.
10197                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10198                        }
10199                    } break;
10200
10201                    case GRANT_UPGRADE: {
10202                        // Grant runtime permissions for a previously held install permission.
10203                        PermissionState permissionState = origPermissions
10204                                .getInstallPermissionState(bp.name);
10205                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10206
10207                        if (origPermissions.revokeInstallPermission(bp)
10208                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10209                            // We will be transferring the permission flags, so clear them.
10210                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10211                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10212                            changedInstallPermission = true;
10213                        }
10214
10215                        // If the permission is not to be promoted to runtime we ignore it and
10216                        // also its other flags as they are not applicable to install permissions.
10217                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10218                            for (int userId : currentUserIds) {
10219                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10220                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10221                                    // Transfer the permission flags.
10222                                    permissionsState.updatePermissionFlags(bp, userId,
10223                                            flags, flags);
10224                                    // If we granted the permission, we have to write.
10225                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10226                                            changedRuntimePermissionUserIds, userId);
10227                                }
10228                            }
10229                        }
10230                    } break;
10231
10232                    default: {
10233                        if (packageOfInterest == null
10234                                || packageOfInterest.equals(pkg.packageName)) {
10235                            Slog.w(TAG, "Not granting permission " + perm
10236                                    + " to package " + pkg.packageName
10237                                    + " because it was previously installed without");
10238                        }
10239                    } break;
10240                }
10241            } else {
10242                if (permissionsState.revokeInstallPermission(bp) !=
10243                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10244                    // Also drop the permission flags.
10245                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10246                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10247                    changedInstallPermission = true;
10248                    Slog.i(TAG, "Un-granting permission " + perm
10249                            + " from package " + pkg.packageName
10250                            + " (protectionLevel=" + bp.protectionLevel
10251                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10252                            + ")");
10253                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10254                    // Don't print warning for app op permissions, since it is fine for them
10255                    // not to be granted, there is a UI for the user to decide.
10256                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10257                        Slog.w(TAG, "Not granting permission " + perm
10258                                + " to package " + pkg.packageName
10259                                + " (protectionLevel=" + bp.protectionLevel
10260                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10261                                + ")");
10262                    }
10263                }
10264            }
10265        }
10266
10267        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10268                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10269            // This is the first that we have heard about this package, so the
10270            // permissions we have now selected are fixed until explicitly
10271            // changed.
10272            ps.installPermissionsFixed = true;
10273        }
10274
10275        // Persist the runtime permissions state for users with changes. If permissions
10276        // were revoked because no app in the shared user declares them we have to
10277        // write synchronously to avoid losing runtime permissions state.
10278        for (int userId : changedRuntimePermissionUserIds) {
10279            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10280        }
10281
10282        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10283    }
10284
10285    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10286        boolean allowed = false;
10287        final int NP = PackageParser.NEW_PERMISSIONS.length;
10288        for (int ip=0; ip<NP; ip++) {
10289            final PackageParser.NewPermissionInfo npi
10290                    = PackageParser.NEW_PERMISSIONS[ip];
10291            if (npi.name.equals(perm)
10292                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10293                allowed = true;
10294                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10295                        + pkg.packageName);
10296                break;
10297            }
10298        }
10299        return allowed;
10300    }
10301
10302    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10303            BasePermission bp, PermissionsState origPermissions) {
10304        boolean allowed;
10305        allowed = (compareSignatures(
10306                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10307                        == PackageManager.SIGNATURE_MATCH)
10308                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10309                        == PackageManager.SIGNATURE_MATCH);
10310        if (!allowed && (bp.protectionLevel
10311                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10312            if (isSystemApp(pkg)) {
10313                // For updated system applications, a system permission
10314                // is granted only if it had been defined by the original application.
10315                if (pkg.isUpdatedSystemApp()) {
10316                    final PackageSetting sysPs = mSettings
10317                            .getDisabledSystemPkgLPr(pkg.packageName);
10318                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10319                        // If the original was granted this permission, we take
10320                        // that grant decision as read and propagate it to the
10321                        // update.
10322                        if (sysPs.isPrivileged()) {
10323                            allowed = true;
10324                        }
10325                    } else {
10326                        // The system apk may have been updated with an older
10327                        // version of the one on the data partition, but which
10328                        // granted a new system permission that it didn't have
10329                        // before.  In this case we do want to allow the app to
10330                        // now get the new permission if the ancestral apk is
10331                        // privileged to get it.
10332                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10333                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10334                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10335                                    allowed = true;
10336                                    break;
10337                                }
10338                            }
10339                        }
10340                        // Also if a privileged parent package on the system image or any of
10341                        // its children requested a privileged permission, the updated child
10342                        // packages can also get the permission.
10343                        if (pkg.parentPackage != null) {
10344                            final PackageSetting disabledSysParentPs = mSettings
10345                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10346                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10347                                    && disabledSysParentPs.isPrivileged()) {
10348                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10349                                    allowed = true;
10350                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10351                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10352                                    for (int i = 0; i < count; i++) {
10353                                        PackageParser.Package disabledSysChildPkg =
10354                                                disabledSysParentPs.pkg.childPackages.get(i);
10355                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10356                                                perm)) {
10357                                            allowed = true;
10358                                            break;
10359                                        }
10360                                    }
10361                                }
10362                            }
10363                        }
10364                    }
10365                } else {
10366                    allowed = isPrivilegedApp(pkg);
10367                }
10368            }
10369        }
10370        if (!allowed) {
10371            if (!allowed && (bp.protectionLevel
10372                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10373                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10374                // If this was a previously normal/dangerous permission that got moved
10375                // to a system permission as part of the runtime permission redesign, then
10376                // we still want to blindly grant it to old apps.
10377                allowed = true;
10378            }
10379            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10380                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10381                // If this permission is to be granted to the system installer and
10382                // this app is an installer, then it gets the permission.
10383                allowed = true;
10384            }
10385            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10386                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10387                // If this permission is to be granted to the system verifier and
10388                // this app is a verifier, then it gets the permission.
10389                allowed = true;
10390            }
10391            if (!allowed && (bp.protectionLevel
10392                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10393                    && isSystemApp(pkg)) {
10394                // Any pre-installed system app is allowed to get this permission.
10395                allowed = true;
10396            }
10397            if (!allowed && (bp.protectionLevel
10398                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10399                // For development permissions, a development permission
10400                // is granted only if it was already granted.
10401                allowed = origPermissions.hasInstallPermission(perm);
10402            }
10403            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10404                    && pkg.packageName.equals(mSetupWizardPackage)) {
10405                // If this permission is to be granted to the system setup wizard and
10406                // this app is a setup wizard, then it gets the permission.
10407                allowed = true;
10408            }
10409        }
10410        return allowed;
10411    }
10412
10413    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10414        final int permCount = pkg.requestedPermissions.size();
10415        for (int j = 0; j < permCount; j++) {
10416            String requestedPermission = pkg.requestedPermissions.get(j);
10417            if (permission.equals(requestedPermission)) {
10418                return true;
10419            }
10420        }
10421        return false;
10422    }
10423
10424    final class ActivityIntentResolver
10425            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10426        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10427                boolean defaultOnly, int userId) {
10428            if (!sUserManager.exists(userId)) return null;
10429            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10430            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10431        }
10432
10433        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10434                int userId) {
10435            if (!sUserManager.exists(userId)) return null;
10436            mFlags = flags;
10437            return super.queryIntent(intent, resolvedType,
10438                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10439        }
10440
10441        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10442                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10443            if (!sUserManager.exists(userId)) return null;
10444            if (packageActivities == null) {
10445                return null;
10446            }
10447            mFlags = flags;
10448            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10449            final int N = packageActivities.size();
10450            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10451                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10452
10453            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10454            for (int i = 0; i < N; ++i) {
10455                intentFilters = packageActivities.get(i).intents;
10456                if (intentFilters != null && intentFilters.size() > 0) {
10457                    PackageParser.ActivityIntentInfo[] array =
10458                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10459                    intentFilters.toArray(array);
10460                    listCut.add(array);
10461                }
10462            }
10463            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10464        }
10465
10466        /**
10467         * Finds a privileged activity that matches the specified activity names.
10468         */
10469        private PackageParser.Activity findMatchingActivity(
10470                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10471            for (PackageParser.Activity sysActivity : activityList) {
10472                if (sysActivity.info.name.equals(activityInfo.name)) {
10473                    return sysActivity;
10474                }
10475                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10476                    return sysActivity;
10477                }
10478                if (sysActivity.info.targetActivity != null) {
10479                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10480                        return sysActivity;
10481                    }
10482                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10483                        return sysActivity;
10484                    }
10485                }
10486            }
10487            return null;
10488        }
10489
10490        public class IterGenerator<E> {
10491            public Iterator<E> generate(ActivityIntentInfo info) {
10492                return null;
10493            }
10494        }
10495
10496        public class ActionIterGenerator extends IterGenerator<String> {
10497            @Override
10498            public Iterator<String> generate(ActivityIntentInfo info) {
10499                return info.actionsIterator();
10500            }
10501        }
10502
10503        public class CategoriesIterGenerator extends IterGenerator<String> {
10504            @Override
10505            public Iterator<String> generate(ActivityIntentInfo info) {
10506                return info.categoriesIterator();
10507            }
10508        }
10509
10510        public class SchemesIterGenerator extends IterGenerator<String> {
10511            @Override
10512            public Iterator<String> generate(ActivityIntentInfo info) {
10513                return info.schemesIterator();
10514            }
10515        }
10516
10517        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10518            @Override
10519            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10520                return info.authoritiesIterator();
10521            }
10522        }
10523
10524        /**
10525         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10526         * MODIFIED. Do not pass in a list that should not be changed.
10527         */
10528        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10529                IterGenerator<T> generator, Iterator<T> searchIterator) {
10530            // loop through the set of actions; every one must be found in the intent filter
10531            while (searchIterator.hasNext()) {
10532                // we must have at least one filter in the list to consider a match
10533                if (intentList.size() == 0) {
10534                    break;
10535                }
10536
10537                final T searchAction = searchIterator.next();
10538
10539                // loop through the set of intent filters
10540                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10541                while (intentIter.hasNext()) {
10542                    final ActivityIntentInfo intentInfo = intentIter.next();
10543                    boolean selectionFound = false;
10544
10545                    // loop through the intent filter's selection criteria; at least one
10546                    // of them must match the searched criteria
10547                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10548                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10549                        final T intentSelection = intentSelectionIter.next();
10550                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10551                            selectionFound = true;
10552                            break;
10553                        }
10554                    }
10555
10556                    // the selection criteria wasn't found in this filter's set; this filter
10557                    // is not a potential match
10558                    if (!selectionFound) {
10559                        intentIter.remove();
10560                    }
10561                }
10562            }
10563        }
10564
10565        private boolean isProtectedAction(ActivityIntentInfo filter) {
10566            final Iterator<String> actionsIter = filter.actionsIterator();
10567            while (actionsIter != null && actionsIter.hasNext()) {
10568                final String filterAction = actionsIter.next();
10569                if (PROTECTED_ACTIONS.contains(filterAction)) {
10570                    return true;
10571                }
10572            }
10573            return false;
10574        }
10575
10576        /**
10577         * Adjusts the priority of the given intent filter according to policy.
10578         * <p>
10579         * <ul>
10580         * <li>The priority for non privileged applications is capped to '0'</li>
10581         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10582         * <li>The priority for unbundled updates to privileged applications is capped to the
10583         *      priority defined on the system partition</li>
10584         * </ul>
10585         * <p>
10586         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10587         * allowed to obtain any priority on any action.
10588         */
10589        private void adjustPriority(
10590                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10591            // nothing to do; priority is fine as-is
10592            if (intent.getPriority() <= 0) {
10593                return;
10594            }
10595
10596            final ActivityInfo activityInfo = intent.activity.info;
10597            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10598
10599            final boolean privilegedApp =
10600                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10601            if (!privilegedApp) {
10602                // non-privileged applications can never define a priority >0
10603                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10604                        + " package: " + applicationInfo.packageName
10605                        + " activity: " + intent.activity.className
10606                        + " origPrio: " + intent.getPriority());
10607                intent.setPriority(0);
10608                return;
10609            }
10610
10611            if (systemActivities == null) {
10612                // the system package is not disabled; we're parsing the system partition
10613                if (isProtectedAction(intent)) {
10614                    if (mDeferProtectedFilters) {
10615                        // We can't deal with these just yet. No component should ever obtain a
10616                        // >0 priority for a protected actions, with ONE exception -- the setup
10617                        // wizard. The setup wizard, however, cannot be known until we're able to
10618                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10619                        // until all intent filters have been processed. Chicken, meet egg.
10620                        // Let the filter temporarily have a high priority and rectify the
10621                        // priorities after all system packages have been scanned.
10622                        mProtectedFilters.add(intent);
10623                        if (DEBUG_FILTERS) {
10624                            Slog.i(TAG, "Protected action; save for later;"
10625                                    + " package: " + applicationInfo.packageName
10626                                    + " activity: " + intent.activity.className
10627                                    + " origPrio: " + intent.getPriority());
10628                        }
10629                        return;
10630                    } else {
10631                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10632                            Slog.i(TAG, "No setup wizard;"
10633                                + " All protected intents capped to priority 0");
10634                        }
10635                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10636                            if (DEBUG_FILTERS) {
10637                                Slog.i(TAG, "Found setup wizard;"
10638                                    + " allow priority " + intent.getPriority() + ";"
10639                                    + " package: " + intent.activity.info.packageName
10640                                    + " activity: " + intent.activity.className
10641                                    + " priority: " + intent.getPriority());
10642                            }
10643                            // setup wizard gets whatever it wants
10644                            return;
10645                        }
10646                        Slog.w(TAG, "Protected action; cap priority to 0;"
10647                                + " package: " + intent.activity.info.packageName
10648                                + " activity: " + intent.activity.className
10649                                + " origPrio: " + intent.getPriority());
10650                        intent.setPriority(0);
10651                        return;
10652                    }
10653                }
10654                // privileged apps on the system image get whatever priority they request
10655                return;
10656            }
10657
10658            // privileged app unbundled update ... try to find the same activity
10659            final PackageParser.Activity foundActivity =
10660                    findMatchingActivity(systemActivities, activityInfo);
10661            if (foundActivity == null) {
10662                // this is a new activity; it cannot obtain >0 priority
10663                if (DEBUG_FILTERS) {
10664                    Slog.i(TAG, "New activity; cap priority to 0;"
10665                            + " package: " + applicationInfo.packageName
10666                            + " activity: " + intent.activity.className
10667                            + " origPrio: " + intent.getPriority());
10668                }
10669                intent.setPriority(0);
10670                return;
10671            }
10672
10673            // found activity, now check for filter equivalence
10674
10675            // a shallow copy is enough; we modify the list, not its contents
10676            final List<ActivityIntentInfo> intentListCopy =
10677                    new ArrayList<>(foundActivity.intents);
10678            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10679
10680            // find matching action subsets
10681            final Iterator<String> actionsIterator = intent.actionsIterator();
10682            if (actionsIterator != null) {
10683                getIntentListSubset(
10684                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10685                if (intentListCopy.size() == 0) {
10686                    // no more intents to match; we're not equivalent
10687                    if (DEBUG_FILTERS) {
10688                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10689                                + " package: " + applicationInfo.packageName
10690                                + " activity: " + intent.activity.className
10691                                + " origPrio: " + intent.getPriority());
10692                    }
10693                    intent.setPriority(0);
10694                    return;
10695                }
10696            }
10697
10698            // find matching category subsets
10699            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10700            if (categoriesIterator != null) {
10701                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10702                        categoriesIterator);
10703                if (intentListCopy.size() == 0) {
10704                    // no more intents to match; we're not equivalent
10705                    if (DEBUG_FILTERS) {
10706                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10707                                + " package: " + applicationInfo.packageName
10708                                + " activity: " + intent.activity.className
10709                                + " origPrio: " + intent.getPriority());
10710                    }
10711                    intent.setPriority(0);
10712                    return;
10713                }
10714            }
10715
10716            // find matching schemes subsets
10717            final Iterator<String> schemesIterator = intent.schemesIterator();
10718            if (schemesIterator != null) {
10719                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10720                        schemesIterator);
10721                if (intentListCopy.size() == 0) {
10722                    // no more intents to match; we're not equivalent
10723                    if (DEBUG_FILTERS) {
10724                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10725                                + " package: " + applicationInfo.packageName
10726                                + " activity: " + intent.activity.className
10727                                + " origPrio: " + intent.getPriority());
10728                    }
10729                    intent.setPriority(0);
10730                    return;
10731                }
10732            }
10733
10734            // find matching authorities subsets
10735            final Iterator<IntentFilter.AuthorityEntry>
10736                    authoritiesIterator = intent.authoritiesIterator();
10737            if (authoritiesIterator != null) {
10738                getIntentListSubset(intentListCopy,
10739                        new AuthoritiesIterGenerator(),
10740                        authoritiesIterator);
10741                if (intentListCopy.size() == 0) {
10742                    // no more intents to match; we're not equivalent
10743                    if (DEBUG_FILTERS) {
10744                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10745                                + " package: " + applicationInfo.packageName
10746                                + " activity: " + intent.activity.className
10747                                + " origPrio: " + intent.getPriority());
10748                    }
10749                    intent.setPriority(0);
10750                    return;
10751                }
10752            }
10753
10754            // we found matching filter(s); app gets the max priority of all intents
10755            int cappedPriority = 0;
10756            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10757                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10758            }
10759            if (intent.getPriority() > cappedPriority) {
10760                if (DEBUG_FILTERS) {
10761                    Slog.i(TAG, "Found matching filter(s);"
10762                            + " cap priority to " + cappedPriority + ";"
10763                            + " package: " + applicationInfo.packageName
10764                            + " activity: " + intent.activity.className
10765                            + " origPrio: " + intent.getPriority());
10766                }
10767                intent.setPriority(cappedPriority);
10768                return;
10769            }
10770            // all this for nothing; the requested priority was <= what was on the system
10771        }
10772
10773        public final void addActivity(PackageParser.Activity a, String type) {
10774            mActivities.put(a.getComponentName(), a);
10775            if (DEBUG_SHOW_INFO)
10776                Log.v(
10777                TAG, "  " + type + " " +
10778                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10779            if (DEBUG_SHOW_INFO)
10780                Log.v(TAG, "    Class=" + a.info.name);
10781            final int NI = a.intents.size();
10782            for (int j=0; j<NI; j++) {
10783                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10784                if ("activity".equals(type)) {
10785                    final PackageSetting ps =
10786                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10787                    final List<PackageParser.Activity> systemActivities =
10788                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10789                    adjustPriority(systemActivities, intent);
10790                }
10791                if (DEBUG_SHOW_INFO) {
10792                    Log.v(TAG, "    IntentFilter:");
10793                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10794                }
10795                if (!intent.debugCheck()) {
10796                    Log.w(TAG, "==> For Activity " + a.info.name);
10797                }
10798                addFilter(intent);
10799            }
10800        }
10801
10802        public final void removeActivity(PackageParser.Activity a, String type) {
10803            mActivities.remove(a.getComponentName());
10804            if (DEBUG_SHOW_INFO) {
10805                Log.v(TAG, "  " + type + " "
10806                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10807                                : a.info.name) + ":");
10808                Log.v(TAG, "    Class=" + a.info.name);
10809            }
10810            final int NI = a.intents.size();
10811            for (int j=0; j<NI; j++) {
10812                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10813                if (DEBUG_SHOW_INFO) {
10814                    Log.v(TAG, "    IntentFilter:");
10815                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10816                }
10817                removeFilter(intent);
10818            }
10819        }
10820
10821        @Override
10822        protected boolean allowFilterResult(
10823                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10824            ActivityInfo filterAi = filter.activity.info;
10825            for (int i=dest.size()-1; i>=0; i--) {
10826                ActivityInfo destAi = dest.get(i).activityInfo;
10827                if (destAi.name == filterAi.name
10828                        && destAi.packageName == filterAi.packageName) {
10829                    return false;
10830                }
10831            }
10832            return true;
10833        }
10834
10835        @Override
10836        protected ActivityIntentInfo[] newArray(int size) {
10837            return new ActivityIntentInfo[size];
10838        }
10839
10840        @Override
10841        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10842            if (!sUserManager.exists(userId)) return true;
10843            PackageParser.Package p = filter.activity.owner;
10844            if (p != null) {
10845                PackageSetting ps = (PackageSetting)p.mExtras;
10846                if (ps != null) {
10847                    // System apps are never considered stopped for purposes of
10848                    // filtering, because there may be no way for the user to
10849                    // actually re-launch them.
10850                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10851                            && ps.getStopped(userId);
10852                }
10853            }
10854            return false;
10855        }
10856
10857        @Override
10858        protected boolean isPackageForFilter(String packageName,
10859                PackageParser.ActivityIntentInfo info) {
10860            return packageName.equals(info.activity.owner.packageName);
10861        }
10862
10863        @Override
10864        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10865                int match, int userId) {
10866            if (!sUserManager.exists(userId)) return null;
10867            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10868                return null;
10869            }
10870            final PackageParser.Activity activity = info.activity;
10871            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10872            if (ps == null) {
10873                return null;
10874            }
10875            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10876                    ps.readUserState(userId), userId);
10877            if (ai == null) {
10878                return null;
10879            }
10880            final ResolveInfo res = new ResolveInfo();
10881            res.activityInfo = ai;
10882            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10883                res.filter = info;
10884            }
10885            if (info != null) {
10886                res.handleAllWebDataURI = info.handleAllWebDataURI();
10887            }
10888            res.priority = info.getPriority();
10889            res.preferredOrder = activity.owner.mPreferredOrder;
10890            //System.out.println("Result: " + res.activityInfo.className +
10891            //                   " = " + res.priority);
10892            res.match = match;
10893            res.isDefault = info.hasDefault;
10894            res.labelRes = info.labelRes;
10895            res.nonLocalizedLabel = info.nonLocalizedLabel;
10896            if (userNeedsBadging(userId)) {
10897                res.noResourceId = true;
10898            } else {
10899                res.icon = info.icon;
10900            }
10901            res.iconResourceId = info.icon;
10902            res.system = res.activityInfo.applicationInfo.isSystemApp();
10903            return res;
10904        }
10905
10906        @Override
10907        protected void sortResults(List<ResolveInfo> results) {
10908            Collections.sort(results, mResolvePrioritySorter);
10909        }
10910
10911        @Override
10912        protected void dumpFilter(PrintWriter out, String prefix,
10913                PackageParser.ActivityIntentInfo filter) {
10914            out.print(prefix); out.print(
10915                    Integer.toHexString(System.identityHashCode(filter.activity)));
10916                    out.print(' ');
10917                    filter.activity.printComponentShortName(out);
10918                    out.print(" filter ");
10919                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10920        }
10921
10922        @Override
10923        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10924            return filter.activity;
10925        }
10926
10927        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10928            PackageParser.Activity activity = (PackageParser.Activity)label;
10929            out.print(prefix); out.print(
10930                    Integer.toHexString(System.identityHashCode(activity)));
10931                    out.print(' ');
10932                    activity.printComponentShortName(out);
10933            if (count > 1) {
10934                out.print(" ("); out.print(count); out.print(" filters)");
10935            }
10936            out.println();
10937        }
10938
10939        // Keys are String (activity class name), values are Activity.
10940        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10941                = new ArrayMap<ComponentName, PackageParser.Activity>();
10942        private int mFlags;
10943    }
10944
10945    private final class ServiceIntentResolver
10946            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10947        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10948                boolean defaultOnly, int userId) {
10949            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10950            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10951        }
10952
10953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10954                int userId) {
10955            if (!sUserManager.exists(userId)) return null;
10956            mFlags = flags;
10957            return super.queryIntent(intent, resolvedType,
10958                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10959        }
10960
10961        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10962                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10963            if (!sUserManager.exists(userId)) return null;
10964            if (packageServices == null) {
10965                return null;
10966            }
10967            mFlags = flags;
10968            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10969            final int N = packageServices.size();
10970            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10971                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10972
10973            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10974            for (int i = 0; i < N; ++i) {
10975                intentFilters = packageServices.get(i).intents;
10976                if (intentFilters != null && intentFilters.size() > 0) {
10977                    PackageParser.ServiceIntentInfo[] array =
10978                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10979                    intentFilters.toArray(array);
10980                    listCut.add(array);
10981                }
10982            }
10983            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10984        }
10985
10986        public final void addService(PackageParser.Service s) {
10987            mServices.put(s.getComponentName(), s);
10988            if (DEBUG_SHOW_INFO) {
10989                Log.v(TAG, "  "
10990                        + (s.info.nonLocalizedLabel != null
10991                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10992                Log.v(TAG, "    Class=" + s.info.name);
10993            }
10994            final int NI = s.intents.size();
10995            int j;
10996            for (j=0; j<NI; j++) {
10997                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10998                if (DEBUG_SHOW_INFO) {
10999                    Log.v(TAG, "    IntentFilter:");
11000                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11001                }
11002                if (!intent.debugCheck()) {
11003                    Log.w(TAG, "==> For Service " + s.info.name);
11004                }
11005                addFilter(intent);
11006            }
11007        }
11008
11009        public final void removeService(PackageParser.Service s) {
11010            mServices.remove(s.getComponentName());
11011            if (DEBUG_SHOW_INFO) {
11012                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11013                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11014                Log.v(TAG, "    Class=" + s.info.name);
11015            }
11016            final int NI = s.intents.size();
11017            int j;
11018            for (j=0; j<NI; j++) {
11019                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11020                if (DEBUG_SHOW_INFO) {
11021                    Log.v(TAG, "    IntentFilter:");
11022                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11023                }
11024                removeFilter(intent);
11025            }
11026        }
11027
11028        @Override
11029        protected boolean allowFilterResult(
11030                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11031            ServiceInfo filterSi = filter.service.info;
11032            for (int i=dest.size()-1; i>=0; i--) {
11033                ServiceInfo destAi = dest.get(i).serviceInfo;
11034                if (destAi.name == filterSi.name
11035                        && destAi.packageName == filterSi.packageName) {
11036                    return false;
11037                }
11038            }
11039            return true;
11040        }
11041
11042        @Override
11043        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11044            return new PackageParser.ServiceIntentInfo[size];
11045        }
11046
11047        @Override
11048        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11049            if (!sUserManager.exists(userId)) return true;
11050            PackageParser.Package p = filter.service.owner;
11051            if (p != null) {
11052                PackageSetting ps = (PackageSetting)p.mExtras;
11053                if (ps != null) {
11054                    // System apps are never considered stopped for purposes of
11055                    // filtering, because there may be no way for the user to
11056                    // actually re-launch them.
11057                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11058                            && ps.getStopped(userId);
11059                }
11060            }
11061            return false;
11062        }
11063
11064        @Override
11065        protected boolean isPackageForFilter(String packageName,
11066                PackageParser.ServiceIntentInfo info) {
11067            return packageName.equals(info.service.owner.packageName);
11068        }
11069
11070        @Override
11071        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11072                int match, int userId) {
11073            if (!sUserManager.exists(userId)) return null;
11074            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11075            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11076                return null;
11077            }
11078            final PackageParser.Service service = info.service;
11079            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11080            if (ps == null) {
11081                return null;
11082            }
11083            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11084                    ps.readUserState(userId), userId);
11085            if (si == null) {
11086                return null;
11087            }
11088            final ResolveInfo res = new ResolveInfo();
11089            res.serviceInfo = si;
11090            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11091                res.filter = filter;
11092            }
11093            res.priority = info.getPriority();
11094            res.preferredOrder = service.owner.mPreferredOrder;
11095            res.match = match;
11096            res.isDefault = info.hasDefault;
11097            res.labelRes = info.labelRes;
11098            res.nonLocalizedLabel = info.nonLocalizedLabel;
11099            res.icon = info.icon;
11100            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11101            return res;
11102        }
11103
11104        @Override
11105        protected void sortResults(List<ResolveInfo> results) {
11106            Collections.sort(results, mResolvePrioritySorter);
11107        }
11108
11109        @Override
11110        protected void dumpFilter(PrintWriter out, String prefix,
11111                PackageParser.ServiceIntentInfo filter) {
11112            out.print(prefix); out.print(
11113                    Integer.toHexString(System.identityHashCode(filter.service)));
11114                    out.print(' ');
11115                    filter.service.printComponentShortName(out);
11116                    out.print(" filter ");
11117                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11118        }
11119
11120        @Override
11121        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11122            return filter.service;
11123        }
11124
11125        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11126            PackageParser.Service service = (PackageParser.Service)label;
11127            out.print(prefix); out.print(
11128                    Integer.toHexString(System.identityHashCode(service)));
11129                    out.print(' ');
11130                    service.printComponentShortName(out);
11131            if (count > 1) {
11132                out.print(" ("); out.print(count); out.print(" filters)");
11133            }
11134            out.println();
11135        }
11136
11137//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11138//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11139//            final List<ResolveInfo> retList = Lists.newArrayList();
11140//            while (i.hasNext()) {
11141//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11142//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11143//                    retList.add(resolveInfo);
11144//                }
11145//            }
11146//            return retList;
11147//        }
11148
11149        // Keys are String (activity class name), values are Activity.
11150        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11151                = new ArrayMap<ComponentName, PackageParser.Service>();
11152        private int mFlags;
11153    };
11154
11155    private final class ProviderIntentResolver
11156            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11157        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11158                boolean defaultOnly, int userId) {
11159            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11160            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11161        }
11162
11163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11164                int userId) {
11165            if (!sUserManager.exists(userId))
11166                return null;
11167            mFlags = flags;
11168            return super.queryIntent(intent, resolvedType,
11169                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11170        }
11171
11172        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11173                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11174            if (!sUserManager.exists(userId))
11175                return null;
11176            if (packageProviders == null) {
11177                return null;
11178            }
11179            mFlags = flags;
11180            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11181            final int N = packageProviders.size();
11182            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11183                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11184
11185            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11186            for (int i = 0; i < N; ++i) {
11187                intentFilters = packageProviders.get(i).intents;
11188                if (intentFilters != null && intentFilters.size() > 0) {
11189                    PackageParser.ProviderIntentInfo[] array =
11190                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11191                    intentFilters.toArray(array);
11192                    listCut.add(array);
11193                }
11194            }
11195            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11196        }
11197
11198        public final void addProvider(PackageParser.Provider p) {
11199            if (mProviders.containsKey(p.getComponentName())) {
11200                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11201                return;
11202            }
11203
11204            mProviders.put(p.getComponentName(), p);
11205            if (DEBUG_SHOW_INFO) {
11206                Log.v(TAG, "  "
11207                        + (p.info.nonLocalizedLabel != null
11208                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11209                Log.v(TAG, "    Class=" + p.info.name);
11210            }
11211            final int NI = p.intents.size();
11212            int j;
11213            for (j = 0; j < NI; j++) {
11214                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11215                if (DEBUG_SHOW_INFO) {
11216                    Log.v(TAG, "    IntentFilter:");
11217                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11218                }
11219                if (!intent.debugCheck()) {
11220                    Log.w(TAG, "==> For Provider " + p.info.name);
11221                }
11222                addFilter(intent);
11223            }
11224        }
11225
11226        public final void removeProvider(PackageParser.Provider p) {
11227            mProviders.remove(p.getComponentName());
11228            if (DEBUG_SHOW_INFO) {
11229                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11230                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11231                Log.v(TAG, "    Class=" + p.info.name);
11232            }
11233            final int NI = p.intents.size();
11234            int j;
11235            for (j = 0; j < NI; j++) {
11236                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11237                if (DEBUG_SHOW_INFO) {
11238                    Log.v(TAG, "    IntentFilter:");
11239                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11240                }
11241                removeFilter(intent);
11242            }
11243        }
11244
11245        @Override
11246        protected boolean allowFilterResult(
11247                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11248            ProviderInfo filterPi = filter.provider.info;
11249            for (int i = dest.size() - 1; i >= 0; i--) {
11250                ProviderInfo destPi = dest.get(i).providerInfo;
11251                if (destPi.name == filterPi.name
11252                        && destPi.packageName == filterPi.packageName) {
11253                    return false;
11254                }
11255            }
11256            return true;
11257        }
11258
11259        @Override
11260        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11261            return new PackageParser.ProviderIntentInfo[size];
11262        }
11263
11264        @Override
11265        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11266            if (!sUserManager.exists(userId))
11267                return true;
11268            PackageParser.Package p = filter.provider.owner;
11269            if (p != null) {
11270                PackageSetting ps = (PackageSetting) p.mExtras;
11271                if (ps != null) {
11272                    // System apps are never considered stopped for purposes of
11273                    // filtering, because there may be no way for the user to
11274                    // actually re-launch them.
11275                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11276                            && ps.getStopped(userId);
11277                }
11278            }
11279            return false;
11280        }
11281
11282        @Override
11283        protected boolean isPackageForFilter(String packageName,
11284                PackageParser.ProviderIntentInfo info) {
11285            return packageName.equals(info.provider.owner.packageName);
11286        }
11287
11288        @Override
11289        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11290                int match, int userId) {
11291            if (!sUserManager.exists(userId))
11292                return null;
11293            final PackageParser.ProviderIntentInfo info = filter;
11294            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11295                return null;
11296            }
11297            final PackageParser.Provider provider = info.provider;
11298            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11299            if (ps == null) {
11300                return null;
11301            }
11302            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11303                    ps.readUserState(userId), userId);
11304            if (pi == null) {
11305                return null;
11306            }
11307            final ResolveInfo res = new ResolveInfo();
11308            res.providerInfo = pi;
11309            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11310                res.filter = filter;
11311            }
11312            res.priority = info.getPriority();
11313            res.preferredOrder = provider.owner.mPreferredOrder;
11314            res.match = match;
11315            res.isDefault = info.hasDefault;
11316            res.labelRes = info.labelRes;
11317            res.nonLocalizedLabel = info.nonLocalizedLabel;
11318            res.icon = info.icon;
11319            res.system = res.providerInfo.applicationInfo.isSystemApp();
11320            return res;
11321        }
11322
11323        @Override
11324        protected void sortResults(List<ResolveInfo> results) {
11325            Collections.sort(results, mResolvePrioritySorter);
11326        }
11327
11328        @Override
11329        protected void dumpFilter(PrintWriter out, String prefix,
11330                PackageParser.ProviderIntentInfo filter) {
11331            out.print(prefix);
11332            out.print(
11333                    Integer.toHexString(System.identityHashCode(filter.provider)));
11334            out.print(' ');
11335            filter.provider.printComponentShortName(out);
11336            out.print(" filter ");
11337            out.println(Integer.toHexString(System.identityHashCode(filter)));
11338        }
11339
11340        @Override
11341        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11342            return filter.provider;
11343        }
11344
11345        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11346            PackageParser.Provider provider = (PackageParser.Provider)label;
11347            out.print(prefix); out.print(
11348                    Integer.toHexString(System.identityHashCode(provider)));
11349                    out.print(' ');
11350                    provider.printComponentShortName(out);
11351            if (count > 1) {
11352                out.print(" ("); out.print(count); out.print(" filters)");
11353            }
11354            out.println();
11355        }
11356
11357        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11358                = new ArrayMap<ComponentName, PackageParser.Provider>();
11359        private int mFlags;
11360    }
11361
11362    private static final class EphemeralIntentResolver
11363            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11364        @Override
11365        protected EphemeralResolveIntentInfo[] newArray(int size) {
11366            return new EphemeralResolveIntentInfo[size];
11367        }
11368
11369        @Override
11370        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11371            return true;
11372        }
11373
11374        @Override
11375        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11376                int userId) {
11377            if (!sUserManager.exists(userId)) {
11378                return null;
11379            }
11380            return info.getEphemeralResolveInfo();
11381        }
11382    }
11383
11384    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11385            new Comparator<ResolveInfo>() {
11386        public int compare(ResolveInfo r1, ResolveInfo r2) {
11387            int v1 = r1.priority;
11388            int v2 = r2.priority;
11389            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11390            if (v1 != v2) {
11391                return (v1 > v2) ? -1 : 1;
11392            }
11393            v1 = r1.preferredOrder;
11394            v2 = r2.preferredOrder;
11395            if (v1 != v2) {
11396                return (v1 > v2) ? -1 : 1;
11397            }
11398            if (r1.isDefault != r2.isDefault) {
11399                return r1.isDefault ? -1 : 1;
11400            }
11401            v1 = r1.match;
11402            v2 = r2.match;
11403            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11404            if (v1 != v2) {
11405                return (v1 > v2) ? -1 : 1;
11406            }
11407            if (r1.system != r2.system) {
11408                return r1.system ? -1 : 1;
11409            }
11410            if (r1.activityInfo != null) {
11411                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11412            }
11413            if (r1.serviceInfo != null) {
11414                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11415            }
11416            if (r1.providerInfo != null) {
11417                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11418            }
11419            return 0;
11420        }
11421    };
11422
11423    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11424            new Comparator<ProviderInfo>() {
11425        public int compare(ProviderInfo p1, ProviderInfo p2) {
11426            final int v1 = p1.initOrder;
11427            final int v2 = p2.initOrder;
11428            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11429        }
11430    };
11431
11432    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11433            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11434            final int[] userIds) {
11435        mHandler.post(new Runnable() {
11436            @Override
11437            public void run() {
11438                try {
11439                    final IActivityManager am = ActivityManagerNative.getDefault();
11440                    if (am == null) return;
11441                    final int[] resolvedUserIds;
11442                    if (userIds == null) {
11443                        resolvedUserIds = am.getRunningUserIds();
11444                    } else {
11445                        resolvedUserIds = userIds;
11446                    }
11447                    final ShortcutServiceInternal shortcutService =
11448                            LocalServices.getService(ShortcutServiceInternal.class);
11449
11450                    for (int id : resolvedUserIds) {
11451                        final Intent intent = new Intent(action,
11452                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11453                        if (extras != null) {
11454                            intent.putExtras(extras);
11455                        }
11456                        if (targetPkg != null) {
11457                            intent.setPackage(targetPkg);
11458                        }
11459                        // Modify the UID when posting to other users
11460                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11461                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11462                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11463                            intent.putExtra(Intent.EXTRA_UID, uid);
11464                        }
11465                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11466                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11467                        if (DEBUG_BROADCASTS) {
11468                            RuntimeException here = new RuntimeException("here");
11469                            here.fillInStackTrace();
11470                            Slog.d(TAG, "Sending to user " + id + ": "
11471                                    + intent.toShortString(false, true, false, false)
11472                                    + " " + intent.getExtras(), here);
11473                        }
11474                        // TODO b/29385425 Consider making lifecycle callbacks for this.
11475                        if (shortcutService != null) {
11476                            shortcutService.onPackageBroadcast(intent);
11477                        }
11478                        am.broadcastIntent(null, intent, null, finishedReceiver,
11479                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11480                                null, finishedReceiver != null, false, id);
11481                    }
11482                } catch (RemoteException ex) {
11483                }
11484            }
11485        });
11486    }
11487
11488    /**
11489     * Check if the external storage media is available. This is true if there
11490     * is a mounted external storage medium or if the external storage is
11491     * emulated.
11492     */
11493    private boolean isExternalMediaAvailable() {
11494        return mMediaMounted || Environment.isExternalStorageEmulated();
11495    }
11496
11497    @Override
11498    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11499        // writer
11500        synchronized (mPackages) {
11501            if (!isExternalMediaAvailable()) {
11502                // If the external storage is no longer mounted at this point,
11503                // the caller may not have been able to delete all of this
11504                // packages files and can not delete any more.  Bail.
11505                return null;
11506            }
11507            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11508            if (lastPackage != null) {
11509                pkgs.remove(lastPackage);
11510            }
11511            if (pkgs.size() > 0) {
11512                return pkgs.get(0);
11513            }
11514        }
11515        return null;
11516    }
11517
11518    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11519        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11520                userId, andCode ? 1 : 0, packageName);
11521        if (mSystemReady) {
11522            msg.sendToTarget();
11523        } else {
11524            if (mPostSystemReadyMessages == null) {
11525                mPostSystemReadyMessages = new ArrayList<>();
11526            }
11527            mPostSystemReadyMessages.add(msg);
11528        }
11529    }
11530
11531    void startCleaningPackages() {
11532        // reader
11533        if (!isExternalMediaAvailable()) {
11534            return;
11535        }
11536        synchronized (mPackages) {
11537            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11538                return;
11539            }
11540        }
11541        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11542        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11543        IActivityManager am = ActivityManagerNative.getDefault();
11544        if (am != null) {
11545            try {
11546                am.startService(null, intent, null, mContext.getOpPackageName(),
11547                        UserHandle.USER_SYSTEM);
11548            } catch (RemoteException e) {
11549            }
11550        }
11551    }
11552
11553    @Override
11554    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11555            int installFlags, String installerPackageName, int userId) {
11556        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11557
11558        final int callingUid = Binder.getCallingUid();
11559        enforceCrossUserPermission(callingUid, userId,
11560                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11561
11562        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11563            try {
11564                if (observer != null) {
11565                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11566                }
11567            } catch (RemoteException re) {
11568            }
11569            return;
11570        }
11571
11572        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11573            installFlags |= PackageManager.INSTALL_FROM_ADB;
11574
11575        } else {
11576            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11577            // about installerPackageName.
11578
11579            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11580            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11581        }
11582
11583        UserHandle user;
11584        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11585            user = UserHandle.ALL;
11586        } else {
11587            user = new UserHandle(userId);
11588        }
11589
11590        // Only system components can circumvent runtime permissions when installing.
11591        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11592                && mContext.checkCallingOrSelfPermission(Manifest.permission
11593                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11594            throw new SecurityException("You need the "
11595                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11596                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11597        }
11598
11599        final File originFile = new File(originPath);
11600        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11601
11602        final Message msg = mHandler.obtainMessage(INIT_COPY);
11603        final VerificationInfo verificationInfo = new VerificationInfo(
11604                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11605        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11606                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11607                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11608                null /*certificates*/);
11609        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11610        msg.obj = params;
11611
11612        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11613                System.identityHashCode(msg.obj));
11614        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11615                System.identityHashCode(msg.obj));
11616
11617        mHandler.sendMessage(msg);
11618    }
11619
11620    void installStage(String packageName, File stagedDir, String stagedCid,
11621            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11622            String installerPackageName, int installerUid, UserHandle user,
11623            Certificate[][] certificates) {
11624        if (DEBUG_EPHEMERAL) {
11625            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11626                Slog.d(TAG, "Ephemeral install of " + packageName);
11627            }
11628        }
11629        final VerificationInfo verificationInfo = new VerificationInfo(
11630                sessionParams.originatingUri, sessionParams.referrerUri,
11631                sessionParams.originatingUid, installerUid);
11632
11633        final OriginInfo origin;
11634        if (stagedDir != null) {
11635            origin = OriginInfo.fromStagedFile(stagedDir);
11636        } else {
11637            origin = OriginInfo.fromStagedContainer(stagedCid);
11638        }
11639
11640        final Message msg = mHandler.obtainMessage(INIT_COPY);
11641        final InstallParams params = new InstallParams(origin, null, observer,
11642                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11643                verificationInfo, user, sessionParams.abiOverride,
11644                sessionParams.grantedRuntimePermissions, certificates);
11645        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11646        msg.obj = params;
11647
11648        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11649                System.identityHashCode(msg.obj));
11650        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11651                System.identityHashCode(msg.obj));
11652
11653        mHandler.sendMessage(msg);
11654    }
11655
11656    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11657            int userId) {
11658        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11659        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11660    }
11661
11662    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11663            int appId, int userId) {
11664        Bundle extras = new Bundle(1);
11665        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11666
11667        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11668                packageName, extras, 0, null, null, new int[] {userId});
11669        try {
11670            IActivityManager am = ActivityManagerNative.getDefault();
11671            if (isSystem && am.isUserRunning(userId, 0)) {
11672                // The just-installed/enabled app is bundled on the system, so presumed
11673                // to be able to run automatically without needing an explicit launch.
11674                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11675                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11676                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11677                        .setPackage(packageName);
11678                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11679                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11680            }
11681        } catch (RemoteException e) {
11682            // shouldn't happen
11683            Slog.w(TAG, "Unable to bootstrap installed package", e);
11684        }
11685    }
11686
11687    @Override
11688    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11689            int userId) {
11690        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11691        PackageSetting pkgSetting;
11692        final int uid = Binder.getCallingUid();
11693        enforceCrossUserPermission(uid, userId,
11694                true /* requireFullPermission */, true /* checkShell */,
11695                "setApplicationHiddenSetting for user " + userId);
11696
11697        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11698            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11699            return false;
11700        }
11701
11702        long callingId = Binder.clearCallingIdentity();
11703        try {
11704            boolean sendAdded = false;
11705            boolean sendRemoved = false;
11706            // writer
11707            synchronized (mPackages) {
11708                pkgSetting = mSettings.mPackages.get(packageName);
11709                if (pkgSetting == null) {
11710                    return false;
11711                }
11712                // Only allow protected packages to hide themselves.
11713                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11714                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11715                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11716                    return false;
11717                }
11718                if (pkgSetting.getHidden(userId) != hidden) {
11719                    pkgSetting.setHidden(hidden, userId);
11720                    mSettings.writePackageRestrictionsLPr(userId);
11721                    if (hidden) {
11722                        sendRemoved = true;
11723                    } else {
11724                        sendAdded = true;
11725                    }
11726                }
11727            }
11728            if (sendAdded) {
11729                sendPackageAddedForUser(packageName, pkgSetting, userId);
11730                return true;
11731            }
11732            if (sendRemoved) {
11733                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11734                        "hiding pkg");
11735                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11736                return true;
11737            }
11738        } finally {
11739            Binder.restoreCallingIdentity(callingId);
11740        }
11741        return false;
11742    }
11743
11744    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11745            int userId) {
11746        final PackageRemovedInfo info = new PackageRemovedInfo();
11747        info.removedPackage = packageName;
11748        info.removedUsers = new int[] {userId};
11749        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11750        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11751    }
11752
11753    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11754        if (pkgList.length > 0) {
11755            Bundle extras = new Bundle(1);
11756            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11757
11758            sendPackageBroadcast(
11759                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11760                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11761                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11762                    new int[] {userId});
11763        }
11764    }
11765
11766    /**
11767     * Returns true if application is not found or there was an error. Otherwise it returns
11768     * the hidden state of the package for the given user.
11769     */
11770    @Override
11771    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11772        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11773        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11774                true /* requireFullPermission */, false /* checkShell */,
11775                "getApplicationHidden for user " + userId);
11776        PackageSetting pkgSetting;
11777        long callingId = Binder.clearCallingIdentity();
11778        try {
11779            // writer
11780            synchronized (mPackages) {
11781                pkgSetting = mSettings.mPackages.get(packageName);
11782                if (pkgSetting == null) {
11783                    return true;
11784                }
11785                return pkgSetting.getHidden(userId);
11786            }
11787        } finally {
11788            Binder.restoreCallingIdentity(callingId);
11789        }
11790    }
11791
11792    /**
11793     * @hide
11794     */
11795    @Override
11796    public int installExistingPackageAsUser(String packageName, int userId) {
11797        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11798                null);
11799        PackageSetting pkgSetting;
11800        final int uid = Binder.getCallingUid();
11801        enforceCrossUserPermission(uid, userId,
11802                true /* requireFullPermission */, true /* checkShell */,
11803                "installExistingPackage for user " + userId);
11804        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11805            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11806        }
11807
11808        long callingId = Binder.clearCallingIdentity();
11809        try {
11810            boolean installed = false;
11811
11812            // writer
11813            synchronized (mPackages) {
11814                pkgSetting = mSettings.mPackages.get(packageName);
11815                if (pkgSetting == null) {
11816                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11817                }
11818                if (!pkgSetting.getInstalled(userId)) {
11819                    pkgSetting.setInstalled(true, userId);
11820                    pkgSetting.setHidden(false, userId);
11821                    mSettings.writePackageRestrictionsLPr(userId);
11822                    installed = true;
11823                }
11824            }
11825
11826            if (installed) {
11827                if (pkgSetting.pkg != null) {
11828                    synchronized (mInstallLock) {
11829                        // We don't need to freeze for a brand new install
11830                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11831                    }
11832                }
11833                sendPackageAddedForUser(packageName, pkgSetting, userId);
11834            }
11835        } finally {
11836            Binder.restoreCallingIdentity(callingId);
11837        }
11838
11839        return PackageManager.INSTALL_SUCCEEDED;
11840    }
11841
11842    boolean isUserRestricted(int userId, String restrictionKey) {
11843        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11844        if (restrictions.getBoolean(restrictionKey, false)) {
11845            Log.w(TAG, "User is restricted: " + restrictionKey);
11846            return true;
11847        }
11848        return false;
11849    }
11850
11851    @Override
11852    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11853            int userId) {
11854        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11855        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11856                true /* requireFullPermission */, true /* checkShell */,
11857                "setPackagesSuspended for user " + userId);
11858
11859        if (ArrayUtils.isEmpty(packageNames)) {
11860            return packageNames;
11861        }
11862
11863        // List of package names for whom the suspended state has changed.
11864        List<String> changedPackages = new ArrayList<>(packageNames.length);
11865        // List of package names for whom the suspended state is not set as requested in this
11866        // method.
11867        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11868        long callingId = Binder.clearCallingIdentity();
11869        try {
11870            for (int i = 0; i < packageNames.length; i++) {
11871                String packageName = packageNames[i];
11872                boolean changed = false;
11873                final int appId;
11874                synchronized (mPackages) {
11875                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11876                    if (pkgSetting == null) {
11877                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11878                                + "\". Skipping suspending/un-suspending.");
11879                        unactionedPackages.add(packageName);
11880                        continue;
11881                    }
11882                    appId = pkgSetting.appId;
11883                    if (pkgSetting.getSuspended(userId) != suspended) {
11884                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11885                            unactionedPackages.add(packageName);
11886                            continue;
11887                        }
11888                        pkgSetting.setSuspended(suspended, userId);
11889                        mSettings.writePackageRestrictionsLPr(userId);
11890                        changed = true;
11891                        changedPackages.add(packageName);
11892                    }
11893                }
11894
11895                if (changed && suspended) {
11896                    killApplication(packageName, UserHandle.getUid(userId, appId),
11897                            "suspending package");
11898                }
11899            }
11900        } finally {
11901            Binder.restoreCallingIdentity(callingId);
11902        }
11903
11904        if (!changedPackages.isEmpty()) {
11905            sendPackagesSuspendedForUser(changedPackages.toArray(
11906                    new String[changedPackages.size()]), userId, suspended);
11907        }
11908
11909        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11910    }
11911
11912    @Override
11913    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11914        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11915                true /* requireFullPermission */, false /* checkShell */,
11916                "isPackageSuspendedForUser for user " + userId);
11917        synchronized (mPackages) {
11918            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11919            if (pkgSetting == null) {
11920                throw new IllegalArgumentException("Unknown target package: " + packageName);
11921            }
11922            return pkgSetting.getSuspended(userId);
11923        }
11924    }
11925
11926    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11927        if (isPackageDeviceAdmin(packageName, userId)) {
11928            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11929                    + "\": has an active device admin");
11930            return false;
11931        }
11932
11933        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11934        if (packageName.equals(activeLauncherPackageName)) {
11935            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11936                    + "\": contains the active launcher");
11937            return false;
11938        }
11939
11940        if (packageName.equals(mRequiredInstallerPackage)) {
11941            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11942                    + "\": required for package installation");
11943            return false;
11944        }
11945
11946        if (packageName.equals(mRequiredVerifierPackage)) {
11947            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11948                    + "\": required for package verification");
11949            return false;
11950        }
11951
11952        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11953            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11954                    + "\": is the default dialer");
11955            return false;
11956        }
11957
11958        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11959            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11960                    + "\": protected package");
11961            return false;
11962        }
11963
11964        return true;
11965    }
11966
11967    private String getActiveLauncherPackageName(int userId) {
11968        Intent intent = new Intent(Intent.ACTION_MAIN);
11969        intent.addCategory(Intent.CATEGORY_HOME);
11970        ResolveInfo resolveInfo = resolveIntent(
11971                intent,
11972                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11973                PackageManager.MATCH_DEFAULT_ONLY,
11974                userId);
11975
11976        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11977    }
11978
11979    private String getDefaultDialerPackageName(int userId) {
11980        synchronized (mPackages) {
11981            return mSettings.getDefaultDialerPackageNameLPw(userId);
11982        }
11983    }
11984
11985    @Override
11986    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11987        mContext.enforceCallingOrSelfPermission(
11988                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11989                "Only package verification agents can verify applications");
11990
11991        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11992        final PackageVerificationResponse response = new PackageVerificationResponse(
11993                verificationCode, Binder.getCallingUid());
11994        msg.arg1 = id;
11995        msg.obj = response;
11996        mHandler.sendMessage(msg);
11997    }
11998
11999    @Override
12000    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12001            long millisecondsToDelay) {
12002        mContext.enforceCallingOrSelfPermission(
12003                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12004                "Only package verification agents can extend verification timeouts");
12005
12006        final PackageVerificationState state = mPendingVerification.get(id);
12007        final PackageVerificationResponse response = new PackageVerificationResponse(
12008                verificationCodeAtTimeout, Binder.getCallingUid());
12009
12010        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12011            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12012        }
12013        if (millisecondsToDelay < 0) {
12014            millisecondsToDelay = 0;
12015        }
12016        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12017                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12018            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12019        }
12020
12021        if ((state != null) && !state.timeoutExtended()) {
12022            state.extendTimeout();
12023
12024            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12025            msg.arg1 = id;
12026            msg.obj = response;
12027            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12028        }
12029    }
12030
12031    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12032            int verificationCode, UserHandle user) {
12033        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12034        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12035        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12036        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12037        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12038
12039        mContext.sendBroadcastAsUser(intent, user,
12040                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12041    }
12042
12043    private ComponentName matchComponentForVerifier(String packageName,
12044            List<ResolveInfo> receivers) {
12045        ActivityInfo targetReceiver = null;
12046
12047        final int NR = receivers.size();
12048        for (int i = 0; i < NR; i++) {
12049            final ResolveInfo info = receivers.get(i);
12050            if (info.activityInfo == null) {
12051                continue;
12052            }
12053
12054            if (packageName.equals(info.activityInfo.packageName)) {
12055                targetReceiver = info.activityInfo;
12056                break;
12057            }
12058        }
12059
12060        if (targetReceiver == null) {
12061            return null;
12062        }
12063
12064        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12065    }
12066
12067    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12068            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12069        if (pkgInfo.verifiers.length == 0) {
12070            return null;
12071        }
12072
12073        final int N = pkgInfo.verifiers.length;
12074        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12075        for (int i = 0; i < N; i++) {
12076            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12077
12078            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12079                    receivers);
12080            if (comp == null) {
12081                continue;
12082            }
12083
12084            final int verifierUid = getUidForVerifier(verifierInfo);
12085            if (verifierUid == -1) {
12086                continue;
12087            }
12088
12089            if (DEBUG_VERIFY) {
12090                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12091                        + " with the correct signature");
12092            }
12093            sufficientVerifiers.add(comp);
12094            verificationState.addSufficientVerifier(verifierUid);
12095        }
12096
12097        return sufficientVerifiers;
12098    }
12099
12100    private int getUidForVerifier(VerifierInfo verifierInfo) {
12101        synchronized (mPackages) {
12102            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12103            if (pkg == null) {
12104                return -1;
12105            } else if (pkg.mSignatures.length != 1) {
12106                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12107                        + " has more than one signature; ignoring");
12108                return -1;
12109            }
12110
12111            /*
12112             * If the public key of the package's signature does not match
12113             * our expected public key, then this is a different package and
12114             * we should skip.
12115             */
12116
12117            final byte[] expectedPublicKey;
12118            try {
12119                final Signature verifierSig = pkg.mSignatures[0];
12120                final PublicKey publicKey = verifierSig.getPublicKey();
12121                expectedPublicKey = publicKey.getEncoded();
12122            } catch (CertificateException e) {
12123                return -1;
12124            }
12125
12126            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12127
12128            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12129                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12130                        + " does not have the expected public key; ignoring");
12131                return -1;
12132            }
12133
12134            return pkg.applicationInfo.uid;
12135        }
12136    }
12137
12138    @Override
12139    public void finishPackageInstall(int token, boolean didLaunch) {
12140        enforceSystemOrRoot("Only the system is allowed to finish installs");
12141
12142        if (DEBUG_INSTALL) {
12143            Slog.v(TAG, "BM finishing package install for " + token);
12144        }
12145        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12146
12147        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12148        mHandler.sendMessage(msg);
12149    }
12150
12151    /**
12152     * Get the verification agent timeout.
12153     *
12154     * @return verification timeout in milliseconds
12155     */
12156    private long getVerificationTimeout() {
12157        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12158                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12159                DEFAULT_VERIFICATION_TIMEOUT);
12160    }
12161
12162    /**
12163     * Get the default verification agent response code.
12164     *
12165     * @return default verification response code
12166     */
12167    private int getDefaultVerificationResponse() {
12168        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12169                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12170                DEFAULT_VERIFICATION_RESPONSE);
12171    }
12172
12173    /**
12174     * Check whether or not package verification has been enabled.
12175     *
12176     * @return true if verification should be performed
12177     */
12178    private boolean isVerificationEnabled(int userId, int installFlags) {
12179        if (!DEFAULT_VERIFY_ENABLE) {
12180            return false;
12181        }
12182        // Ephemeral apps don't get the full verification treatment
12183        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12184            if (DEBUG_EPHEMERAL) {
12185                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12186            }
12187            return false;
12188        }
12189
12190        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12191
12192        // Check if installing from ADB
12193        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12194            // Do not run verification in a test harness environment
12195            if (ActivityManager.isRunningInTestHarness()) {
12196                return false;
12197            }
12198            if (ensureVerifyAppsEnabled) {
12199                return true;
12200            }
12201            // Check if the developer does not want package verification for ADB installs
12202            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12203                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12204                return false;
12205            }
12206        }
12207
12208        if (ensureVerifyAppsEnabled) {
12209            return true;
12210        }
12211
12212        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12213                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12214    }
12215
12216    @Override
12217    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12218            throws RemoteException {
12219        mContext.enforceCallingOrSelfPermission(
12220                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12221                "Only intentfilter verification agents can verify applications");
12222
12223        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12224        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12225                Binder.getCallingUid(), verificationCode, failedDomains);
12226        msg.arg1 = id;
12227        msg.obj = response;
12228        mHandler.sendMessage(msg);
12229    }
12230
12231    @Override
12232    public int getIntentVerificationStatus(String packageName, int userId) {
12233        synchronized (mPackages) {
12234            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12235        }
12236    }
12237
12238    @Override
12239    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12240        mContext.enforceCallingOrSelfPermission(
12241                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12242
12243        boolean result = false;
12244        synchronized (mPackages) {
12245            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12246        }
12247        if (result) {
12248            scheduleWritePackageRestrictionsLocked(userId);
12249        }
12250        return result;
12251    }
12252
12253    @Override
12254    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12255            String packageName) {
12256        synchronized (mPackages) {
12257            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12258        }
12259    }
12260
12261    @Override
12262    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12263        if (TextUtils.isEmpty(packageName)) {
12264            return ParceledListSlice.emptyList();
12265        }
12266        synchronized (mPackages) {
12267            PackageParser.Package pkg = mPackages.get(packageName);
12268            if (pkg == null || pkg.activities == null) {
12269                return ParceledListSlice.emptyList();
12270            }
12271            final int count = pkg.activities.size();
12272            ArrayList<IntentFilter> result = new ArrayList<>();
12273            for (int n=0; n<count; n++) {
12274                PackageParser.Activity activity = pkg.activities.get(n);
12275                if (activity.intents != null && activity.intents.size() > 0) {
12276                    result.addAll(activity.intents);
12277                }
12278            }
12279            return new ParceledListSlice<>(result);
12280        }
12281    }
12282
12283    @Override
12284    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12285        mContext.enforceCallingOrSelfPermission(
12286                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12287
12288        synchronized (mPackages) {
12289            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12290            if (packageName != null) {
12291                result |= updateIntentVerificationStatus(packageName,
12292                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12293                        userId);
12294                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12295                        packageName, userId);
12296            }
12297            return result;
12298        }
12299    }
12300
12301    @Override
12302    public String getDefaultBrowserPackageName(int userId) {
12303        synchronized (mPackages) {
12304            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12305        }
12306    }
12307
12308    /**
12309     * Get the "allow unknown sources" setting.
12310     *
12311     * @return the current "allow unknown sources" setting
12312     */
12313    private int getUnknownSourcesSettings() {
12314        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12315                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12316                -1);
12317    }
12318
12319    @Override
12320    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12321        final int uid = Binder.getCallingUid();
12322        // writer
12323        synchronized (mPackages) {
12324            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12325            if (targetPackageSetting == null) {
12326                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12327            }
12328
12329            PackageSetting installerPackageSetting;
12330            if (installerPackageName != null) {
12331                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12332                if (installerPackageSetting == null) {
12333                    throw new IllegalArgumentException("Unknown installer package: "
12334                            + installerPackageName);
12335                }
12336            } else {
12337                installerPackageSetting = null;
12338            }
12339
12340            Signature[] callerSignature;
12341            Object obj = mSettings.getUserIdLPr(uid);
12342            if (obj != null) {
12343                if (obj instanceof SharedUserSetting) {
12344                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12345                } else if (obj instanceof PackageSetting) {
12346                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12347                } else {
12348                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12349                }
12350            } else {
12351                throw new SecurityException("Unknown calling UID: " + uid);
12352            }
12353
12354            // Verify: can't set installerPackageName to a package that is
12355            // not signed with the same cert as the caller.
12356            if (installerPackageSetting != null) {
12357                if (compareSignatures(callerSignature,
12358                        installerPackageSetting.signatures.mSignatures)
12359                        != PackageManager.SIGNATURE_MATCH) {
12360                    throw new SecurityException(
12361                            "Caller does not have same cert as new installer package "
12362                            + installerPackageName);
12363                }
12364            }
12365
12366            // Verify: if target already has an installer package, it must
12367            // be signed with the same cert as the caller.
12368            if (targetPackageSetting.installerPackageName != null) {
12369                PackageSetting setting = mSettings.mPackages.get(
12370                        targetPackageSetting.installerPackageName);
12371                // If the currently set package isn't valid, then it's always
12372                // okay to change it.
12373                if (setting != null) {
12374                    if (compareSignatures(callerSignature,
12375                            setting.signatures.mSignatures)
12376                            != PackageManager.SIGNATURE_MATCH) {
12377                        throw new SecurityException(
12378                                "Caller does not have same cert as old installer package "
12379                                + targetPackageSetting.installerPackageName);
12380                    }
12381                }
12382            }
12383
12384            // Okay!
12385            targetPackageSetting.installerPackageName = installerPackageName;
12386            if (installerPackageName != null) {
12387                mSettings.mInstallerPackages.add(installerPackageName);
12388            }
12389            scheduleWriteSettingsLocked();
12390        }
12391    }
12392
12393    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12394        // Queue up an async operation since the package installation may take a little while.
12395        mHandler.post(new Runnable() {
12396            public void run() {
12397                mHandler.removeCallbacks(this);
12398                 // Result object to be returned
12399                PackageInstalledInfo res = new PackageInstalledInfo();
12400                res.setReturnCode(currentStatus);
12401                res.uid = -1;
12402                res.pkg = null;
12403                res.removedInfo = null;
12404                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12405                    args.doPreInstall(res.returnCode);
12406                    synchronized (mInstallLock) {
12407                        installPackageTracedLI(args, res);
12408                    }
12409                    args.doPostInstall(res.returnCode, res.uid);
12410                }
12411
12412                // A restore should be performed at this point if (a) the install
12413                // succeeded, (b) the operation is not an update, and (c) the new
12414                // package has not opted out of backup participation.
12415                final boolean update = res.removedInfo != null
12416                        && res.removedInfo.removedPackage != null;
12417                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12418                boolean doRestore = !update
12419                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12420
12421                // Set up the post-install work request bookkeeping.  This will be used
12422                // and cleaned up by the post-install event handling regardless of whether
12423                // there's a restore pass performed.  Token values are >= 1.
12424                int token;
12425                if (mNextInstallToken < 0) mNextInstallToken = 1;
12426                token = mNextInstallToken++;
12427
12428                PostInstallData data = new PostInstallData(args, res);
12429                mRunningInstalls.put(token, data);
12430                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12431
12432                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12433                    // Pass responsibility to the Backup Manager.  It will perform a
12434                    // restore if appropriate, then pass responsibility back to the
12435                    // Package Manager to run the post-install observer callbacks
12436                    // and broadcasts.
12437                    IBackupManager bm = IBackupManager.Stub.asInterface(
12438                            ServiceManager.getService(Context.BACKUP_SERVICE));
12439                    if (bm != null) {
12440                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12441                                + " to BM for possible restore");
12442                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12443                        try {
12444                            // TODO: http://b/22388012
12445                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12446                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12447                            } else {
12448                                doRestore = false;
12449                            }
12450                        } catch (RemoteException e) {
12451                            // can't happen; the backup manager is local
12452                        } catch (Exception e) {
12453                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12454                            doRestore = false;
12455                        }
12456                    } else {
12457                        Slog.e(TAG, "Backup Manager not found!");
12458                        doRestore = false;
12459                    }
12460                }
12461
12462                if (!doRestore) {
12463                    // No restore possible, or the Backup Manager was mysteriously not
12464                    // available -- just fire the post-install work request directly.
12465                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12466
12467                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12468
12469                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12470                    mHandler.sendMessage(msg);
12471                }
12472            }
12473        });
12474    }
12475
12476    /**
12477     * Callback from PackageSettings whenever an app is first transitioned out of the
12478     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12479     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12480     * here whether the app is the target of an ongoing install, and only send the
12481     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12482     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12483     * handling.
12484     */
12485    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12486        // Serialize this with the rest of the install-process message chain.  In the
12487        // restore-at-install case, this Runnable will necessarily run before the
12488        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12489        // are coherent.  In the non-restore case, the app has already completed install
12490        // and been launched through some other means, so it is not in a problematic
12491        // state for observers to see the FIRST_LAUNCH signal.
12492        mHandler.post(new Runnable() {
12493            @Override
12494            public void run() {
12495                for (int i = 0; i < mRunningInstalls.size(); i++) {
12496                    final PostInstallData data = mRunningInstalls.valueAt(i);
12497                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12498                        // right package; but is it for the right user?
12499                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12500                            if (userId == data.res.newUsers[uIndex]) {
12501                                if (DEBUG_BACKUP) {
12502                                    Slog.i(TAG, "Package " + pkgName
12503                                            + " being restored so deferring FIRST_LAUNCH");
12504                                }
12505                                return;
12506                            }
12507                        }
12508                    }
12509                }
12510                // didn't find it, so not being restored
12511                if (DEBUG_BACKUP) {
12512                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12513                }
12514                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12515            }
12516        });
12517    }
12518
12519    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12520        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12521                installerPkg, null, userIds);
12522    }
12523
12524    private abstract class HandlerParams {
12525        private static final int MAX_RETRIES = 4;
12526
12527        /**
12528         * Number of times startCopy() has been attempted and had a non-fatal
12529         * error.
12530         */
12531        private int mRetries = 0;
12532
12533        /** User handle for the user requesting the information or installation. */
12534        private final UserHandle mUser;
12535        String traceMethod;
12536        int traceCookie;
12537
12538        HandlerParams(UserHandle user) {
12539            mUser = user;
12540        }
12541
12542        UserHandle getUser() {
12543            return mUser;
12544        }
12545
12546        HandlerParams setTraceMethod(String traceMethod) {
12547            this.traceMethod = traceMethod;
12548            return this;
12549        }
12550
12551        HandlerParams setTraceCookie(int traceCookie) {
12552            this.traceCookie = traceCookie;
12553            return this;
12554        }
12555
12556        final boolean startCopy() {
12557            boolean res;
12558            try {
12559                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12560
12561                if (++mRetries > MAX_RETRIES) {
12562                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12563                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12564                    handleServiceError();
12565                    return false;
12566                } else {
12567                    handleStartCopy();
12568                    res = true;
12569                }
12570            } catch (RemoteException e) {
12571                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12572                mHandler.sendEmptyMessage(MCS_RECONNECT);
12573                res = false;
12574            }
12575            handleReturnCode();
12576            return res;
12577        }
12578
12579        final void serviceError() {
12580            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12581            handleServiceError();
12582            handleReturnCode();
12583        }
12584
12585        abstract void handleStartCopy() throws RemoteException;
12586        abstract void handleServiceError();
12587        abstract void handleReturnCode();
12588    }
12589
12590    class MeasureParams extends HandlerParams {
12591        private final PackageStats mStats;
12592        private boolean mSuccess;
12593
12594        private final IPackageStatsObserver mObserver;
12595
12596        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12597            super(new UserHandle(stats.userHandle));
12598            mObserver = observer;
12599            mStats = stats;
12600        }
12601
12602        @Override
12603        public String toString() {
12604            return "MeasureParams{"
12605                + Integer.toHexString(System.identityHashCode(this))
12606                + " " + mStats.packageName + "}";
12607        }
12608
12609        @Override
12610        void handleStartCopy() throws RemoteException {
12611            synchronized (mInstallLock) {
12612                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12613            }
12614
12615            if (mSuccess) {
12616                boolean mounted = false;
12617                try {
12618                    final String status = Environment.getExternalStorageState();
12619                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12620                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12621                } catch (Exception e) {
12622                }
12623
12624                if (mounted) {
12625                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12626
12627                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12628                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12629
12630                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12631                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12632
12633                    // Always subtract cache size, since it's a subdirectory
12634                    mStats.externalDataSize -= mStats.externalCacheSize;
12635
12636                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12637                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12638
12639                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12640                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12641                }
12642            }
12643        }
12644
12645        @Override
12646        void handleReturnCode() {
12647            if (mObserver != null) {
12648                try {
12649                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12650                } catch (RemoteException e) {
12651                    Slog.i(TAG, "Observer no longer exists.");
12652                }
12653            }
12654        }
12655
12656        @Override
12657        void handleServiceError() {
12658            Slog.e(TAG, "Could not measure application " + mStats.packageName
12659                            + " external storage");
12660        }
12661    }
12662
12663    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12664            throws RemoteException {
12665        long result = 0;
12666        for (File path : paths) {
12667            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12668        }
12669        return result;
12670    }
12671
12672    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12673        for (File path : paths) {
12674            try {
12675                mcs.clearDirectory(path.getAbsolutePath());
12676            } catch (RemoteException e) {
12677            }
12678        }
12679    }
12680
12681    static class OriginInfo {
12682        /**
12683         * Location where install is coming from, before it has been
12684         * copied/renamed into place. This could be a single monolithic APK
12685         * file, or a cluster directory. This location may be untrusted.
12686         */
12687        final File file;
12688        final String cid;
12689
12690        /**
12691         * Flag indicating that {@link #file} or {@link #cid} has already been
12692         * staged, meaning downstream users don't need to defensively copy the
12693         * contents.
12694         */
12695        final boolean staged;
12696
12697        /**
12698         * Flag indicating that {@link #file} or {@link #cid} is an already
12699         * installed app that is being moved.
12700         */
12701        final boolean existing;
12702
12703        final String resolvedPath;
12704        final File resolvedFile;
12705
12706        static OriginInfo fromNothing() {
12707            return new OriginInfo(null, null, false, false);
12708        }
12709
12710        static OriginInfo fromUntrustedFile(File file) {
12711            return new OriginInfo(file, null, false, false);
12712        }
12713
12714        static OriginInfo fromExistingFile(File file) {
12715            return new OriginInfo(file, null, false, true);
12716        }
12717
12718        static OriginInfo fromStagedFile(File file) {
12719            return new OriginInfo(file, null, true, false);
12720        }
12721
12722        static OriginInfo fromStagedContainer(String cid) {
12723            return new OriginInfo(null, cid, true, false);
12724        }
12725
12726        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12727            this.file = file;
12728            this.cid = cid;
12729            this.staged = staged;
12730            this.existing = existing;
12731
12732            if (cid != null) {
12733                resolvedPath = PackageHelper.getSdDir(cid);
12734                resolvedFile = new File(resolvedPath);
12735            } else if (file != null) {
12736                resolvedPath = file.getAbsolutePath();
12737                resolvedFile = file;
12738            } else {
12739                resolvedPath = null;
12740                resolvedFile = null;
12741            }
12742        }
12743    }
12744
12745    static class MoveInfo {
12746        final int moveId;
12747        final String fromUuid;
12748        final String toUuid;
12749        final String packageName;
12750        final String dataAppName;
12751        final int appId;
12752        final String seinfo;
12753        final int targetSdkVersion;
12754
12755        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12756                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12757            this.moveId = moveId;
12758            this.fromUuid = fromUuid;
12759            this.toUuid = toUuid;
12760            this.packageName = packageName;
12761            this.dataAppName = dataAppName;
12762            this.appId = appId;
12763            this.seinfo = seinfo;
12764            this.targetSdkVersion = targetSdkVersion;
12765        }
12766    }
12767
12768    static class VerificationInfo {
12769        /** A constant used to indicate that a uid value is not present. */
12770        public static final int NO_UID = -1;
12771
12772        /** URI referencing where the package was downloaded from. */
12773        final Uri originatingUri;
12774
12775        /** HTTP referrer URI associated with the originatingURI. */
12776        final Uri referrer;
12777
12778        /** UID of the application that the install request originated from. */
12779        final int originatingUid;
12780
12781        /** UID of application requesting the install */
12782        final int installerUid;
12783
12784        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12785            this.originatingUri = originatingUri;
12786            this.referrer = referrer;
12787            this.originatingUid = originatingUid;
12788            this.installerUid = installerUid;
12789        }
12790    }
12791
12792    class InstallParams extends HandlerParams {
12793        final OriginInfo origin;
12794        final MoveInfo move;
12795        final IPackageInstallObserver2 observer;
12796        int installFlags;
12797        final String installerPackageName;
12798        final String volumeUuid;
12799        private InstallArgs mArgs;
12800        private int mRet;
12801        final String packageAbiOverride;
12802        final String[] grantedRuntimePermissions;
12803        final VerificationInfo verificationInfo;
12804        final Certificate[][] certificates;
12805
12806        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12807                int installFlags, String installerPackageName, String volumeUuid,
12808                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12809                String[] grantedPermissions, Certificate[][] certificates) {
12810            super(user);
12811            this.origin = origin;
12812            this.move = move;
12813            this.observer = observer;
12814            this.installFlags = installFlags;
12815            this.installerPackageName = installerPackageName;
12816            this.volumeUuid = volumeUuid;
12817            this.verificationInfo = verificationInfo;
12818            this.packageAbiOverride = packageAbiOverride;
12819            this.grantedRuntimePermissions = grantedPermissions;
12820            this.certificates = certificates;
12821        }
12822
12823        @Override
12824        public String toString() {
12825            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12826                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12827        }
12828
12829        private int installLocationPolicy(PackageInfoLite pkgLite) {
12830            String packageName = pkgLite.packageName;
12831            int installLocation = pkgLite.installLocation;
12832            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12833            // reader
12834            synchronized (mPackages) {
12835                // Currently installed package which the new package is attempting to replace or
12836                // null if no such package is installed.
12837                PackageParser.Package installedPkg = mPackages.get(packageName);
12838                // Package which currently owns the data which the new package will own if installed.
12839                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12840                // will be null whereas dataOwnerPkg will contain information about the package
12841                // which was uninstalled while keeping its data.
12842                PackageParser.Package dataOwnerPkg = installedPkg;
12843                if (dataOwnerPkg  == null) {
12844                    PackageSetting ps = mSettings.mPackages.get(packageName);
12845                    if (ps != null) {
12846                        dataOwnerPkg = ps.pkg;
12847                    }
12848                }
12849
12850                if (dataOwnerPkg != null) {
12851                    // If installed, the package will get access to data left on the device by its
12852                    // predecessor. As a security measure, this is permited only if this is not a
12853                    // version downgrade or if the predecessor package is marked as debuggable and
12854                    // a downgrade is explicitly requested.
12855                    //
12856                    // On debuggable platform builds, downgrades are permitted even for
12857                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12858                    // not offer security guarantees and thus it's OK to disable some security
12859                    // mechanisms to make debugging/testing easier on those builds. However, even on
12860                    // debuggable builds downgrades of packages are permitted only if requested via
12861                    // installFlags. This is because we aim to keep the behavior of debuggable
12862                    // platform builds as close as possible to the behavior of non-debuggable
12863                    // platform builds.
12864                    final boolean downgradeRequested =
12865                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12866                    final boolean packageDebuggable =
12867                                (dataOwnerPkg.applicationInfo.flags
12868                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12869                    final boolean downgradePermitted =
12870                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12871                    if (!downgradePermitted) {
12872                        try {
12873                            checkDowngrade(dataOwnerPkg, pkgLite);
12874                        } catch (PackageManagerException e) {
12875                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12876                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12877                        }
12878                    }
12879                }
12880
12881                if (installedPkg != null) {
12882                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12883                        // Check for updated system application.
12884                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12885                            if (onSd) {
12886                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12887                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12888                            }
12889                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12890                        } else {
12891                            if (onSd) {
12892                                // Install flag overrides everything.
12893                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12894                            }
12895                            // If current upgrade specifies particular preference
12896                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12897                                // Application explicitly specified internal.
12898                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12899                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12900                                // App explictly prefers external. Let policy decide
12901                            } else {
12902                                // Prefer previous location
12903                                if (isExternal(installedPkg)) {
12904                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12905                                }
12906                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12907                            }
12908                        }
12909                    } else {
12910                        // Invalid install. Return error code
12911                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12912                    }
12913                }
12914            }
12915            // All the special cases have been taken care of.
12916            // Return result based on recommended install location.
12917            if (onSd) {
12918                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12919            }
12920            return pkgLite.recommendedInstallLocation;
12921        }
12922
12923        /*
12924         * Invoke remote method to get package information and install
12925         * location values. Override install location based on default
12926         * policy if needed and then create install arguments based
12927         * on the install location.
12928         */
12929        public void handleStartCopy() throws RemoteException {
12930            int ret = PackageManager.INSTALL_SUCCEEDED;
12931
12932            // If we're already staged, we've firmly committed to an install location
12933            if (origin.staged) {
12934                if (origin.file != null) {
12935                    installFlags |= PackageManager.INSTALL_INTERNAL;
12936                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12937                } else if (origin.cid != null) {
12938                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12939                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12940                } else {
12941                    throw new IllegalStateException("Invalid stage location");
12942                }
12943            }
12944
12945            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12946            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12947            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12948            PackageInfoLite pkgLite = null;
12949
12950            if (onInt && onSd) {
12951                // Check if both bits are set.
12952                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12953                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12954            } else if (onSd && ephemeral) {
12955                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12956                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12957            } else {
12958                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12959                        packageAbiOverride);
12960
12961                if (DEBUG_EPHEMERAL && ephemeral) {
12962                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12963                }
12964
12965                /*
12966                 * If we have too little free space, try to free cache
12967                 * before giving up.
12968                 */
12969                if (!origin.staged && pkgLite.recommendedInstallLocation
12970                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12971                    // TODO: focus freeing disk space on the target device
12972                    final StorageManager storage = StorageManager.from(mContext);
12973                    final long lowThreshold = storage.getStorageLowBytes(
12974                            Environment.getDataDirectory());
12975
12976                    final long sizeBytes = mContainerService.calculateInstalledSize(
12977                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12978
12979                    try {
12980                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12981                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12982                                installFlags, packageAbiOverride);
12983                    } catch (InstallerException e) {
12984                        Slog.w(TAG, "Failed to free cache", e);
12985                    }
12986
12987                    /*
12988                     * The cache free must have deleted the file we
12989                     * downloaded to install.
12990                     *
12991                     * TODO: fix the "freeCache" call to not delete
12992                     *       the file we care about.
12993                     */
12994                    if (pkgLite.recommendedInstallLocation
12995                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12996                        pkgLite.recommendedInstallLocation
12997                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12998                    }
12999                }
13000            }
13001
13002            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13003                int loc = pkgLite.recommendedInstallLocation;
13004                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13005                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13006                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13007                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13008                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13009                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13010                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13011                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13012                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13013                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13014                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13015                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13016                } else {
13017                    // Override with defaults if needed.
13018                    loc = installLocationPolicy(pkgLite);
13019                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13020                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13021                    } else if (!onSd && !onInt) {
13022                        // Override install location with flags
13023                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13024                            // Set the flag to install on external media.
13025                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13026                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13027                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13028                            if (DEBUG_EPHEMERAL) {
13029                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13030                            }
13031                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13032                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13033                                    |PackageManager.INSTALL_INTERNAL);
13034                        } else {
13035                            // Make sure the flag for installing on external
13036                            // media is unset
13037                            installFlags |= PackageManager.INSTALL_INTERNAL;
13038                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13039                        }
13040                    }
13041                }
13042            }
13043
13044            final InstallArgs args = createInstallArgs(this);
13045            mArgs = args;
13046
13047            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13048                // TODO: http://b/22976637
13049                // Apps installed for "all" users use the device owner to verify the app
13050                UserHandle verifierUser = getUser();
13051                if (verifierUser == UserHandle.ALL) {
13052                    verifierUser = UserHandle.SYSTEM;
13053                }
13054
13055                /*
13056                 * Determine if we have any installed package verifiers. If we
13057                 * do, then we'll defer to them to verify the packages.
13058                 */
13059                final int requiredUid = mRequiredVerifierPackage == null ? -1
13060                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13061                                verifierUser.getIdentifier());
13062                if (!origin.existing && requiredUid != -1
13063                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13064                    final Intent verification = new Intent(
13065                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13066                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13067                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13068                            PACKAGE_MIME_TYPE);
13069                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13070
13071                    // Query all live verifiers based on current user state
13072                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13073                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13074
13075                    if (DEBUG_VERIFY) {
13076                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13077                                + verification.toString() + " with " + pkgLite.verifiers.length
13078                                + " optional verifiers");
13079                    }
13080
13081                    final int verificationId = mPendingVerificationToken++;
13082
13083                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13084
13085                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13086                            installerPackageName);
13087
13088                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13089                            installFlags);
13090
13091                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13092                            pkgLite.packageName);
13093
13094                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13095                            pkgLite.versionCode);
13096
13097                    if (verificationInfo != null) {
13098                        if (verificationInfo.originatingUri != null) {
13099                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13100                                    verificationInfo.originatingUri);
13101                        }
13102                        if (verificationInfo.referrer != null) {
13103                            verification.putExtra(Intent.EXTRA_REFERRER,
13104                                    verificationInfo.referrer);
13105                        }
13106                        if (verificationInfo.originatingUid >= 0) {
13107                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13108                                    verificationInfo.originatingUid);
13109                        }
13110                        if (verificationInfo.installerUid >= 0) {
13111                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13112                                    verificationInfo.installerUid);
13113                        }
13114                    }
13115
13116                    final PackageVerificationState verificationState = new PackageVerificationState(
13117                            requiredUid, args);
13118
13119                    mPendingVerification.append(verificationId, verificationState);
13120
13121                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13122                            receivers, verificationState);
13123
13124                    /*
13125                     * If any sufficient verifiers were listed in the package
13126                     * manifest, attempt to ask them.
13127                     */
13128                    if (sufficientVerifiers != null) {
13129                        final int N = sufficientVerifiers.size();
13130                        if (N == 0) {
13131                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13132                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13133                        } else {
13134                            for (int i = 0; i < N; i++) {
13135                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13136
13137                                final Intent sufficientIntent = new Intent(verification);
13138                                sufficientIntent.setComponent(verifierComponent);
13139                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13140                            }
13141                        }
13142                    }
13143
13144                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13145                            mRequiredVerifierPackage, receivers);
13146                    if (ret == PackageManager.INSTALL_SUCCEEDED
13147                            && mRequiredVerifierPackage != null) {
13148                        Trace.asyncTraceBegin(
13149                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13150                        /*
13151                         * Send the intent to the required verification agent,
13152                         * but only start the verification timeout after the
13153                         * target BroadcastReceivers have run.
13154                         */
13155                        verification.setComponent(requiredVerifierComponent);
13156                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13157                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13158                                new BroadcastReceiver() {
13159                                    @Override
13160                                    public void onReceive(Context context, Intent intent) {
13161                                        final Message msg = mHandler
13162                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13163                                        msg.arg1 = verificationId;
13164                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13165                                    }
13166                                }, null, 0, null, null);
13167
13168                        /*
13169                         * We don't want the copy to proceed until verification
13170                         * succeeds, so null out this field.
13171                         */
13172                        mArgs = null;
13173                    }
13174                } else {
13175                    /*
13176                     * No package verification is enabled, so immediately start
13177                     * the remote call to initiate copy using temporary file.
13178                     */
13179                    ret = args.copyApk(mContainerService, true);
13180                }
13181            }
13182
13183            mRet = ret;
13184        }
13185
13186        @Override
13187        void handleReturnCode() {
13188            // If mArgs is null, then MCS couldn't be reached. When it
13189            // reconnects, it will try again to install. At that point, this
13190            // will succeed.
13191            if (mArgs != null) {
13192                processPendingInstall(mArgs, mRet);
13193            }
13194        }
13195
13196        @Override
13197        void handleServiceError() {
13198            mArgs = createInstallArgs(this);
13199            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13200        }
13201
13202        public boolean isForwardLocked() {
13203            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13204        }
13205    }
13206
13207    /**
13208     * Used during creation of InstallArgs
13209     *
13210     * @param installFlags package installation flags
13211     * @return true if should be installed on external storage
13212     */
13213    private static boolean installOnExternalAsec(int installFlags) {
13214        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13215            return false;
13216        }
13217        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13218            return true;
13219        }
13220        return false;
13221    }
13222
13223    /**
13224     * Used during creation of InstallArgs
13225     *
13226     * @param installFlags package installation flags
13227     * @return true if should be installed as forward locked
13228     */
13229    private static boolean installForwardLocked(int installFlags) {
13230        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13231    }
13232
13233    private InstallArgs createInstallArgs(InstallParams params) {
13234        if (params.move != null) {
13235            return new MoveInstallArgs(params);
13236        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13237            return new AsecInstallArgs(params);
13238        } else {
13239            return new FileInstallArgs(params);
13240        }
13241    }
13242
13243    /**
13244     * Create args that describe an existing installed package. Typically used
13245     * when cleaning up old installs, or used as a move source.
13246     */
13247    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13248            String resourcePath, String[] instructionSets) {
13249        final boolean isInAsec;
13250        if (installOnExternalAsec(installFlags)) {
13251            /* Apps on SD card are always in ASEC containers. */
13252            isInAsec = true;
13253        } else if (installForwardLocked(installFlags)
13254                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13255            /*
13256             * Forward-locked apps are only in ASEC containers if they're the
13257             * new style
13258             */
13259            isInAsec = true;
13260        } else {
13261            isInAsec = false;
13262        }
13263
13264        if (isInAsec) {
13265            return new AsecInstallArgs(codePath, instructionSets,
13266                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13267        } else {
13268            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13269        }
13270    }
13271
13272    static abstract class InstallArgs {
13273        /** @see InstallParams#origin */
13274        final OriginInfo origin;
13275        /** @see InstallParams#move */
13276        final MoveInfo move;
13277
13278        final IPackageInstallObserver2 observer;
13279        // Always refers to PackageManager flags only
13280        final int installFlags;
13281        final String installerPackageName;
13282        final String volumeUuid;
13283        final UserHandle user;
13284        final String abiOverride;
13285        final String[] installGrantPermissions;
13286        /** If non-null, drop an async trace when the install completes */
13287        final String traceMethod;
13288        final int traceCookie;
13289        final Certificate[][] certificates;
13290
13291        // The list of instruction sets supported by this app. This is currently
13292        // only used during the rmdex() phase to clean up resources. We can get rid of this
13293        // if we move dex files under the common app path.
13294        /* nullable */ String[] instructionSets;
13295
13296        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13297                int installFlags, String installerPackageName, String volumeUuid,
13298                UserHandle user, String[] instructionSets,
13299                String abiOverride, String[] installGrantPermissions,
13300                String traceMethod, int traceCookie, Certificate[][] certificates) {
13301            this.origin = origin;
13302            this.move = move;
13303            this.installFlags = installFlags;
13304            this.observer = observer;
13305            this.installerPackageName = installerPackageName;
13306            this.volumeUuid = volumeUuid;
13307            this.user = user;
13308            this.instructionSets = instructionSets;
13309            this.abiOverride = abiOverride;
13310            this.installGrantPermissions = installGrantPermissions;
13311            this.traceMethod = traceMethod;
13312            this.traceCookie = traceCookie;
13313            this.certificates = certificates;
13314        }
13315
13316        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13317        abstract int doPreInstall(int status);
13318
13319        /**
13320         * Rename package into final resting place. All paths on the given
13321         * scanned package should be updated to reflect the rename.
13322         */
13323        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13324        abstract int doPostInstall(int status, int uid);
13325
13326        /** @see PackageSettingBase#codePathString */
13327        abstract String getCodePath();
13328        /** @see PackageSettingBase#resourcePathString */
13329        abstract String getResourcePath();
13330
13331        // Need installer lock especially for dex file removal.
13332        abstract void cleanUpResourcesLI();
13333        abstract boolean doPostDeleteLI(boolean delete);
13334
13335        /**
13336         * Called before the source arguments are copied. This is used mostly
13337         * for MoveParams when it needs to read the source file to put it in the
13338         * destination.
13339         */
13340        int doPreCopy() {
13341            return PackageManager.INSTALL_SUCCEEDED;
13342        }
13343
13344        /**
13345         * Called after the source arguments are copied. This is used mostly for
13346         * MoveParams when it needs to read the source file to put it in the
13347         * destination.
13348         */
13349        int doPostCopy(int uid) {
13350            return PackageManager.INSTALL_SUCCEEDED;
13351        }
13352
13353        protected boolean isFwdLocked() {
13354            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13355        }
13356
13357        protected boolean isExternalAsec() {
13358            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13359        }
13360
13361        protected boolean isEphemeral() {
13362            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13363        }
13364
13365        UserHandle getUser() {
13366            return user;
13367        }
13368    }
13369
13370    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13371        if (!allCodePaths.isEmpty()) {
13372            if (instructionSets == null) {
13373                throw new IllegalStateException("instructionSet == null");
13374            }
13375            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13376            for (String codePath : allCodePaths) {
13377                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13378                    try {
13379                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13380                    } catch (InstallerException ignored) {
13381                    }
13382                }
13383            }
13384        }
13385    }
13386
13387    /**
13388     * Logic to handle installation of non-ASEC applications, including copying
13389     * and renaming logic.
13390     */
13391    class FileInstallArgs extends InstallArgs {
13392        private File codeFile;
13393        private File resourceFile;
13394
13395        // Example topology:
13396        // /data/app/com.example/base.apk
13397        // /data/app/com.example/split_foo.apk
13398        // /data/app/com.example/lib/arm/libfoo.so
13399        // /data/app/com.example/lib/arm64/libfoo.so
13400        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13401
13402        /** New install */
13403        FileInstallArgs(InstallParams params) {
13404            super(params.origin, params.move, params.observer, params.installFlags,
13405                    params.installerPackageName, params.volumeUuid,
13406                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13407                    params.grantedRuntimePermissions,
13408                    params.traceMethod, params.traceCookie, params.certificates);
13409            if (isFwdLocked()) {
13410                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13411            }
13412        }
13413
13414        /** Existing install */
13415        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13416            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13417                    null, null, null, 0, null /*certificates*/);
13418            this.codeFile = (codePath != null) ? new File(codePath) : null;
13419            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13420        }
13421
13422        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13423            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13424            try {
13425                return doCopyApk(imcs, temp);
13426            } finally {
13427                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13428            }
13429        }
13430
13431        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13432            if (origin.staged) {
13433                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13434                codeFile = origin.file;
13435                resourceFile = origin.file;
13436                return PackageManager.INSTALL_SUCCEEDED;
13437            }
13438
13439            try {
13440                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13441                final File tempDir =
13442                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13443                codeFile = tempDir;
13444                resourceFile = tempDir;
13445            } catch (IOException e) {
13446                Slog.w(TAG, "Failed to create copy file: " + e);
13447                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13448            }
13449
13450            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13451                @Override
13452                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13453                    if (!FileUtils.isValidExtFilename(name)) {
13454                        throw new IllegalArgumentException("Invalid filename: " + name);
13455                    }
13456                    try {
13457                        final File file = new File(codeFile, name);
13458                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13459                                O_RDWR | O_CREAT, 0644);
13460                        Os.chmod(file.getAbsolutePath(), 0644);
13461                        return new ParcelFileDescriptor(fd);
13462                    } catch (ErrnoException e) {
13463                        throw new RemoteException("Failed to open: " + e.getMessage());
13464                    }
13465                }
13466            };
13467
13468            int ret = PackageManager.INSTALL_SUCCEEDED;
13469            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13470            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13471                Slog.e(TAG, "Failed to copy package");
13472                return ret;
13473            }
13474
13475            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13476            NativeLibraryHelper.Handle handle = null;
13477            try {
13478                handle = NativeLibraryHelper.Handle.create(codeFile);
13479                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13480                        abiOverride);
13481            } catch (IOException e) {
13482                Slog.e(TAG, "Copying native libraries failed", e);
13483                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13484            } finally {
13485                IoUtils.closeQuietly(handle);
13486            }
13487
13488            return ret;
13489        }
13490
13491        int doPreInstall(int status) {
13492            if (status != PackageManager.INSTALL_SUCCEEDED) {
13493                cleanUp();
13494            }
13495            return status;
13496        }
13497
13498        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13499            if (status != PackageManager.INSTALL_SUCCEEDED) {
13500                cleanUp();
13501                return false;
13502            }
13503
13504            final File targetDir = codeFile.getParentFile();
13505            final File beforeCodeFile = codeFile;
13506            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13507
13508            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13509            try {
13510                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13511            } catch (ErrnoException e) {
13512                Slog.w(TAG, "Failed to rename", e);
13513                return false;
13514            }
13515
13516            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13517                Slog.w(TAG, "Failed to restorecon");
13518                return false;
13519            }
13520
13521            // Reflect the rename internally
13522            codeFile = afterCodeFile;
13523            resourceFile = afterCodeFile;
13524
13525            // Reflect the rename in scanned details
13526            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13527            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13528                    afterCodeFile, pkg.baseCodePath));
13529            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13530                    afterCodeFile, pkg.splitCodePaths));
13531
13532            // Reflect the rename in app info
13533            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13534            pkg.setApplicationInfoCodePath(pkg.codePath);
13535            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13536            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13537            pkg.setApplicationInfoResourcePath(pkg.codePath);
13538            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13539            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13540
13541            return true;
13542        }
13543
13544        int doPostInstall(int status, int uid) {
13545            if (status != PackageManager.INSTALL_SUCCEEDED) {
13546                cleanUp();
13547            }
13548            return status;
13549        }
13550
13551        @Override
13552        String getCodePath() {
13553            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13554        }
13555
13556        @Override
13557        String getResourcePath() {
13558            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13559        }
13560
13561        private boolean cleanUp() {
13562            if (codeFile == null || !codeFile.exists()) {
13563                return false;
13564            }
13565
13566            removeCodePathLI(codeFile);
13567
13568            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13569                resourceFile.delete();
13570            }
13571
13572            return true;
13573        }
13574
13575        void cleanUpResourcesLI() {
13576            // Try enumerating all code paths before deleting
13577            List<String> allCodePaths = Collections.EMPTY_LIST;
13578            if (codeFile != null && codeFile.exists()) {
13579                try {
13580                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13581                    allCodePaths = pkg.getAllCodePaths();
13582                } catch (PackageParserException e) {
13583                    // Ignored; we tried our best
13584                }
13585            }
13586
13587            cleanUp();
13588            removeDexFiles(allCodePaths, instructionSets);
13589        }
13590
13591        boolean doPostDeleteLI(boolean delete) {
13592            // XXX err, shouldn't we respect the delete flag?
13593            cleanUpResourcesLI();
13594            return true;
13595        }
13596    }
13597
13598    private boolean isAsecExternal(String cid) {
13599        final String asecPath = PackageHelper.getSdFilesystem(cid);
13600        return !asecPath.startsWith(mAsecInternalPath);
13601    }
13602
13603    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13604            PackageManagerException {
13605        if (copyRet < 0) {
13606            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13607                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13608                throw new PackageManagerException(copyRet, message);
13609            }
13610        }
13611    }
13612
13613    /**
13614     * Extract the MountService "container ID" from the full code path of an
13615     * .apk.
13616     */
13617    static String cidFromCodePath(String fullCodePath) {
13618        int eidx = fullCodePath.lastIndexOf("/");
13619        String subStr1 = fullCodePath.substring(0, eidx);
13620        int sidx = subStr1.lastIndexOf("/");
13621        return subStr1.substring(sidx+1, eidx);
13622    }
13623
13624    /**
13625     * Logic to handle installation of ASEC applications, including copying and
13626     * renaming logic.
13627     */
13628    class AsecInstallArgs extends InstallArgs {
13629        static final String RES_FILE_NAME = "pkg.apk";
13630        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13631
13632        String cid;
13633        String packagePath;
13634        String resourcePath;
13635
13636        /** New install */
13637        AsecInstallArgs(InstallParams params) {
13638            super(params.origin, params.move, params.observer, params.installFlags,
13639                    params.installerPackageName, params.volumeUuid,
13640                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13641                    params.grantedRuntimePermissions,
13642                    params.traceMethod, params.traceCookie, params.certificates);
13643        }
13644
13645        /** Existing install */
13646        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13647                        boolean isExternal, boolean isForwardLocked) {
13648            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13649              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13650                    instructionSets, null, null, null, 0, null /*certificates*/);
13651            // Hackily pretend we're still looking at a full code path
13652            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13653                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13654            }
13655
13656            // Extract cid from fullCodePath
13657            int eidx = fullCodePath.lastIndexOf("/");
13658            String subStr1 = fullCodePath.substring(0, eidx);
13659            int sidx = subStr1.lastIndexOf("/");
13660            cid = subStr1.substring(sidx+1, eidx);
13661            setMountPath(subStr1);
13662        }
13663
13664        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13665            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13666              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13667                    instructionSets, null, null, null, 0, null /*certificates*/);
13668            this.cid = cid;
13669            setMountPath(PackageHelper.getSdDir(cid));
13670        }
13671
13672        void createCopyFile() {
13673            cid = mInstallerService.allocateExternalStageCidLegacy();
13674        }
13675
13676        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13677            if (origin.staged && origin.cid != null) {
13678                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13679                cid = origin.cid;
13680                setMountPath(PackageHelper.getSdDir(cid));
13681                return PackageManager.INSTALL_SUCCEEDED;
13682            }
13683
13684            if (temp) {
13685                createCopyFile();
13686            } else {
13687                /*
13688                 * Pre-emptively destroy the container since it's destroyed if
13689                 * copying fails due to it existing anyway.
13690                 */
13691                PackageHelper.destroySdDir(cid);
13692            }
13693
13694            final String newMountPath = imcs.copyPackageToContainer(
13695                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13696                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13697
13698            if (newMountPath != null) {
13699                setMountPath(newMountPath);
13700                return PackageManager.INSTALL_SUCCEEDED;
13701            } else {
13702                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13703            }
13704        }
13705
13706        @Override
13707        String getCodePath() {
13708            return packagePath;
13709        }
13710
13711        @Override
13712        String getResourcePath() {
13713            return resourcePath;
13714        }
13715
13716        int doPreInstall(int status) {
13717            if (status != PackageManager.INSTALL_SUCCEEDED) {
13718                // Destroy container
13719                PackageHelper.destroySdDir(cid);
13720            } else {
13721                boolean mounted = PackageHelper.isContainerMounted(cid);
13722                if (!mounted) {
13723                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13724                            Process.SYSTEM_UID);
13725                    if (newMountPath != null) {
13726                        setMountPath(newMountPath);
13727                    } else {
13728                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13729                    }
13730                }
13731            }
13732            return status;
13733        }
13734
13735        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13736            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13737            String newMountPath = null;
13738            if (PackageHelper.isContainerMounted(cid)) {
13739                // Unmount the container
13740                if (!PackageHelper.unMountSdDir(cid)) {
13741                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13742                    return false;
13743                }
13744            }
13745            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13746                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13747                        " which might be stale. Will try to clean up.");
13748                // Clean up the stale container and proceed to recreate.
13749                if (!PackageHelper.destroySdDir(newCacheId)) {
13750                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13751                    return false;
13752                }
13753                // Successfully cleaned up stale container. Try to rename again.
13754                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13755                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13756                            + " inspite of cleaning it up.");
13757                    return false;
13758                }
13759            }
13760            if (!PackageHelper.isContainerMounted(newCacheId)) {
13761                Slog.w(TAG, "Mounting container " + newCacheId);
13762                newMountPath = PackageHelper.mountSdDir(newCacheId,
13763                        getEncryptKey(), Process.SYSTEM_UID);
13764            } else {
13765                newMountPath = PackageHelper.getSdDir(newCacheId);
13766            }
13767            if (newMountPath == null) {
13768                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13769                return false;
13770            }
13771            Log.i(TAG, "Succesfully renamed " + cid +
13772                    " to " + newCacheId +
13773                    " at new path: " + newMountPath);
13774            cid = newCacheId;
13775
13776            final File beforeCodeFile = new File(packagePath);
13777            setMountPath(newMountPath);
13778            final File afterCodeFile = new File(packagePath);
13779
13780            // Reflect the rename in scanned details
13781            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13782            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13783                    afterCodeFile, pkg.baseCodePath));
13784            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13785                    afterCodeFile, pkg.splitCodePaths));
13786
13787            // Reflect the rename in app info
13788            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13789            pkg.setApplicationInfoCodePath(pkg.codePath);
13790            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13791            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13792            pkg.setApplicationInfoResourcePath(pkg.codePath);
13793            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13794            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13795
13796            return true;
13797        }
13798
13799        private void setMountPath(String mountPath) {
13800            final File mountFile = new File(mountPath);
13801
13802            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13803            if (monolithicFile.exists()) {
13804                packagePath = monolithicFile.getAbsolutePath();
13805                if (isFwdLocked()) {
13806                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13807                } else {
13808                    resourcePath = packagePath;
13809                }
13810            } else {
13811                packagePath = mountFile.getAbsolutePath();
13812                resourcePath = packagePath;
13813            }
13814        }
13815
13816        int doPostInstall(int status, int uid) {
13817            if (status != PackageManager.INSTALL_SUCCEEDED) {
13818                cleanUp();
13819            } else {
13820                final int groupOwner;
13821                final String protectedFile;
13822                if (isFwdLocked()) {
13823                    groupOwner = UserHandle.getSharedAppGid(uid);
13824                    protectedFile = RES_FILE_NAME;
13825                } else {
13826                    groupOwner = -1;
13827                    protectedFile = null;
13828                }
13829
13830                if (uid < Process.FIRST_APPLICATION_UID
13831                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13832                    Slog.e(TAG, "Failed to finalize " + cid);
13833                    PackageHelper.destroySdDir(cid);
13834                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13835                }
13836
13837                boolean mounted = PackageHelper.isContainerMounted(cid);
13838                if (!mounted) {
13839                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13840                }
13841            }
13842            return status;
13843        }
13844
13845        private void cleanUp() {
13846            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13847
13848            // Destroy secure container
13849            PackageHelper.destroySdDir(cid);
13850        }
13851
13852        private List<String> getAllCodePaths() {
13853            final File codeFile = new File(getCodePath());
13854            if (codeFile != null && codeFile.exists()) {
13855                try {
13856                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13857                    return pkg.getAllCodePaths();
13858                } catch (PackageParserException e) {
13859                    // Ignored; we tried our best
13860                }
13861            }
13862            return Collections.EMPTY_LIST;
13863        }
13864
13865        void cleanUpResourcesLI() {
13866            // Enumerate all code paths before deleting
13867            cleanUpResourcesLI(getAllCodePaths());
13868        }
13869
13870        private void cleanUpResourcesLI(List<String> allCodePaths) {
13871            cleanUp();
13872            removeDexFiles(allCodePaths, instructionSets);
13873        }
13874
13875        String getPackageName() {
13876            return getAsecPackageName(cid);
13877        }
13878
13879        boolean doPostDeleteLI(boolean delete) {
13880            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13881            final List<String> allCodePaths = getAllCodePaths();
13882            boolean mounted = PackageHelper.isContainerMounted(cid);
13883            if (mounted) {
13884                // Unmount first
13885                if (PackageHelper.unMountSdDir(cid)) {
13886                    mounted = false;
13887                }
13888            }
13889            if (!mounted && delete) {
13890                cleanUpResourcesLI(allCodePaths);
13891            }
13892            return !mounted;
13893        }
13894
13895        @Override
13896        int doPreCopy() {
13897            if (isFwdLocked()) {
13898                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13899                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13900                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13901                }
13902            }
13903
13904            return PackageManager.INSTALL_SUCCEEDED;
13905        }
13906
13907        @Override
13908        int doPostCopy(int uid) {
13909            if (isFwdLocked()) {
13910                if (uid < Process.FIRST_APPLICATION_UID
13911                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13912                                RES_FILE_NAME)) {
13913                    Slog.e(TAG, "Failed to finalize " + cid);
13914                    PackageHelper.destroySdDir(cid);
13915                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13916                }
13917            }
13918
13919            return PackageManager.INSTALL_SUCCEEDED;
13920        }
13921    }
13922
13923    /**
13924     * Logic to handle movement of existing installed applications.
13925     */
13926    class MoveInstallArgs extends InstallArgs {
13927        private File codeFile;
13928        private File resourceFile;
13929
13930        /** New install */
13931        MoveInstallArgs(InstallParams params) {
13932            super(params.origin, params.move, params.observer, params.installFlags,
13933                    params.installerPackageName, params.volumeUuid,
13934                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13935                    params.grantedRuntimePermissions,
13936                    params.traceMethod, params.traceCookie, params.certificates);
13937        }
13938
13939        int copyApk(IMediaContainerService imcs, boolean temp) {
13940            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13941                    + move.fromUuid + " to " + move.toUuid);
13942            synchronized (mInstaller) {
13943                try {
13944                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13945                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13946                } catch (InstallerException e) {
13947                    Slog.w(TAG, "Failed to move app", e);
13948                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13949                }
13950            }
13951
13952            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13953            resourceFile = codeFile;
13954            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13955
13956            return PackageManager.INSTALL_SUCCEEDED;
13957        }
13958
13959        int doPreInstall(int status) {
13960            if (status != PackageManager.INSTALL_SUCCEEDED) {
13961                cleanUp(move.toUuid);
13962            }
13963            return status;
13964        }
13965
13966        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13967            if (status != PackageManager.INSTALL_SUCCEEDED) {
13968                cleanUp(move.toUuid);
13969                return false;
13970            }
13971
13972            // Reflect the move in app info
13973            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13974            pkg.setApplicationInfoCodePath(pkg.codePath);
13975            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13976            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13977            pkg.setApplicationInfoResourcePath(pkg.codePath);
13978            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13979            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13980
13981            return true;
13982        }
13983
13984        int doPostInstall(int status, int uid) {
13985            if (status == PackageManager.INSTALL_SUCCEEDED) {
13986                cleanUp(move.fromUuid);
13987            } else {
13988                cleanUp(move.toUuid);
13989            }
13990            return status;
13991        }
13992
13993        @Override
13994        String getCodePath() {
13995            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13996        }
13997
13998        @Override
13999        String getResourcePath() {
14000            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14001        }
14002
14003        private boolean cleanUp(String volumeUuid) {
14004            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14005                    move.dataAppName);
14006            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14007            final int[] userIds = sUserManager.getUserIds();
14008            synchronized (mInstallLock) {
14009                // Clean up both app data and code
14010                // All package moves are frozen until finished
14011                for (int userId : userIds) {
14012                    try {
14013                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14014                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14015                    } catch (InstallerException e) {
14016                        Slog.w(TAG, String.valueOf(e));
14017                    }
14018                }
14019                removeCodePathLI(codeFile);
14020            }
14021            return true;
14022        }
14023
14024        void cleanUpResourcesLI() {
14025            throw new UnsupportedOperationException();
14026        }
14027
14028        boolean doPostDeleteLI(boolean delete) {
14029            throw new UnsupportedOperationException();
14030        }
14031    }
14032
14033    static String getAsecPackageName(String packageCid) {
14034        int idx = packageCid.lastIndexOf("-");
14035        if (idx == -1) {
14036            return packageCid;
14037        }
14038        return packageCid.substring(0, idx);
14039    }
14040
14041    // Utility method used to create code paths based on package name and available index.
14042    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14043        String idxStr = "";
14044        int idx = 1;
14045        // Fall back to default value of idx=1 if prefix is not
14046        // part of oldCodePath
14047        if (oldCodePath != null) {
14048            String subStr = oldCodePath;
14049            // Drop the suffix right away
14050            if (suffix != null && subStr.endsWith(suffix)) {
14051                subStr = subStr.substring(0, subStr.length() - suffix.length());
14052            }
14053            // If oldCodePath already contains prefix find out the
14054            // ending index to either increment or decrement.
14055            int sidx = subStr.lastIndexOf(prefix);
14056            if (sidx != -1) {
14057                subStr = subStr.substring(sidx + prefix.length());
14058                if (subStr != null) {
14059                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14060                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14061                    }
14062                    try {
14063                        idx = Integer.parseInt(subStr);
14064                        if (idx <= 1) {
14065                            idx++;
14066                        } else {
14067                            idx--;
14068                        }
14069                    } catch(NumberFormatException e) {
14070                    }
14071                }
14072            }
14073        }
14074        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14075        return prefix + idxStr;
14076    }
14077
14078    private File getNextCodePath(File targetDir, String packageName) {
14079        int suffix = 1;
14080        File result;
14081        do {
14082            result = new File(targetDir, packageName + "-" + suffix);
14083            suffix++;
14084        } while (result.exists());
14085        return result;
14086    }
14087
14088    // Utility method that returns the relative package path with respect
14089    // to the installation directory. Like say for /data/data/com.test-1.apk
14090    // string com.test-1 is returned.
14091    static String deriveCodePathName(String codePath) {
14092        if (codePath == null) {
14093            return null;
14094        }
14095        final File codeFile = new File(codePath);
14096        final String name = codeFile.getName();
14097        if (codeFile.isDirectory()) {
14098            return name;
14099        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14100            final int lastDot = name.lastIndexOf('.');
14101            return name.substring(0, lastDot);
14102        } else {
14103            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14104            return null;
14105        }
14106    }
14107
14108    static class PackageInstalledInfo {
14109        String name;
14110        int uid;
14111        // The set of users that originally had this package installed.
14112        int[] origUsers;
14113        // The set of users that now have this package installed.
14114        int[] newUsers;
14115        PackageParser.Package pkg;
14116        int returnCode;
14117        String returnMsg;
14118        PackageRemovedInfo removedInfo;
14119        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14120
14121        public void setError(int code, String msg) {
14122            setReturnCode(code);
14123            setReturnMessage(msg);
14124            Slog.w(TAG, msg);
14125        }
14126
14127        public void setError(String msg, PackageParserException e) {
14128            setReturnCode(e.error);
14129            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14130            Slog.w(TAG, msg, e);
14131        }
14132
14133        public void setError(String msg, PackageManagerException e) {
14134            returnCode = e.error;
14135            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14136            Slog.w(TAG, msg, e);
14137        }
14138
14139        public void setReturnCode(int returnCode) {
14140            this.returnCode = returnCode;
14141            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14142            for (int i = 0; i < childCount; i++) {
14143                addedChildPackages.valueAt(i).returnCode = returnCode;
14144            }
14145        }
14146
14147        private void setReturnMessage(String returnMsg) {
14148            this.returnMsg = returnMsg;
14149            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14150            for (int i = 0; i < childCount; i++) {
14151                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14152            }
14153        }
14154
14155        // In some error cases we want to convey more info back to the observer
14156        String origPackage;
14157        String origPermission;
14158    }
14159
14160    /*
14161     * Install a non-existing package.
14162     */
14163    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14164            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14165            PackageInstalledInfo res) {
14166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14167
14168        // Remember this for later, in case we need to rollback this install
14169        String pkgName = pkg.packageName;
14170
14171        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14172
14173        synchronized(mPackages) {
14174            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14175                // A package with the same name is already installed, though
14176                // it has been renamed to an older name.  The package we
14177                // are trying to install should be installed as an update to
14178                // the existing one, but that has not been requested, so bail.
14179                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14180                        + " without first uninstalling package running as "
14181                        + mSettings.mRenamedPackages.get(pkgName));
14182                return;
14183            }
14184            if (mPackages.containsKey(pkgName)) {
14185                // Don't allow installation over an existing package with the same name.
14186                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14187                        + " without first uninstalling.");
14188                return;
14189            }
14190        }
14191
14192        try {
14193            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14194                    System.currentTimeMillis(), user);
14195
14196            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14197
14198            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14199                prepareAppDataAfterInstallLIF(newPackage);
14200
14201            } else {
14202                // Remove package from internal structures, but keep around any
14203                // data that might have already existed
14204                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14205                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14206            }
14207        } catch (PackageManagerException e) {
14208            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14209        }
14210
14211        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14212    }
14213
14214    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14215        // Can't rotate keys during boot or if sharedUser.
14216        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14217                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14218            return false;
14219        }
14220        // app is using upgradeKeySets; make sure all are valid
14221        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14222        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14223        for (int i = 0; i < upgradeKeySets.length; i++) {
14224            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14225                Slog.wtf(TAG, "Package "
14226                         + (oldPs.name != null ? oldPs.name : "<null>")
14227                         + " contains upgrade-key-set reference to unknown key-set: "
14228                         + upgradeKeySets[i]
14229                         + " reverting to signatures check.");
14230                return false;
14231            }
14232        }
14233        return true;
14234    }
14235
14236    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14237        // Upgrade keysets are being used.  Determine if new package has a superset of the
14238        // required keys.
14239        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14240        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14241        for (int i = 0; i < upgradeKeySets.length; i++) {
14242            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14243            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14244                return true;
14245            }
14246        }
14247        return false;
14248    }
14249
14250    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14251        try (DigestInputStream digestStream =
14252                new DigestInputStream(new FileInputStream(file), digest)) {
14253            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14254        }
14255    }
14256
14257    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14258            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14259        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14260
14261        final PackageParser.Package oldPackage;
14262        final String pkgName = pkg.packageName;
14263        final int[] allUsers;
14264        final int[] installedUsers;
14265
14266        synchronized(mPackages) {
14267            oldPackage = mPackages.get(pkgName);
14268            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14269
14270            // don't allow upgrade to target a release SDK from a pre-release SDK
14271            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14272                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14273            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14274                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14275            if (oldTargetsPreRelease
14276                    && !newTargetsPreRelease
14277                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14278                Slog.w(TAG, "Can't install package targeting released sdk");
14279                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14280                return;
14281            }
14282
14283            // don't allow an upgrade from full to ephemeral
14284            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14285            if (isEphemeral && !oldIsEphemeral) {
14286                // can't downgrade from full to ephemeral
14287                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14288                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14289                return;
14290            }
14291
14292            // verify signatures are valid
14293            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14294            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14295                if (!checkUpgradeKeySetLP(ps, pkg)) {
14296                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14297                            "New package not signed by keys specified by upgrade-keysets: "
14298                                    + pkgName);
14299                    return;
14300                }
14301            } else {
14302                // default to original signature matching
14303                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14304                        != PackageManager.SIGNATURE_MATCH) {
14305                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14306                            "New package has a different signature: " + pkgName);
14307                    return;
14308                }
14309            }
14310
14311            // don't allow a system upgrade unless the upgrade hash matches
14312            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14313                byte[] digestBytes = null;
14314                try {
14315                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14316                    updateDigest(digest, new File(pkg.baseCodePath));
14317                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14318                        for (String path : pkg.splitCodePaths) {
14319                            updateDigest(digest, new File(path));
14320                        }
14321                    }
14322                    digestBytes = digest.digest();
14323                } catch (NoSuchAlgorithmException | IOException e) {
14324                    res.setError(INSTALL_FAILED_INVALID_APK,
14325                            "Could not compute hash: " + pkgName);
14326                    return;
14327                }
14328                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14329                    res.setError(INSTALL_FAILED_INVALID_APK,
14330                            "New package fails restrict-update check: " + pkgName);
14331                    return;
14332                }
14333                // retain upgrade restriction
14334                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14335            }
14336
14337            // Check for shared user id changes
14338            String invalidPackageName =
14339                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14340            if (invalidPackageName != null) {
14341                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14342                        "Package " + invalidPackageName + " tried to change user "
14343                                + oldPackage.mSharedUserId);
14344                return;
14345            }
14346
14347            // In case of rollback, remember per-user/profile install state
14348            allUsers = sUserManager.getUserIds();
14349            installedUsers = ps.queryInstalledUsers(allUsers, true);
14350        }
14351
14352        // Update what is removed
14353        res.removedInfo = new PackageRemovedInfo();
14354        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14355        res.removedInfo.removedPackage = oldPackage.packageName;
14356        res.removedInfo.isUpdate = true;
14357        res.removedInfo.origUsers = installedUsers;
14358        final int childCount = (oldPackage.childPackages != null)
14359                ? oldPackage.childPackages.size() : 0;
14360        for (int i = 0; i < childCount; i++) {
14361            boolean childPackageUpdated = false;
14362            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14363            if (res.addedChildPackages != null) {
14364                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14365                if (childRes != null) {
14366                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14367                    childRes.removedInfo.removedPackage = childPkg.packageName;
14368                    childRes.removedInfo.isUpdate = true;
14369                    childPackageUpdated = true;
14370                }
14371            }
14372            if (!childPackageUpdated) {
14373                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14374                childRemovedRes.removedPackage = childPkg.packageName;
14375                childRemovedRes.isUpdate = false;
14376                childRemovedRes.dataRemoved = true;
14377                synchronized (mPackages) {
14378                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14379                    if (childPs != null) {
14380                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14381                    }
14382                }
14383                if (res.removedInfo.removedChildPackages == null) {
14384                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14385                }
14386                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14387            }
14388        }
14389
14390        boolean sysPkg = (isSystemApp(oldPackage));
14391        if (sysPkg) {
14392            // Set the system/privileged flags as needed
14393            final boolean privileged =
14394                    (oldPackage.applicationInfo.privateFlags
14395                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14396            final int systemPolicyFlags = policyFlags
14397                    | PackageParser.PARSE_IS_SYSTEM
14398                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14399
14400            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14401                    user, allUsers, installerPackageName, res);
14402        } else {
14403            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14404                    user, allUsers, installerPackageName, res);
14405        }
14406    }
14407
14408    public List<String> getPreviousCodePaths(String packageName) {
14409        final PackageSetting ps = mSettings.mPackages.get(packageName);
14410        final List<String> result = new ArrayList<String>();
14411        if (ps != null && ps.oldCodePaths != null) {
14412            result.addAll(ps.oldCodePaths);
14413        }
14414        return result;
14415    }
14416
14417    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14418            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14419            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14420        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14421                + deletedPackage);
14422
14423        String pkgName = deletedPackage.packageName;
14424        boolean deletedPkg = true;
14425        boolean addedPkg = false;
14426        boolean updatedSettings = false;
14427        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14428        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14429                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14430
14431        final long origUpdateTime = (pkg.mExtras != null)
14432                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14433
14434        // First delete the existing package while retaining the data directory
14435        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14436                res.removedInfo, true, pkg)) {
14437            // If the existing package wasn't successfully deleted
14438            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14439            deletedPkg = false;
14440        } else {
14441            // Successfully deleted the old package; proceed with replace.
14442
14443            // If deleted package lived in a container, give users a chance to
14444            // relinquish resources before killing.
14445            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14446                if (DEBUG_INSTALL) {
14447                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14448                }
14449                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14450                final ArrayList<String> pkgList = new ArrayList<String>(1);
14451                pkgList.add(deletedPackage.applicationInfo.packageName);
14452                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14453            }
14454
14455            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14456                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14457            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14458
14459            try {
14460                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14461                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14462                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14463
14464                // Update the in-memory copy of the previous code paths.
14465                PackageSetting ps = mSettings.mPackages.get(pkgName);
14466                if (!killApp) {
14467                    if (ps.oldCodePaths == null) {
14468                        ps.oldCodePaths = new ArraySet<>();
14469                    }
14470                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14471                    if (deletedPackage.splitCodePaths != null) {
14472                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14473                    }
14474                } else {
14475                    ps.oldCodePaths = null;
14476                }
14477                if (ps.childPackageNames != null) {
14478                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14479                        final String childPkgName = ps.childPackageNames.get(i);
14480                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14481                        childPs.oldCodePaths = ps.oldCodePaths;
14482                    }
14483                }
14484                prepareAppDataAfterInstallLIF(newPackage);
14485                addedPkg = true;
14486            } catch (PackageManagerException e) {
14487                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14488            }
14489        }
14490
14491        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14492            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14493
14494            // Revert all internal state mutations and added folders for the failed install
14495            if (addedPkg) {
14496                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14497                        res.removedInfo, true, null);
14498            }
14499
14500            // Restore the old package
14501            if (deletedPkg) {
14502                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14503                File restoreFile = new File(deletedPackage.codePath);
14504                // Parse old package
14505                boolean oldExternal = isExternal(deletedPackage);
14506                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14507                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14508                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14509                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14510                try {
14511                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14512                            null);
14513                } catch (PackageManagerException e) {
14514                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14515                            + e.getMessage());
14516                    return;
14517                }
14518
14519                synchronized (mPackages) {
14520                    // Ensure the installer package name up to date
14521                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14522
14523                    // Update permissions for restored package
14524                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14525
14526                    mSettings.writeLPr();
14527                }
14528
14529                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14530            }
14531        } else {
14532            synchronized (mPackages) {
14533                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14534                if (ps != null) {
14535                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14536                    if (res.removedInfo.removedChildPackages != null) {
14537                        final int childCount = res.removedInfo.removedChildPackages.size();
14538                        // Iterate in reverse as we may modify the collection
14539                        for (int i = childCount - 1; i >= 0; i--) {
14540                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14541                            if (res.addedChildPackages.containsKey(childPackageName)) {
14542                                res.removedInfo.removedChildPackages.removeAt(i);
14543                            } else {
14544                                PackageRemovedInfo childInfo = res.removedInfo
14545                                        .removedChildPackages.valueAt(i);
14546                                childInfo.removedForAllUsers = mPackages.get(
14547                                        childInfo.removedPackage) == null;
14548                            }
14549                        }
14550                    }
14551                }
14552            }
14553        }
14554    }
14555
14556    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14557            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14558            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14559        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14560                + ", old=" + deletedPackage);
14561
14562        final boolean disabledSystem;
14563
14564        // Remove existing system package
14565        removePackageLI(deletedPackage, true);
14566
14567        synchronized (mPackages) {
14568            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14569        }
14570        if (!disabledSystem) {
14571            // We didn't need to disable the .apk as a current system package,
14572            // which means we are replacing another update that is already
14573            // installed.  We need to make sure to delete the older one's .apk.
14574            res.removedInfo.args = createInstallArgsForExisting(0,
14575                    deletedPackage.applicationInfo.getCodePath(),
14576                    deletedPackage.applicationInfo.getResourcePath(),
14577                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14578        } else {
14579            res.removedInfo.args = null;
14580        }
14581
14582        // Successfully disabled the old package. Now proceed with re-installation
14583        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14584                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14585        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14586
14587        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14588        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14589                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14590
14591        PackageParser.Package newPackage = null;
14592        try {
14593            // Add the package to the internal data structures
14594            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14595
14596            // Set the update and install times
14597            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14598            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14599                    System.currentTimeMillis());
14600
14601            // Update the package dynamic state if succeeded
14602            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14603                // Now that the install succeeded make sure we remove data
14604                // directories for any child package the update removed.
14605                final int deletedChildCount = (deletedPackage.childPackages != null)
14606                        ? deletedPackage.childPackages.size() : 0;
14607                final int newChildCount = (newPackage.childPackages != null)
14608                        ? newPackage.childPackages.size() : 0;
14609                for (int i = 0; i < deletedChildCount; i++) {
14610                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14611                    boolean childPackageDeleted = true;
14612                    for (int j = 0; j < newChildCount; j++) {
14613                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14614                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14615                            childPackageDeleted = false;
14616                            break;
14617                        }
14618                    }
14619                    if (childPackageDeleted) {
14620                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14621                                deletedChildPkg.packageName);
14622                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14623                            PackageRemovedInfo removedChildRes = res.removedInfo
14624                                    .removedChildPackages.get(deletedChildPkg.packageName);
14625                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14626                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14627                        }
14628                    }
14629                }
14630
14631                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14632                prepareAppDataAfterInstallLIF(newPackage);
14633            }
14634        } catch (PackageManagerException e) {
14635            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14636            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14637        }
14638
14639        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14640            // Re installation failed. Restore old information
14641            // Remove new pkg information
14642            if (newPackage != null) {
14643                removeInstalledPackageLI(newPackage, true);
14644            }
14645            // Add back the old system package
14646            try {
14647                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14648            } catch (PackageManagerException e) {
14649                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14650            }
14651
14652            synchronized (mPackages) {
14653                if (disabledSystem) {
14654                    enableSystemPackageLPw(deletedPackage);
14655                }
14656
14657                // Ensure the installer package name up to date
14658                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14659
14660                // Update permissions for restored package
14661                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14662
14663                mSettings.writeLPr();
14664            }
14665
14666            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14667                    + " after failed upgrade");
14668        }
14669    }
14670
14671    /**
14672     * Checks whether the parent or any of the child packages have a change shared
14673     * user. For a package to be a valid update the shred users of the parent and
14674     * the children should match. We may later support changing child shared users.
14675     * @param oldPkg The updated package.
14676     * @param newPkg The update package.
14677     * @return The shared user that change between the versions.
14678     */
14679    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14680            PackageParser.Package newPkg) {
14681        // Check parent shared user
14682        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14683            return newPkg.packageName;
14684        }
14685        // Check child shared users
14686        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14687        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14688        for (int i = 0; i < newChildCount; i++) {
14689            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14690            // If this child was present, did it have the same shared user?
14691            for (int j = 0; j < oldChildCount; j++) {
14692                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14693                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14694                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14695                    return newChildPkg.packageName;
14696                }
14697            }
14698        }
14699        return null;
14700    }
14701
14702    private void removeNativeBinariesLI(PackageSetting ps) {
14703        // Remove the lib path for the parent package
14704        if (ps != null) {
14705            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14706            // Remove the lib path for the child packages
14707            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14708            for (int i = 0; i < childCount; i++) {
14709                PackageSetting childPs = null;
14710                synchronized (mPackages) {
14711                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14712                }
14713                if (childPs != null) {
14714                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14715                            .legacyNativeLibraryPathString);
14716                }
14717            }
14718        }
14719    }
14720
14721    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14722        // Enable the parent package
14723        mSettings.enableSystemPackageLPw(pkg.packageName);
14724        // Enable the child packages
14725        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14726        for (int i = 0; i < childCount; i++) {
14727            PackageParser.Package childPkg = pkg.childPackages.get(i);
14728            mSettings.enableSystemPackageLPw(childPkg.packageName);
14729        }
14730    }
14731
14732    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14733            PackageParser.Package newPkg) {
14734        // Disable the parent package (parent always replaced)
14735        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14736        // Disable the child packages
14737        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14738        for (int i = 0; i < childCount; i++) {
14739            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14740            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14741            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14742        }
14743        return disabled;
14744    }
14745
14746    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14747            String installerPackageName) {
14748        // Enable the parent package
14749        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14750        // Enable the child packages
14751        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14752        for (int i = 0; i < childCount; i++) {
14753            PackageParser.Package childPkg = pkg.childPackages.get(i);
14754            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14755        }
14756    }
14757
14758    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14759        // Collect all used permissions in the UID
14760        ArraySet<String> usedPermissions = new ArraySet<>();
14761        final int packageCount = su.packages.size();
14762        for (int i = 0; i < packageCount; i++) {
14763            PackageSetting ps = su.packages.valueAt(i);
14764            if (ps.pkg == null) {
14765                continue;
14766            }
14767            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14768            for (int j = 0; j < requestedPermCount; j++) {
14769                String permission = ps.pkg.requestedPermissions.get(j);
14770                BasePermission bp = mSettings.mPermissions.get(permission);
14771                if (bp != null) {
14772                    usedPermissions.add(permission);
14773                }
14774            }
14775        }
14776
14777        PermissionsState permissionsState = su.getPermissionsState();
14778        // Prune install permissions
14779        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14780        final int installPermCount = installPermStates.size();
14781        for (int i = installPermCount - 1; i >= 0;  i--) {
14782            PermissionState permissionState = installPermStates.get(i);
14783            if (!usedPermissions.contains(permissionState.getName())) {
14784                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14785                if (bp != null) {
14786                    permissionsState.revokeInstallPermission(bp);
14787                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14788                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14789                }
14790            }
14791        }
14792
14793        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14794
14795        // Prune runtime permissions
14796        for (int userId : allUserIds) {
14797            List<PermissionState> runtimePermStates = permissionsState
14798                    .getRuntimePermissionStates(userId);
14799            final int runtimePermCount = runtimePermStates.size();
14800            for (int i = runtimePermCount - 1; i >= 0; i--) {
14801                PermissionState permissionState = runtimePermStates.get(i);
14802                if (!usedPermissions.contains(permissionState.getName())) {
14803                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14804                    if (bp != null) {
14805                        permissionsState.revokeRuntimePermission(bp, userId);
14806                        permissionsState.updatePermissionFlags(bp, userId,
14807                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14808                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14809                                runtimePermissionChangedUserIds, userId);
14810                    }
14811                }
14812            }
14813        }
14814
14815        return runtimePermissionChangedUserIds;
14816    }
14817
14818    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14819            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14820        // Update the parent package setting
14821        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14822                res, user);
14823        // Update the child packages setting
14824        final int childCount = (newPackage.childPackages != null)
14825                ? newPackage.childPackages.size() : 0;
14826        for (int i = 0; i < childCount; i++) {
14827            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14828            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14829            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14830                    childRes.origUsers, childRes, user);
14831        }
14832    }
14833
14834    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14835            String installerPackageName, int[] allUsers, int[] installedForUsers,
14836            PackageInstalledInfo res, UserHandle user) {
14837        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14838
14839        String pkgName = newPackage.packageName;
14840        synchronized (mPackages) {
14841            //write settings. the installStatus will be incomplete at this stage.
14842            //note that the new package setting would have already been
14843            //added to mPackages. It hasn't been persisted yet.
14844            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14845            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14846            mSettings.writeLPr();
14847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14848        }
14849
14850        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14851        synchronized (mPackages) {
14852            updatePermissionsLPw(newPackage.packageName, newPackage,
14853                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14854                            ? UPDATE_PERMISSIONS_ALL : 0));
14855            // For system-bundled packages, we assume that installing an upgraded version
14856            // of the package implies that the user actually wants to run that new code,
14857            // so we enable the package.
14858            PackageSetting ps = mSettings.mPackages.get(pkgName);
14859            final int userId = user.getIdentifier();
14860            if (ps != null) {
14861                if (isSystemApp(newPackage)) {
14862                    if (DEBUG_INSTALL) {
14863                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14864                    }
14865                    // Enable system package for requested users
14866                    if (res.origUsers != null) {
14867                        for (int origUserId : res.origUsers) {
14868                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14869                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14870                                        origUserId, installerPackageName);
14871                            }
14872                        }
14873                    }
14874                    // Also convey the prior install/uninstall state
14875                    if (allUsers != null && installedForUsers != null) {
14876                        for (int currentUserId : allUsers) {
14877                            final boolean installed = ArrayUtils.contains(
14878                                    installedForUsers, currentUserId);
14879                            if (DEBUG_INSTALL) {
14880                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14881                            }
14882                            ps.setInstalled(installed, currentUserId);
14883                        }
14884                        // these install state changes will be persisted in the
14885                        // upcoming call to mSettings.writeLPr().
14886                    }
14887                }
14888                // It's implied that when a user requests installation, they want the app to be
14889                // installed and enabled.
14890                if (userId != UserHandle.USER_ALL) {
14891                    ps.setInstalled(true, userId);
14892                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14893                }
14894            }
14895            res.name = pkgName;
14896            res.uid = newPackage.applicationInfo.uid;
14897            res.pkg = newPackage;
14898            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14899            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14900            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14901            //to update install status
14902            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14903            mSettings.writeLPr();
14904            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14905        }
14906
14907        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14908    }
14909
14910    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14911        try {
14912            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14913            installPackageLI(args, res);
14914        } finally {
14915            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14916        }
14917    }
14918
14919    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14920        final int installFlags = args.installFlags;
14921        final String installerPackageName = args.installerPackageName;
14922        final String volumeUuid = args.volumeUuid;
14923        final File tmpPackageFile = new File(args.getCodePath());
14924        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14925        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14926                || (args.volumeUuid != null));
14927        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14928        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14929        boolean replace = false;
14930        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14931        if (args.move != null) {
14932            // moving a complete application; perform an initial scan on the new install location
14933            scanFlags |= SCAN_INITIAL;
14934        }
14935        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14936            scanFlags |= SCAN_DONT_KILL_APP;
14937        }
14938
14939        // Result object to be returned
14940        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14941
14942        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14943
14944        // Sanity check
14945        if (ephemeral && (forwardLocked || onExternal)) {
14946            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14947                    + " external=" + onExternal);
14948            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14949            return;
14950        }
14951
14952        // Retrieve PackageSettings and parse package
14953        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14954                | PackageParser.PARSE_ENFORCE_CODE
14955                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14956                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14957                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14958                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14959        PackageParser pp = new PackageParser();
14960        pp.setSeparateProcesses(mSeparateProcesses);
14961        pp.setDisplayMetrics(mMetrics);
14962
14963        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14964        final PackageParser.Package pkg;
14965        try {
14966            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14967        } catch (PackageParserException e) {
14968            res.setError("Failed parse during installPackageLI", e);
14969            return;
14970        } finally {
14971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14972        }
14973
14974        // If we are installing a clustered package add results for the children
14975        if (pkg.childPackages != null) {
14976            synchronized (mPackages) {
14977                final int childCount = pkg.childPackages.size();
14978                for (int i = 0; i < childCount; i++) {
14979                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14980                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14981                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14982                    childRes.pkg = childPkg;
14983                    childRes.name = childPkg.packageName;
14984                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14985                    if (childPs != null) {
14986                        childRes.origUsers = childPs.queryInstalledUsers(
14987                                sUserManager.getUserIds(), true);
14988                    }
14989                    if ((mPackages.containsKey(childPkg.packageName))) {
14990                        childRes.removedInfo = new PackageRemovedInfo();
14991                        childRes.removedInfo.removedPackage = childPkg.packageName;
14992                    }
14993                    if (res.addedChildPackages == null) {
14994                        res.addedChildPackages = new ArrayMap<>();
14995                    }
14996                    res.addedChildPackages.put(childPkg.packageName, childRes);
14997                }
14998            }
14999        }
15000
15001        // If package doesn't declare API override, mark that we have an install
15002        // time CPU ABI override.
15003        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15004            pkg.cpuAbiOverride = args.abiOverride;
15005        }
15006
15007        String pkgName = res.name = pkg.packageName;
15008        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15009            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15010                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15011                return;
15012            }
15013        }
15014
15015        try {
15016            // either use what we've been given or parse directly from the APK
15017            if (args.certificates != null) {
15018                try {
15019                    PackageParser.populateCertificates(pkg, args.certificates);
15020                } catch (PackageParserException e) {
15021                    // there was something wrong with the certificates we were given;
15022                    // try to pull them from the APK
15023                    PackageParser.collectCertificates(pkg, parseFlags);
15024                }
15025            } else {
15026                PackageParser.collectCertificates(pkg, parseFlags);
15027            }
15028        } catch (PackageParserException e) {
15029            res.setError("Failed collect during installPackageLI", e);
15030            return;
15031        }
15032
15033        // Get rid of all references to package scan path via parser.
15034        pp = null;
15035        String oldCodePath = null;
15036        boolean systemApp = false;
15037        synchronized (mPackages) {
15038            // Check if installing already existing package
15039            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15040                String oldName = mSettings.mRenamedPackages.get(pkgName);
15041                if (pkg.mOriginalPackages != null
15042                        && pkg.mOriginalPackages.contains(oldName)
15043                        && mPackages.containsKey(oldName)) {
15044                    // This package is derived from an original package,
15045                    // and this device has been updating from that original
15046                    // name.  We must continue using the original name, so
15047                    // rename the new package here.
15048                    pkg.setPackageName(oldName);
15049                    pkgName = pkg.packageName;
15050                    replace = true;
15051                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15052                            + oldName + " pkgName=" + pkgName);
15053                } else if (mPackages.containsKey(pkgName)) {
15054                    // This package, under its official name, already exists
15055                    // on the device; we should replace it.
15056                    replace = true;
15057                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15058                }
15059
15060                // Child packages are installed through the parent package
15061                if (pkg.parentPackage != null) {
15062                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15063                            "Package " + pkg.packageName + " is child of package "
15064                                    + pkg.parentPackage.parentPackage + ". Child packages "
15065                                    + "can be updated only through the parent package.");
15066                    return;
15067                }
15068
15069                if (replace) {
15070                    // Prevent apps opting out from runtime permissions
15071                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15072                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15073                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15074                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15075                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15076                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15077                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15078                                        + " doesn't support runtime permissions but the old"
15079                                        + " target SDK " + oldTargetSdk + " does.");
15080                        return;
15081                    }
15082
15083                    // Prevent installing of child packages
15084                    if (oldPackage.parentPackage != null) {
15085                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15086                                "Package " + pkg.packageName + " is child of package "
15087                                        + oldPackage.parentPackage + ". Child packages "
15088                                        + "can be updated only through the parent package.");
15089                        return;
15090                    }
15091                }
15092            }
15093
15094            PackageSetting ps = mSettings.mPackages.get(pkgName);
15095            if (ps != null) {
15096                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15097
15098                // Quick sanity check that we're signed correctly if updating;
15099                // we'll check this again later when scanning, but we want to
15100                // bail early here before tripping over redefined permissions.
15101                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15102                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15103                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15104                                + pkg.packageName + " upgrade keys do not match the "
15105                                + "previously installed version");
15106                        return;
15107                    }
15108                } else {
15109                    try {
15110                        verifySignaturesLP(ps, pkg);
15111                    } catch (PackageManagerException e) {
15112                        res.setError(e.error, e.getMessage());
15113                        return;
15114                    }
15115                }
15116
15117                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15118                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15119                    systemApp = (ps.pkg.applicationInfo.flags &
15120                            ApplicationInfo.FLAG_SYSTEM) != 0;
15121                }
15122                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15123            }
15124
15125            // Check whether the newly-scanned package wants to define an already-defined perm
15126            int N = pkg.permissions.size();
15127            for (int i = N-1; i >= 0; i--) {
15128                PackageParser.Permission perm = pkg.permissions.get(i);
15129                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15130                if (bp != null) {
15131                    // If the defining package is signed with our cert, it's okay.  This
15132                    // also includes the "updating the same package" case, of course.
15133                    // "updating same package" could also involve key-rotation.
15134                    final boolean sigsOk;
15135                    if (bp.sourcePackage.equals(pkg.packageName)
15136                            && (bp.packageSetting instanceof PackageSetting)
15137                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15138                                    scanFlags))) {
15139                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15140                    } else {
15141                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15142                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15143                    }
15144                    if (!sigsOk) {
15145                        // If the owning package is the system itself, we log but allow
15146                        // install to proceed; we fail the install on all other permission
15147                        // redefinitions.
15148                        if (!bp.sourcePackage.equals("android")) {
15149                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15150                                    + pkg.packageName + " attempting to redeclare permission "
15151                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15152                            res.origPermission = perm.info.name;
15153                            res.origPackage = bp.sourcePackage;
15154                            return;
15155                        } else {
15156                            Slog.w(TAG, "Package " + pkg.packageName
15157                                    + " attempting to redeclare system permission "
15158                                    + perm.info.name + "; ignoring new declaration");
15159                            pkg.permissions.remove(i);
15160                        }
15161                    }
15162                }
15163            }
15164        }
15165
15166        if (systemApp) {
15167            if (onExternal) {
15168                // Abort update; system app can't be replaced with app on sdcard
15169                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15170                        "Cannot install updates to system apps on sdcard");
15171                return;
15172            } else if (ephemeral) {
15173                // Abort update; system app can't be replaced with an ephemeral app
15174                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15175                        "Cannot update a system app with an ephemeral app");
15176                return;
15177            }
15178        }
15179
15180        if (args.move != null) {
15181            // We did an in-place move, so dex is ready to roll
15182            scanFlags |= SCAN_NO_DEX;
15183            scanFlags |= SCAN_MOVE;
15184
15185            synchronized (mPackages) {
15186                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15187                if (ps == null) {
15188                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15189                            "Missing settings for moved package " + pkgName);
15190                }
15191
15192                // We moved the entire application as-is, so bring over the
15193                // previously derived ABI information.
15194                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15195                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15196            }
15197
15198        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15199            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15200            scanFlags |= SCAN_NO_DEX;
15201
15202            try {
15203                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15204                    args.abiOverride : pkg.cpuAbiOverride);
15205                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15206                        true /* extract libs */);
15207            } catch (PackageManagerException pme) {
15208                Slog.e(TAG, "Error deriving application ABI", pme);
15209                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15210                return;
15211            }
15212
15213            // Shared libraries for the package need to be updated.
15214            synchronized (mPackages) {
15215                try {
15216                    updateSharedLibrariesLPw(pkg, null);
15217                } catch (PackageManagerException e) {
15218                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15219                }
15220            }
15221            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15222            // Do not run PackageDexOptimizer through the local performDexOpt
15223            // method because `pkg` may not be in `mPackages` yet.
15224            //
15225            // Also, don't fail application installs if the dexopt step fails.
15226            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15227                    null /* instructionSets */, false /* checkProfiles */,
15228                    getCompilerFilterForReason(REASON_INSTALL));
15229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15230
15231            // Notify BackgroundDexOptService that the package has been changed.
15232            // If this is an update of a package which used to fail to compile,
15233            // BDOS will remove it from its blacklist.
15234            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15235        }
15236
15237        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15238            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15239            return;
15240        }
15241
15242        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15243
15244        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15245                "installPackageLI")) {
15246            if (replace) {
15247                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15248                        installerPackageName, res);
15249            } else {
15250                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15251                        args.user, installerPackageName, volumeUuid, res);
15252            }
15253        }
15254        synchronized (mPackages) {
15255            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15256            if (ps != null) {
15257                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15258            }
15259
15260            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15261            for (int i = 0; i < childCount; i++) {
15262                PackageParser.Package childPkg = pkg.childPackages.get(i);
15263                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15264                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15265                if (childPs != null) {
15266                    childRes.newUsers = childPs.queryInstalledUsers(
15267                            sUserManager.getUserIds(), true);
15268                }
15269            }
15270        }
15271    }
15272
15273    private void startIntentFilterVerifications(int userId, boolean replacing,
15274            PackageParser.Package pkg) {
15275        if (mIntentFilterVerifierComponent == null) {
15276            Slog.w(TAG, "No IntentFilter verification will not be done as "
15277                    + "there is no IntentFilterVerifier available!");
15278            return;
15279        }
15280
15281        final int verifierUid = getPackageUid(
15282                mIntentFilterVerifierComponent.getPackageName(),
15283                MATCH_DEBUG_TRIAGED_MISSING,
15284                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15285
15286        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15287        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15288        mHandler.sendMessage(msg);
15289
15290        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15291        for (int i = 0; i < childCount; i++) {
15292            PackageParser.Package childPkg = pkg.childPackages.get(i);
15293            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15294            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15295            mHandler.sendMessage(msg);
15296        }
15297    }
15298
15299    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15300            PackageParser.Package pkg) {
15301        int size = pkg.activities.size();
15302        if (size == 0) {
15303            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15304                    "No activity, so no need to verify any IntentFilter!");
15305            return;
15306        }
15307
15308        final boolean hasDomainURLs = hasDomainURLs(pkg);
15309        if (!hasDomainURLs) {
15310            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15311                    "No domain URLs, so no need to verify any IntentFilter!");
15312            return;
15313        }
15314
15315        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15316                + " if any IntentFilter from the " + size
15317                + " Activities needs verification ...");
15318
15319        int count = 0;
15320        final String packageName = pkg.packageName;
15321
15322        synchronized (mPackages) {
15323            // If this is a new install and we see that we've already run verification for this
15324            // package, we have nothing to do: it means the state was restored from backup.
15325            if (!replacing) {
15326                IntentFilterVerificationInfo ivi =
15327                        mSettings.getIntentFilterVerificationLPr(packageName);
15328                if (ivi != null) {
15329                    if (DEBUG_DOMAIN_VERIFICATION) {
15330                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15331                                + ivi.getStatusString());
15332                    }
15333                    return;
15334                }
15335            }
15336
15337            // If any filters need to be verified, then all need to be.
15338            boolean needToVerify = false;
15339            for (PackageParser.Activity a : pkg.activities) {
15340                for (ActivityIntentInfo filter : a.intents) {
15341                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15342                        if (DEBUG_DOMAIN_VERIFICATION) {
15343                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15344                        }
15345                        needToVerify = true;
15346                        break;
15347                    }
15348                }
15349            }
15350
15351            if (needToVerify) {
15352                final int verificationId = mIntentFilterVerificationToken++;
15353                for (PackageParser.Activity a : pkg.activities) {
15354                    for (ActivityIntentInfo filter : a.intents) {
15355                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15356                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15357                                    "Verification needed for IntentFilter:" + filter.toString());
15358                            mIntentFilterVerifier.addOneIntentFilterVerification(
15359                                    verifierUid, userId, verificationId, filter, packageName);
15360                            count++;
15361                        }
15362                    }
15363                }
15364            }
15365        }
15366
15367        if (count > 0) {
15368            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15369                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15370                    +  " for userId:" + userId);
15371            mIntentFilterVerifier.startVerifications(userId);
15372        } else {
15373            if (DEBUG_DOMAIN_VERIFICATION) {
15374                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15375            }
15376        }
15377    }
15378
15379    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15380        final ComponentName cn  = filter.activity.getComponentName();
15381        final String packageName = cn.getPackageName();
15382
15383        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15384                packageName);
15385        if (ivi == null) {
15386            return true;
15387        }
15388        int status = ivi.getStatus();
15389        switch (status) {
15390            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15391            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15392                return true;
15393
15394            default:
15395                // Nothing to do
15396                return false;
15397        }
15398    }
15399
15400    private static boolean isMultiArch(ApplicationInfo info) {
15401        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15402    }
15403
15404    private static boolean isExternal(PackageParser.Package pkg) {
15405        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15406    }
15407
15408    private static boolean isExternal(PackageSetting ps) {
15409        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15410    }
15411
15412    private static boolean isEphemeral(PackageParser.Package pkg) {
15413        return pkg.applicationInfo.isEphemeralApp();
15414    }
15415
15416    private static boolean isEphemeral(PackageSetting ps) {
15417        return ps.pkg != null && isEphemeral(ps.pkg);
15418    }
15419
15420    private static boolean isSystemApp(PackageParser.Package pkg) {
15421        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15422    }
15423
15424    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15425        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15426    }
15427
15428    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15429        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15430    }
15431
15432    private static boolean isSystemApp(PackageSetting ps) {
15433        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15434    }
15435
15436    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15437        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15438    }
15439
15440    private int packageFlagsToInstallFlags(PackageSetting ps) {
15441        int installFlags = 0;
15442        if (isEphemeral(ps)) {
15443            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15444        }
15445        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15446            // This existing package was an external ASEC install when we have
15447            // the external flag without a UUID
15448            installFlags |= PackageManager.INSTALL_EXTERNAL;
15449        }
15450        if (ps.isForwardLocked()) {
15451            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15452        }
15453        return installFlags;
15454    }
15455
15456    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15457        if (isExternal(pkg)) {
15458            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15459                return StorageManager.UUID_PRIMARY_PHYSICAL;
15460            } else {
15461                return pkg.volumeUuid;
15462            }
15463        } else {
15464            return StorageManager.UUID_PRIVATE_INTERNAL;
15465        }
15466    }
15467
15468    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15469        if (isExternal(pkg)) {
15470            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15471                return mSettings.getExternalVersion();
15472            } else {
15473                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15474            }
15475        } else {
15476            return mSettings.getInternalVersion();
15477        }
15478    }
15479
15480    private void deleteTempPackageFiles() {
15481        final FilenameFilter filter = new FilenameFilter() {
15482            public boolean accept(File dir, String name) {
15483                return name.startsWith("vmdl") && name.endsWith(".tmp");
15484            }
15485        };
15486        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15487            file.delete();
15488        }
15489    }
15490
15491    @Override
15492    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15493            int flags) {
15494        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15495                flags);
15496    }
15497
15498    @Override
15499    public void deletePackage(final String packageName,
15500            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15501        mContext.enforceCallingOrSelfPermission(
15502                android.Manifest.permission.DELETE_PACKAGES, null);
15503        Preconditions.checkNotNull(packageName);
15504        Preconditions.checkNotNull(observer);
15505        final int uid = Binder.getCallingUid();
15506        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15507        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15508        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15509            mContext.enforceCallingOrSelfPermission(
15510                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15511                    "deletePackage for user " + userId);
15512        }
15513
15514        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15515            try {
15516                observer.onPackageDeleted(packageName,
15517                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15518            } catch (RemoteException re) {
15519            }
15520            return;
15521        }
15522
15523        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15524            try {
15525                observer.onPackageDeleted(packageName,
15526                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15527            } catch (RemoteException re) {
15528            }
15529            return;
15530        }
15531
15532        if (DEBUG_REMOVE) {
15533            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15534                    + " deleteAllUsers: " + deleteAllUsers );
15535        }
15536        // Queue up an async operation since the package deletion may take a little while.
15537        mHandler.post(new Runnable() {
15538            public void run() {
15539                mHandler.removeCallbacks(this);
15540                int returnCode;
15541                if (!deleteAllUsers) {
15542                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15543                } else {
15544                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15545                    // If nobody is blocking uninstall, proceed with delete for all users
15546                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15547                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15548                    } else {
15549                        // Otherwise uninstall individually for users with blockUninstalls=false
15550                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15551                        for (int userId : users) {
15552                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15553                                returnCode = deletePackageX(packageName, userId, userFlags);
15554                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15555                                    Slog.w(TAG, "Package delete failed for user " + userId
15556                                            + ", returnCode " + returnCode);
15557                                }
15558                            }
15559                        }
15560                        // The app has only been marked uninstalled for certain users.
15561                        // We still need to report that delete was blocked
15562                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15563                    }
15564                }
15565                try {
15566                    observer.onPackageDeleted(packageName, returnCode, null);
15567                } catch (RemoteException e) {
15568                    Log.i(TAG, "Observer no longer exists.");
15569                } //end catch
15570            } //end run
15571        });
15572    }
15573
15574    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15575        int[] result = EMPTY_INT_ARRAY;
15576        for (int userId : userIds) {
15577            if (getBlockUninstallForUser(packageName, userId)) {
15578                result = ArrayUtils.appendInt(result, userId);
15579            }
15580        }
15581        return result;
15582    }
15583
15584    @Override
15585    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15586        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15587    }
15588
15589    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15590        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15591                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15592        try {
15593            if (dpm != null) {
15594                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15595                        /* callingUserOnly =*/ false);
15596                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15597                        : deviceOwnerComponentName.getPackageName();
15598                // Does the package contains the device owner?
15599                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15600                // this check is probably not needed, since DO should be registered as a device
15601                // admin on some user too. (Original bug for this: b/17657954)
15602                if (packageName.equals(deviceOwnerPackageName)) {
15603                    return true;
15604                }
15605                // Does it contain a device admin for any user?
15606                int[] users;
15607                if (userId == UserHandle.USER_ALL) {
15608                    users = sUserManager.getUserIds();
15609                } else {
15610                    users = new int[]{userId};
15611                }
15612                for (int i = 0; i < users.length; ++i) {
15613                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15614                        return true;
15615                    }
15616                }
15617            }
15618        } catch (RemoteException e) {
15619        }
15620        return false;
15621    }
15622
15623    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15624        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15625    }
15626
15627    /**
15628     *  This method is an internal method that could be get invoked either
15629     *  to delete an installed package or to clean up a failed installation.
15630     *  After deleting an installed package, a broadcast is sent to notify any
15631     *  listeners that the package has been removed. For cleaning up a failed
15632     *  installation, the broadcast is not necessary since the package's
15633     *  installation wouldn't have sent the initial broadcast either
15634     *  The key steps in deleting a package are
15635     *  deleting the package information in internal structures like mPackages,
15636     *  deleting the packages base directories through installd
15637     *  updating mSettings to reflect current status
15638     *  persisting settings for later use
15639     *  sending a broadcast if necessary
15640     */
15641    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15642        final PackageRemovedInfo info = new PackageRemovedInfo();
15643        final boolean res;
15644
15645        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15646                ? UserHandle.USER_ALL : userId;
15647
15648        if (isPackageDeviceAdmin(packageName, removeUser)) {
15649            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15650            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15651        }
15652
15653        PackageSetting uninstalledPs = null;
15654
15655        // for the uninstall-updates case and restricted profiles, remember the per-
15656        // user handle installed state
15657        int[] allUsers;
15658        synchronized (mPackages) {
15659            uninstalledPs = mSettings.mPackages.get(packageName);
15660            if (uninstalledPs == null) {
15661                Slog.w(TAG, "Not removing non-existent package " + packageName);
15662                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15663            }
15664            allUsers = sUserManager.getUserIds();
15665            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15666        }
15667
15668        final int freezeUser;
15669        if (isUpdatedSystemApp(uninstalledPs)
15670                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15671            // We're downgrading a system app, which will apply to all users, so
15672            // freeze them all during the downgrade
15673            freezeUser = UserHandle.USER_ALL;
15674        } else {
15675            freezeUser = removeUser;
15676        }
15677
15678        synchronized (mInstallLock) {
15679            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15680            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15681                    deleteFlags, "deletePackageX")) {
15682                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15683                        deleteFlags | REMOVE_CHATTY, info, true, null);
15684            }
15685            synchronized (mPackages) {
15686                if (res) {
15687                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15688                }
15689            }
15690        }
15691
15692        if (res) {
15693            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15694            info.sendPackageRemovedBroadcasts(killApp);
15695            info.sendSystemPackageUpdatedBroadcasts();
15696            info.sendSystemPackageAppearedBroadcasts();
15697        }
15698        // Force a gc here.
15699        Runtime.getRuntime().gc();
15700        // Delete the resources here after sending the broadcast to let
15701        // other processes clean up before deleting resources.
15702        if (info.args != null) {
15703            synchronized (mInstallLock) {
15704                info.args.doPostDeleteLI(true);
15705            }
15706        }
15707
15708        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15709    }
15710
15711    class PackageRemovedInfo {
15712        String removedPackage;
15713        int uid = -1;
15714        int removedAppId = -1;
15715        int[] origUsers;
15716        int[] removedUsers = null;
15717        boolean isRemovedPackageSystemUpdate = false;
15718        boolean isUpdate;
15719        boolean dataRemoved;
15720        boolean removedForAllUsers;
15721        // Clean up resources deleted packages.
15722        InstallArgs args = null;
15723        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15724        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15725
15726        void sendPackageRemovedBroadcasts(boolean killApp) {
15727            sendPackageRemovedBroadcastInternal(killApp);
15728            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15729            for (int i = 0; i < childCount; i++) {
15730                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15731                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15732            }
15733        }
15734
15735        void sendSystemPackageUpdatedBroadcasts() {
15736            if (isRemovedPackageSystemUpdate) {
15737                sendSystemPackageUpdatedBroadcastsInternal();
15738                final int childCount = (removedChildPackages != null)
15739                        ? removedChildPackages.size() : 0;
15740                for (int i = 0; i < childCount; i++) {
15741                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15742                    if (childInfo.isRemovedPackageSystemUpdate) {
15743                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15744                    }
15745                }
15746            }
15747        }
15748
15749        void sendSystemPackageAppearedBroadcasts() {
15750            final int packageCount = (appearedChildPackages != null)
15751                    ? appearedChildPackages.size() : 0;
15752            for (int i = 0; i < packageCount; i++) {
15753                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15754                for (int userId : installedInfo.newUsers) {
15755                    sendPackageAddedForUser(installedInfo.name, true,
15756                            UserHandle.getAppId(installedInfo.uid), userId);
15757                }
15758            }
15759        }
15760
15761        private void sendSystemPackageUpdatedBroadcastsInternal() {
15762            Bundle extras = new Bundle(2);
15763            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15764            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15765            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15766                    extras, 0, null, null, null);
15767            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15768                    extras, 0, null, null, null);
15769            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15770                    null, 0, removedPackage, null, null);
15771        }
15772
15773        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15774            Bundle extras = new Bundle(2);
15775            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15776            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15777            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15778            if (isUpdate || isRemovedPackageSystemUpdate) {
15779                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15780            }
15781            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15782            if (removedPackage != null) {
15783                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15784                        extras, 0, null, null, removedUsers);
15785                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15786                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15787                            removedPackage, extras, 0, null, null, removedUsers);
15788                }
15789            }
15790            if (removedAppId >= 0) {
15791                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15792                        removedUsers);
15793            }
15794        }
15795    }
15796
15797    /*
15798     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15799     * flag is not set, the data directory is removed as well.
15800     * make sure this flag is set for partially installed apps. If not its meaningless to
15801     * delete a partially installed application.
15802     */
15803    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15804            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15805        String packageName = ps.name;
15806        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15807        // Retrieve object to delete permissions for shared user later on
15808        final PackageParser.Package deletedPkg;
15809        final PackageSetting deletedPs;
15810        // reader
15811        synchronized (mPackages) {
15812            deletedPkg = mPackages.get(packageName);
15813            deletedPs = mSettings.mPackages.get(packageName);
15814            if (outInfo != null) {
15815                outInfo.removedPackage = packageName;
15816                outInfo.removedUsers = deletedPs != null
15817                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15818                        : null;
15819            }
15820        }
15821
15822        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15823
15824        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15825            final PackageParser.Package resolvedPkg;
15826            if (deletedPkg != null) {
15827                resolvedPkg = deletedPkg;
15828            } else {
15829                // We don't have a parsed package when it lives on an ejected
15830                // adopted storage device, so fake something together
15831                resolvedPkg = new PackageParser.Package(ps.name);
15832                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15833            }
15834            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15835                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15836            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15837            if (outInfo != null) {
15838                outInfo.dataRemoved = true;
15839            }
15840            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15841        }
15842
15843        // writer
15844        synchronized (mPackages) {
15845            if (deletedPs != null) {
15846                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15847                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15848                    clearDefaultBrowserIfNeeded(packageName);
15849                    if (outInfo != null) {
15850                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15851                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15852                    }
15853                    updatePermissionsLPw(deletedPs.name, null, 0);
15854                    if (deletedPs.sharedUser != null) {
15855                        // Remove permissions associated with package. Since runtime
15856                        // permissions are per user we have to kill the removed package
15857                        // or packages running under the shared user of the removed
15858                        // package if revoking the permissions requested only by the removed
15859                        // package is successful and this causes a change in gids.
15860                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15861                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15862                                    userId);
15863                            if (userIdToKill == UserHandle.USER_ALL
15864                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15865                                // If gids changed for this user, kill all affected packages.
15866                                mHandler.post(new Runnable() {
15867                                    @Override
15868                                    public void run() {
15869                                        // This has to happen with no lock held.
15870                                        killApplication(deletedPs.name, deletedPs.appId,
15871                                                KILL_APP_REASON_GIDS_CHANGED);
15872                                    }
15873                                });
15874                                break;
15875                            }
15876                        }
15877                    }
15878                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15879                }
15880                // make sure to preserve per-user disabled state if this removal was just
15881                // a downgrade of a system app to the factory package
15882                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15883                    if (DEBUG_REMOVE) {
15884                        Slog.d(TAG, "Propagating install state across downgrade");
15885                    }
15886                    for (int userId : allUserHandles) {
15887                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15888                        if (DEBUG_REMOVE) {
15889                            Slog.d(TAG, "    user " + userId + " => " + installed);
15890                        }
15891                        ps.setInstalled(installed, userId);
15892                    }
15893                }
15894            }
15895            // can downgrade to reader
15896            if (writeSettings) {
15897                // Save settings now
15898                mSettings.writeLPr();
15899            }
15900        }
15901        if (outInfo != null) {
15902            // A user ID was deleted here. Go through all users and remove it
15903            // from KeyStore.
15904            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15905        }
15906    }
15907
15908    static boolean locationIsPrivileged(File path) {
15909        try {
15910            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15911                    .getCanonicalPath();
15912            return path.getCanonicalPath().startsWith(privilegedAppDir);
15913        } catch (IOException e) {
15914            Slog.e(TAG, "Unable to access code path " + path);
15915        }
15916        return false;
15917    }
15918
15919    /*
15920     * Tries to delete system package.
15921     */
15922    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15923            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15924            boolean writeSettings) {
15925        if (deletedPs.parentPackageName != null) {
15926            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15927            return false;
15928        }
15929
15930        final boolean applyUserRestrictions
15931                = (allUserHandles != null) && (outInfo.origUsers != null);
15932        final PackageSetting disabledPs;
15933        // Confirm if the system package has been updated
15934        // An updated system app can be deleted. This will also have to restore
15935        // the system pkg from system partition
15936        // reader
15937        synchronized (mPackages) {
15938            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15939        }
15940
15941        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15942                + " disabledPs=" + disabledPs);
15943
15944        if (disabledPs == null) {
15945            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15946            return false;
15947        } else if (DEBUG_REMOVE) {
15948            Slog.d(TAG, "Deleting system pkg from data partition");
15949        }
15950
15951        if (DEBUG_REMOVE) {
15952            if (applyUserRestrictions) {
15953                Slog.d(TAG, "Remembering install states:");
15954                for (int userId : allUserHandles) {
15955                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15956                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15957                }
15958            }
15959        }
15960
15961        // Delete the updated package
15962        outInfo.isRemovedPackageSystemUpdate = true;
15963        if (outInfo.removedChildPackages != null) {
15964            final int childCount = (deletedPs.childPackageNames != null)
15965                    ? deletedPs.childPackageNames.size() : 0;
15966            for (int i = 0; i < childCount; i++) {
15967                String childPackageName = deletedPs.childPackageNames.get(i);
15968                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15969                        .contains(childPackageName)) {
15970                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15971                            childPackageName);
15972                    if (childInfo != null) {
15973                        childInfo.isRemovedPackageSystemUpdate = true;
15974                    }
15975                }
15976            }
15977        }
15978
15979        if (disabledPs.versionCode < deletedPs.versionCode) {
15980            // Delete data for downgrades
15981            flags &= ~PackageManager.DELETE_KEEP_DATA;
15982        } else {
15983            // Preserve data by setting flag
15984            flags |= PackageManager.DELETE_KEEP_DATA;
15985        }
15986
15987        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15988                outInfo, writeSettings, disabledPs.pkg);
15989        if (!ret) {
15990            return false;
15991        }
15992
15993        // writer
15994        synchronized (mPackages) {
15995            // Reinstate the old system package
15996            enableSystemPackageLPw(disabledPs.pkg);
15997            // Remove any native libraries from the upgraded package.
15998            removeNativeBinariesLI(deletedPs);
15999        }
16000
16001        // Install the system package
16002        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16003        int parseFlags = mDefParseFlags
16004                | PackageParser.PARSE_MUST_BE_APK
16005                | PackageParser.PARSE_IS_SYSTEM
16006                | PackageParser.PARSE_IS_SYSTEM_DIR;
16007        if (locationIsPrivileged(disabledPs.codePath)) {
16008            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16009        }
16010
16011        final PackageParser.Package newPkg;
16012        try {
16013            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16014        } catch (PackageManagerException e) {
16015            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16016                    + e.getMessage());
16017            return false;
16018        }
16019
16020        prepareAppDataAfterInstallLIF(newPkg);
16021
16022        // writer
16023        synchronized (mPackages) {
16024            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16025
16026            // Propagate the permissions state as we do not want to drop on the floor
16027            // runtime permissions. The update permissions method below will take
16028            // care of removing obsolete permissions and grant install permissions.
16029            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16030            updatePermissionsLPw(newPkg.packageName, newPkg,
16031                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16032
16033            if (applyUserRestrictions) {
16034                if (DEBUG_REMOVE) {
16035                    Slog.d(TAG, "Propagating install state across reinstall");
16036                }
16037                for (int userId : allUserHandles) {
16038                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16039                    if (DEBUG_REMOVE) {
16040                        Slog.d(TAG, "    user " + userId + " => " + installed);
16041                    }
16042                    ps.setInstalled(installed, userId);
16043
16044                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16045                }
16046                // Regardless of writeSettings we need to ensure that this restriction
16047                // state propagation is persisted
16048                mSettings.writeAllUsersPackageRestrictionsLPr();
16049            }
16050            // can downgrade to reader here
16051            if (writeSettings) {
16052                mSettings.writeLPr();
16053            }
16054        }
16055        return true;
16056    }
16057
16058    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16059            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16060            PackageRemovedInfo outInfo, boolean writeSettings,
16061            PackageParser.Package replacingPackage) {
16062        synchronized (mPackages) {
16063            if (outInfo != null) {
16064                outInfo.uid = ps.appId;
16065            }
16066
16067            if (outInfo != null && outInfo.removedChildPackages != null) {
16068                final int childCount = (ps.childPackageNames != null)
16069                        ? ps.childPackageNames.size() : 0;
16070                for (int i = 0; i < childCount; i++) {
16071                    String childPackageName = ps.childPackageNames.get(i);
16072                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16073                    if (childPs == null) {
16074                        return false;
16075                    }
16076                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16077                            childPackageName);
16078                    if (childInfo != null) {
16079                        childInfo.uid = childPs.appId;
16080                    }
16081                }
16082            }
16083        }
16084
16085        // Delete package data from internal structures and also remove data if flag is set
16086        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16087
16088        // Delete the child packages data
16089        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16090        for (int i = 0; i < childCount; i++) {
16091            PackageSetting childPs;
16092            synchronized (mPackages) {
16093                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16094            }
16095            if (childPs != null) {
16096                PackageRemovedInfo childOutInfo = (outInfo != null
16097                        && outInfo.removedChildPackages != null)
16098                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16099                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16100                        && (replacingPackage != null
16101                        && !replacingPackage.hasChildPackage(childPs.name))
16102                        ? flags & ~DELETE_KEEP_DATA : flags;
16103                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16104                        deleteFlags, writeSettings);
16105            }
16106        }
16107
16108        // Delete application code and resources only for parent packages
16109        if (ps.parentPackageName == null) {
16110            if (deleteCodeAndResources && (outInfo != null)) {
16111                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16112                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16113                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16114            }
16115        }
16116
16117        return true;
16118    }
16119
16120    @Override
16121    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16122            int userId) {
16123        mContext.enforceCallingOrSelfPermission(
16124                android.Manifest.permission.DELETE_PACKAGES, null);
16125        synchronized (mPackages) {
16126            PackageSetting ps = mSettings.mPackages.get(packageName);
16127            if (ps == null) {
16128                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16129                return false;
16130            }
16131            if (!ps.getInstalled(userId)) {
16132                // Can't block uninstall for an app that is not installed or enabled.
16133                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16134                return false;
16135            }
16136            ps.setBlockUninstall(blockUninstall, userId);
16137            mSettings.writePackageRestrictionsLPr(userId);
16138        }
16139        return true;
16140    }
16141
16142    @Override
16143    public boolean getBlockUninstallForUser(String packageName, int userId) {
16144        synchronized (mPackages) {
16145            PackageSetting ps = mSettings.mPackages.get(packageName);
16146            if (ps == null) {
16147                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16148                return false;
16149            }
16150            return ps.getBlockUninstall(userId);
16151        }
16152    }
16153
16154    @Override
16155    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16156        int callingUid = Binder.getCallingUid();
16157        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16158            throw new SecurityException(
16159                    "setRequiredForSystemUser can only be run by the system or root");
16160        }
16161        synchronized (mPackages) {
16162            PackageSetting ps = mSettings.mPackages.get(packageName);
16163            if (ps == null) {
16164                Log.w(TAG, "Package doesn't exist: " + packageName);
16165                return false;
16166            }
16167            if (systemUserApp) {
16168                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16169            } else {
16170                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16171            }
16172            mSettings.writeLPr();
16173        }
16174        return true;
16175    }
16176
16177    /*
16178     * This method handles package deletion in general
16179     */
16180    private boolean deletePackageLIF(String packageName, UserHandle user,
16181            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16182            PackageRemovedInfo outInfo, boolean writeSettings,
16183            PackageParser.Package replacingPackage) {
16184        if (packageName == null) {
16185            Slog.w(TAG, "Attempt to delete null packageName.");
16186            return false;
16187        }
16188
16189        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16190
16191        PackageSetting ps;
16192
16193        synchronized (mPackages) {
16194            ps = mSettings.mPackages.get(packageName);
16195            if (ps == null) {
16196                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16197                return false;
16198            }
16199
16200            if (ps.parentPackageName != null && (!isSystemApp(ps)
16201                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16202                if (DEBUG_REMOVE) {
16203                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16204                            + ((user == null) ? UserHandle.USER_ALL : user));
16205                }
16206                final int removedUserId = (user != null) ? user.getIdentifier()
16207                        : UserHandle.USER_ALL;
16208                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16209                    return false;
16210                }
16211                markPackageUninstalledForUserLPw(ps, user);
16212                scheduleWritePackageRestrictionsLocked(user);
16213                return true;
16214            }
16215        }
16216
16217        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16218                && user.getIdentifier() != UserHandle.USER_ALL)) {
16219            // The caller is asking that the package only be deleted for a single
16220            // user.  To do this, we just mark its uninstalled state and delete
16221            // its data. If this is a system app, we only allow this to happen if
16222            // they have set the special DELETE_SYSTEM_APP which requests different
16223            // semantics than normal for uninstalling system apps.
16224            markPackageUninstalledForUserLPw(ps, user);
16225
16226            if (!isSystemApp(ps)) {
16227                // Do not uninstall the APK if an app should be cached
16228                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16229                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16230                    // Other user still have this package installed, so all
16231                    // we need to do is clear this user's data and save that
16232                    // it is uninstalled.
16233                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16234                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16235                        return false;
16236                    }
16237                    scheduleWritePackageRestrictionsLocked(user);
16238                    return true;
16239                } else {
16240                    // We need to set it back to 'installed' so the uninstall
16241                    // broadcasts will be sent correctly.
16242                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16243                    ps.setInstalled(true, user.getIdentifier());
16244                }
16245            } else {
16246                // This is a system app, so we assume that the
16247                // other users still have this package installed, so all
16248                // we need to do is clear this user's data and save that
16249                // it is uninstalled.
16250                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16251                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16252                    return false;
16253                }
16254                scheduleWritePackageRestrictionsLocked(user);
16255                return true;
16256            }
16257        }
16258
16259        // If we are deleting a composite package for all users, keep track
16260        // of result for each child.
16261        if (ps.childPackageNames != null && outInfo != null) {
16262            synchronized (mPackages) {
16263                final int childCount = ps.childPackageNames.size();
16264                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16265                for (int i = 0; i < childCount; i++) {
16266                    String childPackageName = ps.childPackageNames.get(i);
16267                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16268                    childInfo.removedPackage = childPackageName;
16269                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16270                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16271                    if (childPs != null) {
16272                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16273                    }
16274                }
16275            }
16276        }
16277
16278        boolean ret = false;
16279        if (isSystemApp(ps)) {
16280            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16281            // When an updated system application is deleted we delete the existing resources
16282            // as well and fall back to existing code in system partition
16283            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16284        } else {
16285            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16286            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16287                    outInfo, writeSettings, replacingPackage);
16288        }
16289
16290        // Take a note whether we deleted the package for all users
16291        if (outInfo != null) {
16292            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16293            if (outInfo.removedChildPackages != null) {
16294                synchronized (mPackages) {
16295                    final int childCount = outInfo.removedChildPackages.size();
16296                    for (int i = 0; i < childCount; i++) {
16297                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16298                        if (childInfo != null) {
16299                            childInfo.removedForAllUsers = mPackages.get(
16300                                    childInfo.removedPackage) == null;
16301                        }
16302                    }
16303                }
16304            }
16305            // If we uninstalled an update to a system app there may be some
16306            // child packages that appeared as they are declared in the system
16307            // app but were not declared in the update.
16308            if (isSystemApp(ps)) {
16309                synchronized (mPackages) {
16310                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16311                    final int childCount = (updatedPs.childPackageNames != null)
16312                            ? updatedPs.childPackageNames.size() : 0;
16313                    for (int i = 0; i < childCount; i++) {
16314                        String childPackageName = updatedPs.childPackageNames.get(i);
16315                        if (outInfo.removedChildPackages == null
16316                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16317                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16318                            if (childPs == null) {
16319                                continue;
16320                            }
16321                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16322                            installRes.name = childPackageName;
16323                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16324                            installRes.pkg = mPackages.get(childPackageName);
16325                            installRes.uid = childPs.pkg.applicationInfo.uid;
16326                            if (outInfo.appearedChildPackages == null) {
16327                                outInfo.appearedChildPackages = new ArrayMap<>();
16328                            }
16329                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16330                        }
16331                    }
16332                }
16333            }
16334        }
16335
16336        return ret;
16337    }
16338
16339    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16340        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16341                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16342        for (int nextUserId : userIds) {
16343            if (DEBUG_REMOVE) {
16344                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16345            }
16346            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16347                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16348                    false /*hidden*/, false /*suspended*/, null, null, null,
16349                    false /*blockUninstall*/,
16350                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16351        }
16352    }
16353
16354    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16355            PackageRemovedInfo outInfo) {
16356        final PackageParser.Package pkg;
16357        synchronized (mPackages) {
16358            pkg = mPackages.get(ps.name);
16359        }
16360
16361        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16362                : new int[] {userId};
16363        for (int nextUserId : userIds) {
16364            if (DEBUG_REMOVE) {
16365                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16366                        + nextUserId);
16367            }
16368
16369            destroyAppDataLIF(pkg, userId,
16370                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16371            destroyAppProfilesLIF(pkg, userId);
16372            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16373            schedulePackageCleaning(ps.name, nextUserId, false);
16374            synchronized (mPackages) {
16375                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16376                    scheduleWritePackageRestrictionsLocked(nextUserId);
16377                }
16378                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16379            }
16380        }
16381
16382        if (outInfo != null) {
16383            outInfo.removedPackage = ps.name;
16384            outInfo.removedAppId = ps.appId;
16385            outInfo.removedUsers = userIds;
16386        }
16387
16388        return true;
16389    }
16390
16391    private final class ClearStorageConnection implements ServiceConnection {
16392        IMediaContainerService mContainerService;
16393
16394        @Override
16395        public void onServiceConnected(ComponentName name, IBinder service) {
16396            synchronized (this) {
16397                mContainerService = IMediaContainerService.Stub.asInterface(service);
16398                notifyAll();
16399            }
16400        }
16401
16402        @Override
16403        public void onServiceDisconnected(ComponentName name) {
16404        }
16405    }
16406
16407    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16408        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16409
16410        final boolean mounted;
16411        if (Environment.isExternalStorageEmulated()) {
16412            mounted = true;
16413        } else {
16414            final String status = Environment.getExternalStorageState();
16415
16416            mounted = status.equals(Environment.MEDIA_MOUNTED)
16417                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16418        }
16419
16420        if (!mounted) {
16421            return;
16422        }
16423
16424        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16425        int[] users;
16426        if (userId == UserHandle.USER_ALL) {
16427            users = sUserManager.getUserIds();
16428        } else {
16429            users = new int[] { userId };
16430        }
16431        final ClearStorageConnection conn = new ClearStorageConnection();
16432        if (mContext.bindServiceAsUser(
16433                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16434            try {
16435                for (int curUser : users) {
16436                    long timeout = SystemClock.uptimeMillis() + 5000;
16437                    synchronized (conn) {
16438                        long now;
16439                        while (conn.mContainerService == null &&
16440                                (now = SystemClock.uptimeMillis()) < timeout) {
16441                            try {
16442                                conn.wait(timeout - now);
16443                            } catch (InterruptedException e) {
16444                            }
16445                        }
16446                    }
16447                    if (conn.mContainerService == null) {
16448                        return;
16449                    }
16450
16451                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16452                    clearDirectory(conn.mContainerService,
16453                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16454                    if (allData) {
16455                        clearDirectory(conn.mContainerService,
16456                                userEnv.buildExternalStorageAppDataDirs(packageName));
16457                        clearDirectory(conn.mContainerService,
16458                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16459                    }
16460                }
16461            } finally {
16462                mContext.unbindService(conn);
16463            }
16464        }
16465    }
16466
16467    @Override
16468    public void clearApplicationProfileData(String packageName) {
16469        enforceSystemOrRoot("Only the system can clear all profile data");
16470
16471        final PackageParser.Package pkg;
16472        synchronized (mPackages) {
16473            pkg = mPackages.get(packageName);
16474        }
16475
16476        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16477            synchronized (mInstallLock) {
16478                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16479                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16480                        true /* removeBaseMarker */);
16481            }
16482        }
16483    }
16484
16485    @Override
16486    public void clearApplicationUserData(final String packageName,
16487            final IPackageDataObserver observer, final int userId) {
16488        mContext.enforceCallingOrSelfPermission(
16489                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16490
16491        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16492                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16493
16494        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16495            throw new SecurityException("Cannot clear data for a protected package: "
16496                    + packageName);
16497        }
16498        // Queue up an async operation since the package deletion may take a little while.
16499        mHandler.post(new Runnable() {
16500            public void run() {
16501                mHandler.removeCallbacks(this);
16502                final boolean succeeded;
16503                try (PackageFreezer freezer = freezePackage(packageName,
16504                        "clearApplicationUserData")) {
16505                    synchronized (mInstallLock) {
16506                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16507                    }
16508                    clearExternalStorageDataSync(packageName, userId, true);
16509                }
16510                if (succeeded) {
16511                    // invoke DeviceStorageMonitor's update method to clear any notifications
16512                    DeviceStorageMonitorInternal dsm = LocalServices
16513                            .getService(DeviceStorageMonitorInternal.class);
16514                    if (dsm != null) {
16515                        dsm.checkMemory();
16516                    }
16517                }
16518                if(observer != null) {
16519                    try {
16520                        observer.onRemoveCompleted(packageName, succeeded);
16521                    } catch (RemoteException e) {
16522                        Log.i(TAG, "Observer no longer exists.");
16523                    }
16524                } //end if observer
16525            } //end run
16526        });
16527    }
16528
16529    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16530        if (packageName == null) {
16531            Slog.w(TAG, "Attempt to delete null packageName.");
16532            return false;
16533        }
16534
16535        // Try finding details about the requested package
16536        PackageParser.Package pkg;
16537        synchronized (mPackages) {
16538            pkg = mPackages.get(packageName);
16539            if (pkg == null) {
16540                final PackageSetting ps = mSettings.mPackages.get(packageName);
16541                if (ps != null) {
16542                    pkg = ps.pkg;
16543                }
16544            }
16545
16546            if (pkg == null) {
16547                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16548                return false;
16549            }
16550
16551            PackageSetting ps = (PackageSetting) pkg.mExtras;
16552            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16553        }
16554
16555        clearAppDataLIF(pkg, userId,
16556                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16557
16558        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16559        removeKeystoreDataIfNeeded(userId, appId);
16560
16561        UserManagerInternal umInternal = getUserManagerInternal();
16562        final int flags;
16563        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16564            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16565        } else if (umInternal.isUserRunning(userId)) {
16566            flags = StorageManager.FLAG_STORAGE_DE;
16567        } else {
16568            flags = 0;
16569        }
16570        prepareAppDataContentsLIF(pkg, userId, flags);
16571
16572        return true;
16573    }
16574
16575    /**
16576     * Reverts user permission state changes (permissions and flags) in
16577     * all packages for a given user.
16578     *
16579     * @param userId The device user for which to do a reset.
16580     */
16581    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16582        final int packageCount = mPackages.size();
16583        for (int i = 0; i < packageCount; i++) {
16584            PackageParser.Package pkg = mPackages.valueAt(i);
16585            PackageSetting ps = (PackageSetting) pkg.mExtras;
16586            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16587        }
16588    }
16589
16590    private void resetNetworkPolicies(int userId) {
16591        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16592    }
16593
16594    /**
16595     * Reverts user permission state changes (permissions and flags).
16596     *
16597     * @param ps The package for which to reset.
16598     * @param userId The device user for which to do a reset.
16599     */
16600    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16601            final PackageSetting ps, final int userId) {
16602        if (ps.pkg == null) {
16603            return;
16604        }
16605
16606        // These are flags that can change base on user actions.
16607        final int userSettableMask = FLAG_PERMISSION_USER_SET
16608                | FLAG_PERMISSION_USER_FIXED
16609                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16610                | FLAG_PERMISSION_REVIEW_REQUIRED;
16611
16612        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16613                | FLAG_PERMISSION_POLICY_FIXED;
16614
16615        boolean writeInstallPermissions = false;
16616        boolean writeRuntimePermissions = false;
16617
16618        final int permissionCount = ps.pkg.requestedPermissions.size();
16619        for (int i = 0; i < permissionCount; i++) {
16620            String permission = ps.pkg.requestedPermissions.get(i);
16621
16622            BasePermission bp = mSettings.mPermissions.get(permission);
16623            if (bp == null) {
16624                continue;
16625            }
16626
16627            // If shared user we just reset the state to which only this app contributed.
16628            if (ps.sharedUser != null) {
16629                boolean used = false;
16630                final int packageCount = ps.sharedUser.packages.size();
16631                for (int j = 0; j < packageCount; j++) {
16632                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16633                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16634                            && pkg.pkg.requestedPermissions.contains(permission)) {
16635                        used = true;
16636                        break;
16637                    }
16638                }
16639                if (used) {
16640                    continue;
16641                }
16642            }
16643
16644            PermissionsState permissionsState = ps.getPermissionsState();
16645
16646            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16647
16648            // Always clear the user settable flags.
16649            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16650                    bp.name) != null;
16651            // If permission review is enabled and this is a legacy app, mark the
16652            // permission as requiring a review as this is the initial state.
16653            int flags = 0;
16654            if (Build.PERMISSIONS_REVIEW_REQUIRED
16655                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16656                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16657            }
16658            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16659                if (hasInstallState) {
16660                    writeInstallPermissions = true;
16661                } else {
16662                    writeRuntimePermissions = true;
16663                }
16664            }
16665
16666            // Below is only runtime permission handling.
16667            if (!bp.isRuntime()) {
16668                continue;
16669            }
16670
16671            // Never clobber system or policy.
16672            if ((oldFlags & policyOrSystemFlags) != 0) {
16673                continue;
16674            }
16675
16676            // If this permission was granted by default, make sure it is.
16677            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16678                if (permissionsState.grantRuntimePermission(bp, userId)
16679                        != PERMISSION_OPERATION_FAILURE) {
16680                    writeRuntimePermissions = true;
16681                }
16682            // If permission review is enabled the permissions for a legacy apps
16683            // are represented as constantly granted runtime ones, so don't revoke.
16684            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16685                // Otherwise, reset the permission.
16686                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16687                switch (revokeResult) {
16688                    case PERMISSION_OPERATION_SUCCESS:
16689                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16690                        writeRuntimePermissions = true;
16691                        final int appId = ps.appId;
16692                        mHandler.post(new Runnable() {
16693                            @Override
16694                            public void run() {
16695                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16696                            }
16697                        });
16698                    } break;
16699                }
16700            }
16701        }
16702
16703        // Synchronously write as we are taking permissions away.
16704        if (writeRuntimePermissions) {
16705            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16706        }
16707
16708        // Synchronously write as we are taking permissions away.
16709        if (writeInstallPermissions) {
16710            mSettings.writeLPr();
16711        }
16712    }
16713
16714    /**
16715     * Remove entries from the keystore daemon. Will only remove it if the
16716     * {@code appId} is valid.
16717     */
16718    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16719        if (appId < 0) {
16720            return;
16721        }
16722
16723        final KeyStore keyStore = KeyStore.getInstance();
16724        if (keyStore != null) {
16725            if (userId == UserHandle.USER_ALL) {
16726                for (final int individual : sUserManager.getUserIds()) {
16727                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16728                }
16729            } else {
16730                keyStore.clearUid(UserHandle.getUid(userId, appId));
16731            }
16732        } else {
16733            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16734        }
16735    }
16736
16737    @Override
16738    public void deleteApplicationCacheFiles(final String packageName,
16739            final IPackageDataObserver observer) {
16740        final int userId = UserHandle.getCallingUserId();
16741        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16742    }
16743
16744    @Override
16745    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16746            final IPackageDataObserver observer) {
16747        mContext.enforceCallingOrSelfPermission(
16748                android.Manifest.permission.DELETE_CACHE_FILES, null);
16749        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16750                /* requireFullPermission= */ true, /* checkShell= */ false,
16751                "delete application cache files");
16752
16753        final PackageParser.Package pkg;
16754        synchronized (mPackages) {
16755            pkg = mPackages.get(packageName);
16756        }
16757
16758        // Queue up an async operation since the package deletion may take a little while.
16759        mHandler.post(new Runnable() {
16760            public void run() {
16761                synchronized (mInstallLock) {
16762                    final int flags = StorageManager.FLAG_STORAGE_DE
16763                            | StorageManager.FLAG_STORAGE_CE;
16764                    // We're only clearing cache files, so we don't care if the
16765                    // app is unfrozen and still able to run
16766                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16767                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16768                }
16769                clearExternalStorageDataSync(packageName, userId, false);
16770                if (observer != null) {
16771                    try {
16772                        observer.onRemoveCompleted(packageName, true);
16773                    } catch (RemoteException e) {
16774                        Log.i(TAG, "Observer no longer exists.");
16775                    }
16776                }
16777            }
16778        });
16779    }
16780
16781    @Override
16782    public void getPackageSizeInfo(final String packageName, int userHandle,
16783            final IPackageStatsObserver observer) {
16784        mContext.enforceCallingOrSelfPermission(
16785                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16786        if (packageName == null) {
16787            throw new IllegalArgumentException("Attempt to get size of null packageName");
16788        }
16789
16790        PackageStats stats = new PackageStats(packageName, userHandle);
16791
16792        /*
16793         * Queue up an async operation since the package measurement may take a
16794         * little while.
16795         */
16796        Message msg = mHandler.obtainMessage(INIT_COPY);
16797        msg.obj = new MeasureParams(stats, observer);
16798        mHandler.sendMessage(msg);
16799    }
16800
16801    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16802        final PackageSetting ps;
16803        synchronized (mPackages) {
16804            ps = mSettings.mPackages.get(packageName);
16805            if (ps == null) {
16806                Slog.w(TAG, "Failed to find settings for " + packageName);
16807                return false;
16808            }
16809        }
16810        try {
16811            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16812                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16813                    ps.getCeDataInode(userId), ps.codePathString, stats);
16814        } catch (InstallerException e) {
16815            Slog.w(TAG, String.valueOf(e));
16816            return false;
16817        }
16818
16819        // For now, ignore code size of packages on system partition
16820        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16821            stats.codeSize = 0;
16822        }
16823
16824        return true;
16825    }
16826
16827    private int getUidTargetSdkVersionLockedLPr(int uid) {
16828        Object obj = mSettings.getUserIdLPr(uid);
16829        if (obj instanceof SharedUserSetting) {
16830            final SharedUserSetting sus = (SharedUserSetting) obj;
16831            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16832            final Iterator<PackageSetting> it = sus.packages.iterator();
16833            while (it.hasNext()) {
16834                final PackageSetting ps = it.next();
16835                if (ps.pkg != null) {
16836                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16837                    if (v < vers) vers = v;
16838                }
16839            }
16840            return vers;
16841        } else if (obj instanceof PackageSetting) {
16842            final PackageSetting ps = (PackageSetting) obj;
16843            if (ps.pkg != null) {
16844                return ps.pkg.applicationInfo.targetSdkVersion;
16845            }
16846        }
16847        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16848    }
16849
16850    @Override
16851    public void addPreferredActivity(IntentFilter filter, int match,
16852            ComponentName[] set, ComponentName activity, int userId) {
16853        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16854                "Adding preferred");
16855    }
16856
16857    private void addPreferredActivityInternal(IntentFilter filter, int match,
16858            ComponentName[] set, ComponentName activity, boolean always, int userId,
16859            String opname) {
16860        // writer
16861        int callingUid = Binder.getCallingUid();
16862        enforceCrossUserPermission(callingUid, userId,
16863                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16864        if (filter.countActions() == 0) {
16865            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16866            return;
16867        }
16868        synchronized (mPackages) {
16869            if (mContext.checkCallingOrSelfPermission(
16870                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16871                    != PackageManager.PERMISSION_GRANTED) {
16872                if (getUidTargetSdkVersionLockedLPr(callingUid)
16873                        < Build.VERSION_CODES.FROYO) {
16874                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16875                            + callingUid);
16876                    return;
16877                }
16878                mContext.enforceCallingOrSelfPermission(
16879                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16880            }
16881
16882            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16883            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16884                    + userId + ":");
16885            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16886            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16887            scheduleWritePackageRestrictionsLocked(userId);
16888        }
16889    }
16890
16891    @Override
16892    public void replacePreferredActivity(IntentFilter filter, int match,
16893            ComponentName[] set, ComponentName activity, int userId) {
16894        if (filter.countActions() != 1) {
16895            throw new IllegalArgumentException(
16896                    "replacePreferredActivity expects filter to have only 1 action.");
16897        }
16898        if (filter.countDataAuthorities() != 0
16899                || filter.countDataPaths() != 0
16900                || filter.countDataSchemes() > 1
16901                || filter.countDataTypes() != 0) {
16902            throw new IllegalArgumentException(
16903                    "replacePreferredActivity expects filter to have no data authorities, " +
16904                    "paths, or types; and at most one scheme.");
16905        }
16906
16907        final int callingUid = Binder.getCallingUid();
16908        enforceCrossUserPermission(callingUid, userId,
16909                true /* requireFullPermission */, false /* checkShell */,
16910                "replace preferred activity");
16911        synchronized (mPackages) {
16912            if (mContext.checkCallingOrSelfPermission(
16913                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16914                    != PackageManager.PERMISSION_GRANTED) {
16915                if (getUidTargetSdkVersionLockedLPr(callingUid)
16916                        < Build.VERSION_CODES.FROYO) {
16917                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16918                            + Binder.getCallingUid());
16919                    return;
16920                }
16921                mContext.enforceCallingOrSelfPermission(
16922                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16923            }
16924
16925            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16926            if (pir != null) {
16927                // Get all of the existing entries that exactly match this filter.
16928                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16929                if (existing != null && existing.size() == 1) {
16930                    PreferredActivity cur = existing.get(0);
16931                    if (DEBUG_PREFERRED) {
16932                        Slog.i(TAG, "Checking replace of preferred:");
16933                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16934                        if (!cur.mPref.mAlways) {
16935                            Slog.i(TAG, "  -- CUR; not mAlways!");
16936                        } else {
16937                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16938                            Slog.i(TAG, "  -- CUR: mSet="
16939                                    + Arrays.toString(cur.mPref.mSetComponents));
16940                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16941                            Slog.i(TAG, "  -- NEW: mMatch="
16942                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16943                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16944                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16945                        }
16946                    }
16947                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16948                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16949                            && cur.mPref.sameSet(set)) {
16950                        // Setting the preferred activity to what it happens to be already
16951                        if (DEBUG_PREFERRED) {
16952                            Slog.i(TAG, "Replacing with same preferred activity "
16953                                    + cur.mPref.mShortComponent + " for user "
16954                                    + userId + ":");
16955                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16956                        }
16957                        return;
16958                    }
16959                }
16960
16961                if (existing != null) {
16962                    if (DEBUG_PREFERRED) {
16963                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16964                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16965                    }
16966                    for (int i = 0; i < existing.size(); i++) {
16967                        PreferredActivity pa = existing.get(i);
16968                        if (DEBUG_PREFERRED) {
16969                            Slog.i(TAG, "Removing existing preferred activity "
16970                                    + pa.mPref.mComponent + ":");
16971                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16972                        }
16973                        pir.removeFilter(pa);
16974                    }
16975                }
16976            }
16977            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16978                    "Replacing preferred");
16979        }
16980    }
16981
16982    @Override
16983    public void clearPackagePreferredActivities(String packageName) {
16984        final int uid = Binder.getCallingUid();
16985        // writer
16986        synchronized (mPackages) {
16987            PackageParser.Package pkg = mPackages.get(packageName);
16988            if (pkg == null || pkg.applicationInfo.uid != uid) {
16989                if (mContext.checkCallingOrSelfPermission(
16990                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16991                        != PackageManager.PERMISSION_GRANTED) {
16992                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16993                            < Build.VERSION_CODES.FROYO) {
16994                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16995                                + Binder.getCallingUid());
16996                        return;
16997                    }
16998                    mContext.enforceCallingOrSelfPermission(
16999                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17000                }
17001            }
17002
17003            int user = UserHandle.getCallingUserId();
17004            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17005                scheduleWritePackageRestrictionsLocked(user);
17006            }
17007        }
17008    }
17009
17010    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17011    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17012        ArrayList<PreferredActivity> removed = null;
17013        boolean changed = false;
17014        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17015            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17016            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17017            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17018                continue;
17019            }
17020            Iterator<PreferredActivity> it = pir.filterIterator();
17021            while (it.hasNext()) {
17022                PreferredActivity pa = it.next();
17023                // Mark entry for removal only if it matches the package name
17024                // and the entry is of type "always".
17025                if (packageName == null ||
17026                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17027                                && pa.mPref.mAlways)) {
17028                    if (removed == null) {
17029                        removed = new ArrayList<PreferredActivity>();
17030                    }
17031                    removed.add(pa);
17032                }
17033            }
17034            if (removed != null) {
17035                for (int j=0; j<removed.size(); j++) {
17036                    PreferredActivity pa = removed.get(j);
17037                    pir.removeFilter(pa);
17038                }
17039                changed = true;
17040            }
17041        }
17042        return changed;
17043    }
17044
17045    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17046    private void clearIntentFilterVerificationsLPw(int userId) {
17047        final int packageCount = mPackages.size();
17048        for (int i = 0; i < packageCount; i++) {
17049            PackageParser.Package pkg = mPackages.valueAt(i);
17050            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17051        }
17052    }
17053
17054    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17055    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17056        if (userId == UserHandle.USER_ALL) {
17057            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17058                    sUserManager.getUserIds())) {
17059                for (int oneUserId : sUserManager.getUserIds()) {
17060                    scheduleWritePackageRestrictionsLocked(oneUserId);
17061                }
17062            }
17063        } else {
17064            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17065                scheduleWritePackageRestrictionsLocked(userId);
17066            }
17067        }
17068    }
17069
17070    void clearDefaultBrowserIfNeeded(String packageName) {
17071        for (int oneUserId : sUserManager.getUserIds()) {
17072            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17073            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17074            if (packageName.equals(defaultBrowserPackageName)) {
17075                setDefaultBrowserPackageName(null, oneUserId);
17076            }
17077        }
17078    }
17079
17080    @Override
17081    public void resetApplicationPreferences(int userId) {
17082        mContext.enforceCallingOrSelfPermission(
17083                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17084        final long identity = Binder.clearCallingIdentity();
17085        // writer
17086        try {
17087            synchronized (mPackages) {
17088                clearPackagePreferredActivitiesLPw(null, userId);
17089                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17090                // TODO: We have to reset the default SMS and Phone. This requires
17091                // significant refactoring to keep all default apps in the package
17092                // manager (cleaner but more work) or have the services provide
17093                // callbacks to the package manager to request a default app reset.
17094                applyFactoryDefaultBrowserLPw(userId);
17095                clearIntentFilterVerificationsLPw(userId);
17096                primeDomainVerificationsLPw(userId);
17097                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17098                scheduleWritePackageRestrictionsLocked(userId);
17099            }
17100            resetNetworkPolicies(userId);
17101        } finally {
17102            Binder.restoreCallingIdentity(identity);
17103        }
17104    }
17105
17106    @Override
17107    public int getPreferredActivities(List<IntentFilter> outFilters,
17108            List<ComponentName> outActivities, String packageName) {
17109
17110        int num = 0;
17111        final int userId = UserHandle.getCallingUserId();
17112        // reader
17113        synchronized (mPackages) {
17114            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17115            if (pir != null) {
17116                final Iterator<PreferredActivity> it = pir.filterIterator();
17117                while (it.hasNext()) {
17118                    final PreferredActivity pa = it.next();
17119                    if (packageName == null
17120                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17121                                    && pa.mPref.mAlways)) {
17122                        if (outFilters != null) {
17123                            outFilters.add(new IntentFilter(pa));
17124                        }
17125                        if (outActivities != null) {
17126                            outActivities.add(pa.mPref.mComponent);
17127                        }
17128                    }
17129                }
17130            }
17131        }
17132
17133        return num;
17134    }
17135
17136    @Override
17137    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17138            int userId) {
17139        int callingUid = Binder.getCallingUid();
17140        if (callingUid != Process.SYSTEM_UID) {
17141            throw new SecurityException(
17142                    "addPersistentPreferredActivity can only be run by the system");
17143        }
17144        if (filter.countActions() == 0) {
17145            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17146            return;
17147        }
17148        synchronized (mPackages) {
17149            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17150                    ":");
17151            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17152            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17153                    new PersistentPreferredActivity(filter, activity));
17154            scheduleWritePackageRestrictionsLocked(userId);
17155        }
17156    }
17157
17158    @Override
17159    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17160        int callingUid = Binder.getCallingUid();
17161        if (callingUid != Process.SYSTEM_UID) {
17162            throw new SecurityException(
17163                    "clearPackagePersistentPreferredActivities can only be run by the system");
17164        }
17165        ArrayList<PersistentPreferredActivity> removed = null;
17166        boolean changed = false;
17167        synchronized (mPackages) {
17168            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17169                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17170                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17171                        .valueAt(i);
17172                if (userId != thisUserId) {
17173                    continue;
17174                }
17175                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17176                while (it.hasNext()) {
17177                    PersistentPreferredActivity ppa = it.next();
17178                    // Mark entry for removal only if it matches the package name.
17179                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17180                        if (removed == null) {
17181                            removed = new ArrayList<PersistentPreferredActivity>();
17182                        }
17183                        removed.add(ppa);
17184                    }
17185                }
17186                if (removed != null) {
17187                    for (int j=0; j<removed.size(); j++) {
17188                        PersistentPreferredActivity ppa = removed.get(j);
17189                        ppir.removeFilter(ppa);
17190                    }
17191                    changed = true;
17192                }
17193            }
17194
17195            if (changed) {
17196                scheduleWritePackageRestrictionsLocked(userId);
17197            }
17198        }
17199    }
17200
17201    /**
17202     * Common machinery for picking apart a restored XML blob and passing
17203     * it to a caller-supplied functor to be applied to the running system.
17204     */
17205    private void restoreFromXml(XmlPullParser parser, int userId,
17206            String expectedStartTag, BlobXmlRestorer functor)
17207            throws IOException, XmlPullParserException {
17208        int type;
17209        while ((type = parser.next()) != XmlPullParser.START_TAG
17210                && type != XmlPullParser.END_DOCUMENT) {
17211        }
17212        if (type != XmlPullParser.START_TAG) {
17213            // oops didn't find a start tag?!
17214            if (DEBUG_BACKUP) {
17215                Slog.e(TAG, "Didn't find start tag during restore");
17216            }
17217            return;
17218        }
17219Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17220        // this is supposed to be TAG_PREFERRED_BACKUP
17221        if (!expectedStartTag.equals(parser.getName())) {
17222            if (DEBUG_BACKUP) {
17223                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17224            }
17225            return;
17226        }
17227
17228        // skip interfering stuff, then we're aligned with the backing implementation
17229        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17230Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17231        functor.apply(parser, userId);
17232    }
17233
17234    private interface BlobXmlRestorer {
17235        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17236    }
17237
17238    /**
17239     * Non-Binder method, support for the backup/restore mechanism: write the
17240     * full set of preferred activities in its canonical XML format.  Returns the
17241     * XML output as a byte array, or null if there is none.
17242     */
17243    @Override
17244    public byte[] getPreferredActivityBackup(int userId) {
17245        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17246            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17247        }
17248
17249        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17250        try {
17251            final XmlSerializer serializer = new FastXmlSerializer();
17252            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17253            serializer.startDocument(null, true);
17254            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17255
17256            synchronized (mPackages) {
17257                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17258            }
17259
17260            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17261            serializer.endDocument();
17262            serializer.flush();
17263        } catch (Exception e) {
17264            if (DEBUG_BACKUP) {
17265                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17266            }
17267            return null;
17268        }
17269
17270        return dataStream.toByteArray();
17271    }
17272
17273    @Override
17274    public void restorePreferredActivities(byte[] backup, int userId) {
17275        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17276            throw new SecurityException("Only the system may call restorePreferredActivities()");
17277        }
17278
17279        try {
17280            final XmlPullParser parser = Xml.newPullParser();
17281            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17282            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17283                    new BlobXmlRestorer() {
17284                        @Override
17285                        public void apply(XmlPullParser parser, int userId)
17286                                throws XmlPullParserException, IOException {
17287                            synchronized (mPackages) {
17288                                mSettings.readPreferredActivitiesLPw(parser, userId);
17289                            }
17290                        }
17291                    } );
17292        } catch (Exception e) {
17293            if (DEBUG_BACKUP) {
17294                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17295            }
17296        }
17297    }
17298
17299    /**
17300     * Non-Binder method, support for the backup/restore mechanism: write the
17301     * default browser (etc) settings in its canonical XML format.  Returns the default
17302     * browser XML representation as a byte array, or null if there is none.
17303     */
17304    @Override
17305    public byte[] getDefaultAppsBackup(int userId) {
17306        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17307            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17308        }
17309
17310        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17311        try {
17312            final XmlSerializer serializer = new FastXmlSerializer();
17313            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17314            serializer.startDocument(null, true);
17315            serializer.startTag(null, TAG_DEFAULT_APPS);
17316
17317            synchronized (mPackages) {
17318                mSettings.writeDefaultAppsLPr(serializer, userId);
17319            }
17320
17321            serializer.endTag(null, TAG_DEFAULT_APPS);
17322            serializer.endDocument();
17323            serializer.flush();
17324        } catch (Exception e) {
17325            if (DEBUG_BACKUP) {
17326                Slog.e(TAG, "Unable to write default apps for backup", e);
17327            }
17328            return null;
17329        }
17330
17331        return dataStream.toByteArray();
17332    }
17333
17334    @Override
17335    public void restoreDefaultApps(byte[] backup, int userId) {
17336        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17337            throw new SecurityException("Only the system may call restoreDefaultApps()");
17338        }
17339
17340        try {
17341            final XmlPullParser parser = Xml.newPullParser();
17342            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17343            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17344                    new BlobXmlRestorer() {
17345                        @Override
17346                        public void apply(XmlPullParser parser, int userId)
17347                                throws XmlPullParserException, IOException {
17348                            synchronized (mPackages) {
17349                                mSettings.readDefaultAppsLPw(parser, userId);
17350                            }
17351                        }
17352                    } );
17353        } catch (Exception e) {
17354            if (DEBUG_BACKUP) {
17355                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17356            }
17357        }
17358    }
17359
17360    @Override
17361    public byte[] getIntentFilterVerificationBackup(int userId) {
17362        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17363            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17364        }
17365
17366        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17367        try {
17368            final XmlSerializer serializer = new FastXmlSerializer();
17369            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17370            serializer.startDocument(null, true);
17371            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17372
17373            synchronized (mPackages) {
17374                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17375            }
17376
17377            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17378            serializer.endDocument();
17379            serializer.flush();
17380        } catch (Exception e) {
17381            if (DEBUG_BACKUP) {
17382                Slog.e(TAG, "Unable to write default apps for backup", e);
17383            }
17384            return null;
17385        }
17386
17387        return dataStream.toByteArray();
17388    }
17389
17390    @Override
17391    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17392        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17393            throw new SecurityException("Only the system may call restorePreferredActivities()");
17394        }
17395
17396        try {
17397            final XmlPullParser parser = Xml.newPullParser();
17398            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17399            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17400                    new BlobXmlRestorer() {
17401                        @Override
17402                        public void apply(XmlPullParser parser, int userId)
17403                                throws XmlPullParserException, IOException {
17404                            synchronized (mPackages) {
17405                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17406                                mSettings.writeLPr();
17407                            }
17408                        }
17409                    } );
17410        } catch (Exception e) {
17411            if (DEBUG_BACKUP) {
17412                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17413            }
17414        }
17415    }
17416
17417    @Override
17418    public byte[] getPermissionGrantBackup(int userId) {
17419        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17420            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17421        }
17422
17423        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17424        try {
17425            final XmlSerializer serializer = new FastXmlSerializer();
17426            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17427            serializer.startDocument(null, true);
17428            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17429
17430            synchronized (mPackages) {
17431                serializeRuntimePermissionGrantsLPr(serializer, userId);
17432            }
17433
17434            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17435            serializer.endDocument();
17436            serializer.flush();
17437        } catch (Exception e) {
17438            if (DEBUG_BACKUP) {
17439                Slog.e(TAG, "Unable to write default apps for backup", e);
17440            }
17441            return null;
17442        }
17443
17444        return dataStream.toByteArray();
17445    }
17446
17447    @Override
17448    public void restorePermissionGrants(byte[] backup, int userId) {
17449        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17450            throw new SecurityException("Only the system may call restorePermissionGrants()");
17451        }
17452
17453        try {
17454            final XmlPullParser parser = Xml.newPullParser();
17455            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17456            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17457                    new BlobXmlRestorer() {
17458                        @Override
17459                        public void apply(XmlPullParser parser, int userId)
17460                                throws XmlPullParserException, IOException {
17461                            synchronized (mPackages) {
17462                                processRestoredPermissionGrantsLPr(parser, userId);
17463                            }
17464                        }
17465                    } );
17466        } catch (Exception e) {
17467            if (DEBUG_BACKUP) {
17468                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17469            }
17470        }
17471    }
17472
17473    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17474            throws IOException {
17475        serializer.startTag(null, TAG_ALL_GRANTS);
17476
17477        final int N = mSettings.mPackages.size();
17478        for (int i = 0; i < N; i++) {
17479            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17480            boolean pkgGrantsKnown = false;
17481
17482            PermissionsState packagePerms = ps.getPermissionsState();
17483
17484            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17485                final int grantFlags = state.getFlags();
17486                // only look at grants that are not system/policy fixed
17487                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17488                    final boolean isGranted = state.isGranted();
17489                    // And only back up the user-twiddled state bits
17490                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17491                        final String packageName = mSettings.mPackages.keyAt(i);
17492                        if (!pkgGrantsKnown) {
17493                            serializer.startTag(null, TAG_GRANT);
17494                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17495                            pkgGrantsKnown = true;
17496                        }
17497
17498                        final boolean userSet =
17499                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17500                        final boolean userFixed =
17501                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17502                        final boolean revoke =
17503                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17504
17505                        serializer.startTag(null, TAG_PERMISSION);
17506                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17507                        if (isGranted) {
17508                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17509                        }
17510                        if (userSet) {
17511                            serializer.attribute(null, ATTR_USER_SET, "true");
17512                        }
17513                        if (userFixed) {
17514                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17515                        }
17516                        if (revoke) {
17517                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17518                        }
17519                        serializer.endTag(null, TAG_PERMISSION);
17520                    }
17521                }
17522            }
17523
17524            if (pkgGrantsKnown) {
17525                serializer.endTag(null, TAG_GRANT);
17526            }
17527        }
17528
17529        serializer.endTag(null, TAG_ALL_GRANTS);
17530    }
17531
17532    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17533            throws XmlPullParserException, IOException {
17534        String pkgName = null;
17535        int outerDepth = parser.getDepth();
17536        int type;
17537        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17538                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17539            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17540                continue;
17541            }
17542
17543            final String tagName = parser.getName();
17544            if (tagName.equals(TAG_GRANT)) {
17545                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17546                if (DEBUG_BACKUP) {
17547                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17548                }
17549            } else if (tagName.equals(TAG_PERMISSION)) {
17550
17551                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17552                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17553
17554                int newFlagSet = 0;
17555                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17556                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17557                }
17558                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17559                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17560                }
17561                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17562                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17563                }
17564                if (DEBUG_BACKUP) {
17565                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17566                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17567                }
17568                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17569                if (ps != null) {
17570                    // Already installed so we apply the grant immediately
17571                    if (DEBUG_BACKUP) {
17572                        Slog.v(TAG, "        + already installed; applying");
17573                    }
17574                    PermissionsState perms = ps.getPermissionsState();
17575                    BasePermission bp = mSettings.mPermissions.get(permName);
17576                    if (bp != null) {
17577                        if (isGranted) {
17578                            perms.grantRuntimePermission(bp, userId);
17579                        }
17580                        if (newFlagSet != 0) {
17581                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17582                        }
17583                    }
17584                } else {
17585                    // Need to wait for post-restore install to apply the grant
17586                    if (DEBUG_BACKUP) {
17587                        Slog.v(TAG, "        - not yet installed; saving for later");
17588                    }
17589                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17590                            isGranted, newFlagSet, userId);
17591                }
17592            } else {
17593                PackageManagerService.reportSettingsProblem(Log.WARN,
17594                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17595                XmlUtils.skipCurrentTag(parser);
17596            }
17597        }
17598
17599        scheduleWriteSettingsLocked();
17600        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17601    }
17602
17603    @Override
17604    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17605            int sourceUserId, int targetUserId, int flags) {
17606        mContext.enforceCallingOrSelfPermission(
17607                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17608        int callingUid = Binder.getCallingUid();
17609        enforceOwnerRights(ownerPackage, callingUid);
17610        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17611        if (intentFilter.countActions() == 0) {
17612            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17613            return;
17614        }
17615        synchronized (mPackages) {
17616            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17617                    ownerPackage, targetUserId, flags);
17618            CrossProfileIntentResolver resolver =
17619                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17620            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17621            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17622            if (existing != null) {
17623                int size = existing.size();
17624                for (int i = 0; i < size; i++) {
17625                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17626                        return;
17627                    }
17628                }
17629            }
17630            resolver.addFilter(newFilter);
17631            scheduleWritePackageRestrictionsLocked(sourceUserId);
17632        }
17633    }
17634
17635    @Override
17636    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17637        mContext.enforceCallingOrSelfPermission(
17638                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17639        int callingUid = Binder.getCallingUid();
17640        enforceOwnerRights(ownerPackage, callingUid);
17641        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17642        synchronized (mPackages) {
17643            CrossProfileIntentResolver resolver =
17644                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17645            ArraySet<CrossProfileIntentFilter> set =
17646                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17647            for (CrossProfileIntentFilter filter : set) {
17648                if (filter.getOwnerPackage().equals(ownerPackage)) {
17649                    resolver.removeFilter(filter);
17650                }
17651            }
17652            scheduleWritePackageRestrictionsLocked(sourceUserId);
17653        }
17654    }
17655
17656    // Enforcing that callingUid is owning pkg on userId
17657    private void enforceOwnerRights(String pkg, int callingUid) {
17658        // The system owns everything.
17659        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17660            return;
17661        }
17662        int callingUserId = UserHandle.getUserId(callingUid);
17663        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17664        if (pi == null) {
17665            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17666                    + callingUserId);
17667        }
17668        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17669            throw new SecurityException("Calling uid " + callingUid
17670                    + " does not own package " + pkg);
17671        }
17672    }
17673
17674    @Override
17675    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17676        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17677    }
17678
17679    private Intent getHomeIntent() {
17680        Intent intent = new Intent(Intent.ACTION_MAIN);
17681        intent.addCategory(Intent.CATEGORY_HOME);
17682        intent.addCategory(Intent.CATEGORY_DEFAULT);
17683        return intent;
17684    }
17685
17686    private IntentFilter getHomeFilter() {
17687        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17688        filter.addCategory(Intent.CATEGORY_HOME);
17689        filter.addCategory(Intent.CATEGORY_DEFAULT);
17690        return filter;
17691    }
17692
17693    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17694            int userId) {
17695        Intent intent  = getHomeIntent();
17696        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17697                PackageManager.GET_META_DATA, userId);
17698        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17699                true, false, false, userId);
17700
17701        allHomeCandidates.clear();
17702        if (list != null) {
17703            for (ResolveInfo ri : list) {
17704                allHomeCandidates.add(ri);
17705            }
17706        }
17707        return (preferred == null || preferred.activityInfo == null)
17708                ? null
17709                : new ComponentName(preferred.activityInfo.packageName,
17710                        preferred.activityInfo.name);
17711    }
17712
17713    @Override
17714    public void setHomeActivity(ComponentName comp, int userId) {
17715        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17716        getHomeActivitiesAsUser(homeActivities, userId);
17717
17718        boolean found = false;
17719
17720        final int size = homeActivities.size();
17721        final ComponentName[] set = new ComponentName[size];
17722        for (int i = 0; i < size; i++) {
17723            final ResolveInfo candidate = homeActivities.get(i);
17724            final ActivityInfo info = candidate.activityInfo;
17725            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17726            set[i] = activityName;
17727            if (!found && activityName.equals(comp)) {
17728                found = true;
17729            }
17730        }
17731        if (!found) {
17732            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17733                    + userId);
17734        }
17735        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17736                set, comp, userId);
17737    }
17738
17739    private @Nullable String getSetupWizardPackageName() {
17740        final Intent intent = new Intent(Intent.ACTION_MAIN);
17741        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17742
17743        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17744                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17745                        | MATCH_DISABLED_COMPONENTS,
17746                UserHandle.myUserId());
17747        if (matches.size() == 1) {
17748            return matches.get(0).getComponentInfo().packageName;
17749        } else {
17750            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17751                    + ": matches=" + matches);
17752            return null;
17753        }
17754    }
17755
17756    @Override
17757    public void setApplicationEnabledSetting(String appPackageName,
17758            int newState, int flags, int userId, String callingPackage) {
17759        if (!sUserManager.exists(userId)) return;
17760        if (callingPackage == null) {
17761            callingPackage = Integer.toString(Binder.getCallingUid());
17762        }
17763        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17764    }
17765
17766    @Override
17767    public void setComponentEnabledSetting(ComponentName componentName,
17768            int newState, int flags, int userId) {
17769        if (!sUserManager.exists(userId)) return;
17770        setEnabledSetting(componentName.getPackageName(),
17771                componentName.getClassName(), newState, flags, userId, null);
17772    }
17773
17774    private void setEnabledSetting(final String packageName, String className, int newState,
17775            final int flags, int userId, String callingPackage) {
17776        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17777              || newState == COMPONENT_ENABLED_STATE_ENABLED
17778              || newState == COMPONENT_ENABLED_STATE_DISABLED
17779              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17780              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17781            throw new IllegalArgumentException("Invalid new component state: "
17782                    + newState);
17783        }
17784        PackageSetting pkgSetting;
17785        final int uid = Binder.getCallingUid();
17786        final int permission;
17787        if (uid == Process.SYSTEM_UID) {
17788            permission = PackageManager.PERMISSION_GRANTED;
17789        } else {
17790            permission = mContext.checkCallingOrSelfPermission(
17791                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17792        }
17793        enforceCrossUserPermission(uid, userId,
17794                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17795        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17796        boolean sendNow = false;
17797        boolean isApp = (className == null);
17798        String componentName = isApp ? packageName : className;
17799        int packageUid = -1;
17800        ArrayList<String> components;
17801
17802        // writer
17803        synchronized (mPackages) {
17804            pkgSetting = mSettings.mPackages.get(packageName);
17805            if (pkgSetting == null) {
17806                if (className == null) {
17807                    throw new IllegalArgumentException("Unknown package: " + packageName);
17808                }
17809                throw new IllegalArgumentException(
17810                        "Unknown component: " + packageName + "/" + className);
17811            }
17812        }
17813
17814        // Limit who can change which apps
17815        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17816            // Don't allow apps that don't have permission to modify other apps
17817            if (!allowedByPermission) {
17818                throw new SecurityException(
17819                        "Permission Denial: attempt to change component state from pid="
17820                        + Binder.getCallingPid()
17821                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17822            }
17823            // Don't allow changing protected packages.
17824            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17825                throw new SecurityException("Cannot disable a protected package: " + packageName);
17826            }
17827        }
17828
17829        synchronized (mPackages) {
17830            if (uid == Process.SHELL_UID) {
17831                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17832                int oldState = pkgSetting.getEnabled(userId);
17833                if (className == null
17834                    &&
17835                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17836                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17837                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17838                    &&
17839                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17840                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17841                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17842                    // ok
17843                } else {
17844                    throw new SecurityException(
17845                            "Shell cannot change component state for " + packageName + "/"
17846                            + className + " to " + newState);
17847                }
17848            }
17849            if (className == null) {
17850                // We're dealing with an application/package level state change
17851                if (pkgSetting.getEnabled(userId) == newState) {
17852                    // Nothing to do
17853                    return;
17854                }
17855                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17856                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17857                    // Don't care about who enables an app.
17858                    callingPackage = null;
17859                }
17860                pkgSetting.setEnabled(newState, userId, callingPackage);
17861                // pkgSetting.pkg.mSetEnabled = newState;
17862            } else {
17863                // We're dealing with a component level state change
17864                // First, verify that this is a valid class name.
17865                PackageParser.Package pkg = pkgSetting.pkg;
17866                if (pkg == null || !pkg.hasComponentClassName(className)) {
17867                    if (pkg != null &&
17868                            pkg.applicationInfo.targetSdkVersion >=
17869                                    Build.VERSION_CODES.JELLY_BEAN) {
17870                        throw new IllegalArgumentException("Component class " + className
17871                                + " does not exist in " + packageName);
17872                    } else {
17873                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17874                                + className + " does not exist in " + packageName);
17875                    }
17876                }
17877                switch (newState) {
17878                case COMPONENT_ENABLED_STATE_ENABLED:
17879                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17880                        return;
17881                    }
17882                    break;
17883                case COMPONENT_ENABLED_STATE_DISABLED:
17884                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17885                        return;
17886                    }
17887                    break;
17888                case COMPONENT_ENABLED_STATE_DEFAULT:
17889                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17890                        return;
17891                    }
17892                    break;
17893                default:
17894                    Slog.e(TAG, "Invalid new component state: " + newState);
17895                    return;
17896                }
17897            }
17898            scheduleWritePackageRestrictionsLocked(userId);
17899            components = mPendingBroadcasts.get(userId, packageName);
17900            final boolean newPackage = components == null;
17901            if (newPackage) {
17902                components = new ArrayList<String>();
17903            }
17904            if (!components.contains(componentName)) {
17905                components.add(componentName);
17906            }
17907            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17908                sendNow = true;
17909                // Purge entry from pending broadcast list if another one exists already
17910                // since we are sending one right away.
17911                mPendingBroadcasts.remove(userId, packageName);
17912            } else {
17913                if (newPackage) {
17914                    mPendingBroadcasts.put(userId, packageName, components);
17915                }
17916                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17917                    // Schedule a message
17918                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17919                }
17920            }
17921        }
17922
17923        long callingId = Binder.clearCallingIdentity();
17924        try {
17925            if (sendNow) {
17926                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17927                sendPackageChangedBroadcast(packageName,
17928                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17929            }
17930        } finally {
17931            Binder.restoreCallingIdentity(callingId);
17932        }
17933    }
17934
17935    @Override
17936    public void flushPackageRestrictionsAsUser(int userId) {
17937        if (!sUserManager.exists(userId)) {
17938            return;
17939        }
17940        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17941                false /* checkShell */, "flushPackageRestrictions");
17942        synchronized (mPackages) {
17943            mSettings.writePackageRestrictionsLPr(userId);
17944            mDirtyUsers.remove(userId);
17945            if (mDirtyUsers.isEmpty()) {
17946                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17947            }
17948        }
17949    }
17950
17951    private void sendPackageChangedBroadcast(String packageName,
17952            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17953        if (DEBUG_INSTALL)
17954            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17955                    + componentNames);
17956        Bundle extras = new Bundle(4);
17957        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17958        String nameList[] = new String[componentNames.size()];
17959        componentNames.toArray(nameList);
17960        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17961        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17962        extras.putInt(Intent.EXTRA_UID, packageUid);
17963        // If this is not reporting a change of the overall package, then only send it
17964        // to registered receivers.  We don't want to launch a swath of apps for every
17965        // little component state change.
17966        final int flags = !componentNames.contains(packageName)
17967                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17968        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17969                new int[] {UserHandle.getUserId(packageUid)});
17970    }
17971
17972    @Override
17973    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17974        if (!sUserManager.exists(userId)) return;
17975        final int uid = Binder.getCallingUid();
17976        final int permission = mContext.checkCallingOrSelfPermission(
17977                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17978        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17979        enforceCrossUserPermission(uid, userId,
17980                true /* requireFullPermission */, true /* checkShell */, "stop package");
17981        // writer
17982        synchronized (mPackages) {
17983            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17984                    allowedByPermission, uid, userId)) {
17985                scheduleWritePackageRestrictionsLocked(userId);
17986            }
17987        }
17988    }
17989
17990    @Override
17991    public String getInstallerPackageName(String packageName) {
17992        // reader
17993        synchronized (mPackages) {
17994            return mSettings.getInstallerPackageNameLPr(packageName);
17995        }
17996    }
17997
17998    public boolean isOrphaned(String packageName) {
17999        // reader
18000        synchronized (mPackages) {
18001            return mSettings.isOrphaned(packageName);
18002        }
18003    }
18004
18005    @Override
18006    public int getApplicationEnabledSetting(String packageName, int userId) {
18007        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18008        int uid = Binder.getCallingUid();
18009        enforceCrossUserPermission(uid, userId,
18010                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18011        // reader
18012        synchronized (mPackages) {
18013            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18014        }
18015    }
18016
18017    @Override
18018    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18019        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18020        int uid = Binder.getCallingUid();
18021        enforceCrossUserPermission(uid, userId,
18022                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18023        // reader
18024        synchronized (mPackages) {
18025            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18026        }
18027    }
18028
18029    @Override
18030    public void enterSafeMode() {
18031        enforceSystemOrRoot("Only the system can request entering safe mode");
18032
18033        if (!mSystemReady) {
18034            mSafeMode = true;
18035        }
18036    }
18037
18038    @Override
18039    public void systemReady() {
18040        mSystemReady = true;
18041
18042        // Read the compatibilty setting when the system is ready.
18043        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18044                mContext.getContentResolver(),
18045                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18046        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18047        if (DEBUG_SETTINGS) {
18048            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18049        }
18050
18051        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18052
18053        synchronized (mPackages) {
18054            // Verify that all of the preferred activity components actually
18055            // exist.  It is possible for applications to be updated and at
18056            // that point remove a previously declared activity component that
18057            // had been set as a preferred activity.  We try to clean this up
18058            // the next time we encounter that preferred activity, but it is
18059            // possible for the user flow to never be able to return to that
18060            // situation so here we do a sanity check to make sure we haven't
18061            // left any junk around.
18062            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18063            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18064                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18065                removed.clear();
18066                for (PreferredActivity pa : pir.filterSet()) {
18067                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18068                        removed.add(pa);
18069                    }
18070                }
18071                if (removed.size() > 0) {
18072                    for (int r=0; r<removed.size(); r++) {
18073                        PreferredActivity pa = removed.get(r);
18074                        Slog.w(TAG, "Removing dangling preferred activity: "
18075                                + pa.mPref.mComponent);
18076                        pir.removeFilter(pa);
18077                    }
18078                    mSettings.writePackageRestrictionsLPr(
18079                            mSettings.mPreferredActivities.keyAt(i));
18080                }
18081            }
18082
18083            for (int userId : UserManagerService.getInstance().getUserIds()) {
18084                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18085                    grantPermissionsUserIds = ArrayUtils.appendInt(
18086                            grantPermissionsUserIds, userId);
18087                }
18088            }
18089        }
18090        sUserManager.systemReady();
18091
18092        // If we upgraded grant all default permissions before kicking off.
18093        for (int userId : grantPermissionsUserIds) {
18094            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18095        }
18096
18097        // Kick off any messages waiting for system ready
18098        if (mPostSystemReadyMessages != null) {
18099            for (Message msg : mPostSystemReadyMessages) {
18100                msg.sendToTarget();
18101            }
18102            mPostSystemReadyMessages = null;
18103        }
18104
18105        // Watch for external volumes that come and go over time
18106        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18107        storage.registerListener(mStorageListener);
18108
18109        mInstallerService.systemReady();
18110        mPackageDexOptimizer.systemReady();
18111
18112        MountServiceInternal mountServiceInternal = LocalServices.getService(
18113                MountServiceInternal.class);
18114        mountServiceInternal.addExternalStoragePolicy(
18115                new MountServiceInternal.ExternalStorageMountPolicy() {
18116            @Override
18117            public int getMountMode(int uid, String packageName) {
18118                if (Process.isIsolated(uid)) {
18119                    return Zygote.MOUNT_EXTERNAL_NONE;
18120                }
18121                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18122                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18123                }
18124                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18125                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18126                }
18127                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18128                    return Zygote.MOUNT_EXTERNAL_READ;
18129                }
18130                return Zygote.MOUNT_EXTERNAL_WRITE;
18131            }
18132
18133            @Override
18134            public boolean hasExternalStorage(int uid, String packageName) {
18135                return true;
18136            }
18137        });
18138
18139        // Now that we're mostly running, clean up stale users and apps
18140        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18141        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18142    }
18143
18144    @Override
18145    public boolean isSafeMode() {
18146        return mSafeMode;
18147    }
18148
18149    @Override
18150    public boolean hasSystemUidErrors() {
18151        return mHasSystemUidErrors;
18152    }
18153
18154    static String arrayToString(int[] array) {
18155        StringBuffer buf = new StringBuffer(128);
18156        buf.append('[');
18157        if (array != null) {
18158            for (int i=0; i<array.length; i++) {
18159                if (i > 0) buf.append(", ");
18160                buf.append(array[i]);
18161            }
18162        }
18163        buf.append(']');
18164        return buf.toString();
18165    }
18166
18167    static class DumpState {
18168        public static final int DUMP_LIBS = 1 << 0;
18169        public static final int DUMP_FEATURES = 1 << 1;
18170        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18171        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18172        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18173        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18174        public static final int DUMP_PERMISSIONS = 1 << 6;
18175        public static final int DUMP_PACKAGES = 1 << 7;
18176        public static final int DUMP_SHARED_USERS = 1 << 8;
18177        public static final int DUMP_MESSAGES = 1 << 9;
18178        public static final int DUMP_PROVIDERS = 1 << 10;
18179        public static final int DUMP_VERIFIERS = 1 << 11;
18180        public static final int DUMP_PREFERRED = 1 << 12;
18181        public static final int DUMP_PREFERRED_XML = 1 << 13;
18182        public static final int DUMP_KEYSETS = 1 << 14;
18183        public static final int DUMP_VERSION = 1 << 15;
18184        public static final int DUMP_INSTALLS = 1 << 16;
18185        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18186        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18187        public static final int DUMP_FROZEN = 1 << 19;
18188        public static final int DUMP_DEXOPT = 1 << 20;
18189
18190        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18191
18192        private int mTypes;
18193
18194        private int mOptions;
18195
18196        private boolean mTitlePrinted;
18197
18198        private SharedUserSetting mSharedUser;
18199
18200        public boolean isDumping(int type) {
18201            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18202                return true;
18203            }
18204
18205            return (mTypes & type) != 0;
18206        }
18207
18208        public void setDump(int type) {
18209            mTypes |= type;
18210        }
18211
18212        public boolean isOptionEnabled(int option) {
18213            return (mOptions & option) != 0;
18214        }
18215
18216        public void setOptionEnabled(int option) {
18217            mOptions |= option;
18218        }
18219
18220        public boolean onTitlePrinted() {
18221            final boolean printed = mTitlePrinted;
18222            mTitlePrinted = true;
18223            return printed;
18224        }
18225
18226        public boolean getTitlePrinted() {
18227            return mTitlePrinted;
18228        }
18229
18230        public void setTitlePrinted(boolean enabled) {
18231            mTitlePrinted = enabled;
18232        }
18233
18234        public SharedUserSetting getSharedUser() {
18235            return mSharedUser;
18236        }
18237
18238        public void setSharedUser(SharedUserSetting user) {
18239            mSharedUser = user;
18240        }
18241    }
18242
18243    @Override
18244    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18245            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18246        (new PackageManagerShellCommand(this)).exec(
18247                this, in, out, err, args, resultReceiver);
18248    }
18249
18250    @Override
18251    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18252        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18253                != PackageManager.PERMISSION_GRANTED) {
18254            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18255                    + Binder.getCallingPid()
18256                    + ", uid=" + Binder.getCallingUid()
18257                    + " without permission "
18258                    + android.Manifest.permission.DUMP);
18259            return;
18260        }
18261
18262        DumpState dumpState = new DumpState();
18263        boolean fullPreferred = false;
18264        boolean checkin = false;
18265
18266        String packageName = null;
18267        ArraySet<String> permissionNames = null;
18268
18269        int opti = 0;
18270        while (opti < args.length) {
18271            String opt = args[opti];
18272            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18273                break;
18274            }
18275            opti++;
18276
18277            if ("-a".equals(opt)) {
18278                // Right now we only know how to print all.
18279            } else if ("-h".equals(opt)) {
18280                pw.println("Package manager dump options:");
18281                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18282                pw.println("    --checkin: dump for a checkin");
18283                pw.println("    -f: print details of intent filters");
18284                pw.println("    -h: print this help");
18285                pw.println("  cmd may be one of:");
18286                pw.println("    l[ibraries]: list known shared libraries");
18287                pw.println("    f[eatures]: list device features");
18288                pw.println("    k[eysets]: print known keysets");
18289                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18290                pw.println("    perm[issions]: dump permissions");
18291                pw.println("    permission [name ...]: dump declaration and use of given permission");
18292                pw.println("    pref[erred]: print preferred package settings");
18293                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18294                pw.println("    prov[iders]: dump content providers");
18295                pw.println("    p[ackages]: dump installed packages");
18296                pw.println("    s[hared-users]: dump shared user IDs");
18297                pw.println("    m[essages]: print collected runtime messages");
18298                pw.println("    v[erifiers]: print package verifier info");
18299                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18300                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18301                pw.println("    version: print database version info");
18302                pw.println("    write: write current settings now");
18303                pw.println("    installs: details about install sessions");
18304                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18305                pw.println("    dexopt: dump dexopt state");
18306                pw.println("    <package.name>: info about given package");
18307                return;
18308            } else if ("--checkin".equals(opt)) {
18309                checkin = true;
18310            } else if ("-f".equals(opt)) {
18311                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18312            } else {
18313                pw.println("Unknown argument: " + opt + "; use -h for help");
18314            }
18315        }
18316
18317        // Is the caller requesting to dump a particular piece of data?
18318        if (opti < args.length) {
18319            String cmd = args[opti];
18320            opti++;
18321            // Is this a package name?
18322            if ("android".equals(cmd) || cmd.contains(".")) {
18323                packageName = cmd;
18324                // When dumping a single package, we always dump all of its
18325                // filter information since the amount of data will be reasonable.
18326                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18327            } else if ("check-permission".equals(cmd)) {
18328                if (opti >= args.length) {
18329                    pw.println("Error: check-permission missing permission argument");
18330                    return;
18331                }
18332                String perm = args[opti];
18333                opti++;
18334                if (opti >= args.length) {
18335                    pw.println("Error: check-permission missing package argument");
18336                    return;
18337                }
18338                String pkg = args[opti];
18339                opti++;
18340                int user = UserHandle.getUserId(Binder.getCallingUid());
18341                if (opti < args.length) {
18342                    try {
18343                        user = Integer.parseInt(args[opti]);
18344                    } catch (NumberFormatException e) {
18345                        pw.println("Error: check-permission user argument is not a number: "
18346                                + args[opti]);
18347                        return;
18348                    }
18349                }
18350                pw.println(checkPermission(perm, pkg, user));
18351                return;
18352            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18353                dumpState.setDump(DumpState.DUMP_LIBS);
18354            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18355                dumpState.setDump(DumpState.DUMP_FEATURES);
18356            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18357                if (opti >= args.length) {
18358                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18359                            | DumpState.DUMP_SERVICE_RESOLVERS
18360                            | DumpState.DUMP_RECEIVER_RESOLVERS
18361                            | DumpState.DUMP_CONTENT_RESOLVERS);
18362                } else {
18363                    while (opti < args.length) {
18364                        String name = args[opti];
18365                        if ("a".equals(name) || "activity".equals(name)) {
18366                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18367                        } else if ("s".equals(name) || "service".equals(name)) {
18368                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18369                        } else if ("r".equals(name) || "receiver".equals(name)) {
18370                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18371                        } else if ("c".equals(name) || "content".equals(name)) {
18372                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18373                        } else {
18374                            pw.println("Error: unknown resolver table type: " + name);
18375                            return;
18376                        }
18377                        opti++;
18378                    }
18379                }
18380            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18381                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18382            } else if ("permission".equals(cmd)) {
18383                if (opti >= args.length) {
18384                    pw.println("Error: permission requires permission name");
18385                    return;
18386                }
18387                permissionNames = new ArraySet<>();
18388                while (opti < args.length) {
18389                    permissionNames.add(args[opti]);
18390                    opti++;
18391                }
18392                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18393                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18394            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18395                dumpState.setDump(DumpState.DUMP_PREFERRED);
18396            } else if ("preferred-xml".equals(cmd)) {
18397                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18398                if (opti < args.length && "--full".equals(args[opti])) {
18399                    fullPreferred = true;
18400                    opti++;
18401                }
18402            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18403                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18404            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18405                dumpState.setDump(DumpState.DUMP_PACKAGES);
18406            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18407                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18408            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18409                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18410            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18411                dumpState.setDump(DumpState.DUMP_MESSAGES);
18412            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18413                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18414            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18415                    || "intent-filter-verifiers".equals(cmd)) {
18416                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18417            } else if ("version".equals(cmd)) {
18418                dumpState.setDump(DumpState.DUMP_VERSION);
18419            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18420                dumpState.setDump(DumpState.DUMP_KEYSETS);
18421            } else if ("installs".equals(cmd)) {
18422                dumpState.setDump(DumpState.DUMP_INSTALLS);
18423            } else if ("frozen".equals(cmd)) {
18424                dumpState.setDump(DumpState.DUMP_FROZEN);
18425            } else if ("dexopt".equals(cmd)) {
18426                dumpState.setDump(DumpState.DUMP_DEXOPT);
18427            } else if ("write".equals(cmd)) {
18428                synchronized (mPackages) {
18429                    mSettings.writeLPr();
18430                    pw.println("Settings written.");
18431                    return;
18432                }
18433            }
18434        }
18435
18436        if (checkin) {
18437            pw.println("vers,1");
18438        }
18439
18440        // reader
18441        synchronized (mPackages) {
18442            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18443                if (!checkin) {
18444                    if (dumpState.onTitlePrinted())
18445                        pw.println();
18446                    pw.println("Database versions:");
18447                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18448                }
18449            }
18450
18451            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18452                if (!checkin) {
18453                    if (dumpState.onTitlePrinted())
18454                        pw.println();
18455                    pw.println("Verifiers:");
18456                    pw.print("  Required: ");
18457                    pw.print(mRequiredVerifierPackage);
18458                    pw.print(" (uid=");
18459                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18460                            UserHandle.USER_SYSTEM));
18461                    pw.println(")");
18462                } else if (mRequiredVerifierPackage != null) {
18463                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18464                    pw.print(",");
18465                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18466                            UserHandle.USER_SYSTEM));
18467                }
18468            }
18469
18470            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18471                    packageName == null) {
18472                if (mIntentFilterVerifierComponent != null) {
18473                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18474                    if (!checkin) {
18475                        if (dumpState.onTitlePrinted())
18476                            pw.println();
18477                        pw.println("Intent Filter Verifier:");
18478                        pw.print("  Using: ");
18479                        pw.print(verifierPackageName);
18480                        pw.print(" (uid=");
18481                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18482                                UserHandle.USER_SYSTEM));
18483                        pw.println(")");
18484                    } else if (verifierPackageName != null) {
18485                        pw.print("ifv,"); pw.print(verifierPackageName);
18486                        pw.print(",");
18487                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18488                                UserHandle.USER_SYSTEM));
18489                    }
18490                } else {
18491                    pw.println();
18492                    pw.println("No Intent Filter Verifier available!");
18493                }
18494            }
18495
18496            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18497                boolean printedHeader = false;
18498                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18499                while (it.hasNext()) {
18500                    String name = it.next();
18501                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18502                    if (!checkin) {
18503                        if (!printedHeader) {
18504                            if (dumpState.onTitlePrinted())
18505                                pw.println();
18506                            pw.println("Libraries:");
18507                            printedHeader = true;
18508                        }
18509                        pw.print("  ");
18510                    } else {
18511                        pw.print("lib,");
18512                    }
18513                    pw.print(name);
18514                    if (!checkin) {
18515                        pw.print(" -> ");
18516                    }
18517                    if (ent.path != null) {
18518                        if (!checkin) {
18519                            pw.print("(jar) ");
18520                            pw.print(ent.path);
18521                        } else {
18522                            pw.print(",jar,");
18523                            pw.print(ent.path);
18524                        }
18525                    } else {
18526                        if (!checkin) {
18527                            pw.print("(apk) ");
18528                            pw.print(ent.apk);
18529                        } else {
18530                            pw.print(",apk,");
18531                            pw.print(ent.apk);
18532                        }
18533                    }
18534                    pw.println();
18535                }
18536            }
18537
18538            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18539                if (dumpState.onTitlePrinted())
18540                    pw.println();
18541                if (!checkin) {
18542                    pw.println("Features:");
18543                }
18544
18545                for (FeatureInfo feat : mAvailableFeatures.values()) {
18546                    if (checkin) {
18547                        pw.print("feat,");
18548                        pw.print(feat.name);
18549                        pw.print(",");
18550                        pw.println(feat.version);
18551                    } else {
18552                        pw.print("  ");
18553                        pw.print(feat.name);
18554                        if (feat.version > 0) {
18555                            pw.print(" version=");
18556                            pw.print(feat.version);
18557                        }
18558                        pw.println();
18559                    }
18560                }
18561            }
18562
18563            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18564                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18565                        : "Activity Resolver Table:", "  ", packageName,
18566                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18567                    dumpState.setTitlePrinted(true);
18568                }
18569            }
18570            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18571                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18572                        : "Receiver Resolver Table:", "  ", packageName,
18573                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18574                    dumpState.setTitlePrinted(true);
18575                }
18576            }
18577            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18578                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18579                        : "Service Resolver Table:", "  ", packageName,
18580                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18581                    dumpState.setTitlePrinted(true);
18582                }
18583            }
18584            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18585                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18586                        : "Provider Resolver Table:", "  ", packageName,
18587                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18588                    dumpState.setTitlePrinted(true);
18589                }
18590            }
18591
18592            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18593                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18594                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18595                    int user = mSettings.mPreferredActivities.keyAt(i);
18596                    if (pir.dump(pw,
18597                            dumpState.getTitlePrinted()
18598                                ? "\nPreferred Activities User " + user + ":"
18599                                : "Preferred Activities User " + user + ":", "  ",
18600                            packageName, true, false)) {
18601                        dumpState.setTitlePrinted(true);
18602                    }
18603                }
18604            }
18605
18606            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18607                pw.flush();
18608                FileOutputStream fout = new FileOutputStream(fd);
18609                BufferedOutputStream str = new BufferedOutputStream(fout);
18610                XmlSerializer serializer = new FastXmlSerializer();
18611                try {
18612                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18613                    serializer.startDocument(null, true);
18614                    serializer.setFeature(
18615                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18616                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18617                    serializer.endDocument();
18618                    serializer.flush();
18619                } catch (IllegalArgumentException e) {
18620                    pw.println("Failed writing: " + e);
18621                } catch (IllegalStateException e) {
18622                    pw.println("Failed writing: " + e);
18623                } catch (IOException e) {
18624                    pw.println("Failed writing: " + e);
18625                }
18626            }
18627
18628            if (!checkin
18629                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18630                    && packageName == null) {
18631                pw.println();
18632                int count = mSettings.mPackages.size();
18633                if (count == 0) {
18634                    pw.println("No applications!");
18635                    pw.println();
18636                } else {
18637                    final String prefix = "  ";
18638                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18639                    if (allPackageSettings.size() == 0) {
18640                        pw.println("No domain preferred apps!");
18641                        pw.println();
18642                    } else {
18643                        pw.println("App verification status:");
18644                        pw.println();
18645                        count = 0;
18646                        for (PackageSetting ps : allPackageSettings) {
18647                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18648                            if (ivi == null || ivi.getPackageName() == null) continue;
18649                            pw.println(prefix + "Package: " + ivi.getPackageName());
18650                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18651                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18652                            pw.println();
18653                            count++;
18654                        }
18655                        if (count == 0) {
18656                            pw.println(prefix + "No app verification established.");
18657                            pw.println();
18658                        }
18659                        for (int userId : sUserManager.getUserIds()) {
18660                            pw.println("App linkages for user " + userId + ":");
18661                            pw.println();
18662                            count = 0;
18663                            for (PackageSetting ps : allPackageSettings) {
18664                                final long status = ps.getDomainVerificationStatusForUser(userId);
18665                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18666                                    continue;
18667                                }
18668                                pw.println(prefix + "Package: " + ps.name);
18669                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18670                                String statusStr = IntentFilterVerificationInfo.
18671                                        getStatusStringFromValue(status);
18672                                pw.println(prefix + "Status:  " + statusStr);
18673                                pw.println();
18674                                count++;
18675                            }
18676                            if (count == 0) {
18677                                pw.println(prefix + "No configured app linkages.");
18678                                pw.println();
18679                            }
18680                        }
18681                    }
18682                }
18683            }
18684
18685            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18686                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18687                if (packageName == null && permissionNames == null) {
18688                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18689                        if (iperm == 0) {
18690                            if (dumpState.onTitlePrinted())
18691                                pw.println();
18692                            pw.println("AppOp Permissions:");
18693                        }
18694                        pw.print("  AppOp Permission ");
18695                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18696                        pw.println(":");
18697                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18698                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18699                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18700                        }
18701                    }
18702                }
18703            }
18704
18705            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18706                boolean printedSomething = false;
18707                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18708                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18709                        continue;
18710                    }
18711                    if (!printedSomething) {
18712                        if (dumpState.onTitlePrinted())
18713                            pw.println();
18714                        pw.println("Registered ContentProviders:");
18715                        printedSomething = true;
18716                    }
18717                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18718                    pw.print("    "); pw.println(p.toString());
18719                }
18720                printedSomething = false;
18721                for (Map.Entry<String, PackageParser.Provider> entry :
18722                        mProvidersByAuthority.entrySet()) {
18723                    PackageParser.Provider p = entry.getValue();
18724                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18725                        continue;
18726                    }
18727                    if (!printedSomething) {
18728                        if (dumpState.onTitlePrinted())
18729                            pw.println();
18730                        pw.println("ContentProvider Authorities:");
18731                        printedSomething = true;
18732                    }
18733                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18734                    pw.print("    "); pw.println(p.toString());
18735                    if (p.info != null && p.info.applicationInfo != null) {
18736                        final String appInfo = p.info.applicationInfo.toString();
18737                        pw.print("      applicationInfo="); pw.println(appInfo);
18738                    }
18739                }
18740            }
18741
18742            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18743                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18744            }
18745
18746            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18747                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18748            }
18749
18750            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18751                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18752            }
18753
18754            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18755                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18756            }
18757
18758            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18759                // XXX should handle packageName != null by dumping only install data that
18760                // the given package is involved with.
18761                if (dumpState.onTitlePrinted()) pw.println();
18762                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18763            }
18764
18765            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18766                // XXX should handle packageName != null by dumping only install data that
18767                // the given package is involved with.
18768                if (dumpState.onTitlePrinted()) pw.println();
18769
18770                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18771                ipw.println();
18772                ipw.println("Frozen packages:");
18773                ipw.increaseIndent();
18774                if (mFrozenPackages.size() == 0) {
18775                    ipw.println("(none)");
18776                } else {
18777                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18778                        ipw.println(mFrozenPackages.valueAt(i));
18779                    }
18780                }
18781                ipw.decreaseIndent();
18782            }
18783
18784            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18785                if (dumpState.onTitlePrinted()) pw.println();
18786                dumpDexoptStateLPr(pw, packageName);
18787            }
18788
18789            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18790                if (dumpState.onTitlePrinted()) pw.println();
18791                mSettings.dumpReadMessagesLPr(pw, dumpState);
18792
18793                pw.println();
18794                pw.println("Package warning messages:");
18795                BufferedReader in = null;
18796                String line = null;
18797                try {
18798                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18799                    while ((line = in.readLine()) != null) {
18800                        if (line.contains("ignored: updated version")) continue;
18801                        pw.println(line);
18802                    }
18803                } catch (IOException ignored) {
18804                } finally {
18805                    IoUtils.closeQuietly(in);
18806                }
18807            }
18808
18809            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18810                BufferedReader in = null;
18811                String line = null;
18812                try {
18813                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18814                    while ((line = in.readLine()) != null) {
18815                        if (line.contains("ignored: updated version")) continue;
18816                        pw.print("msg,");
18817                        pw.println(line);
18818                    }
18819                } catch (IOException ignored) {
18820                } finally {
18821                    IoUtils.closeQuietly(in);
18822                }
18823            }
18824        }
18825    }
18826
18827    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18828        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18829        ipw.println();
18830        ipw.println("Dexopt state:");
18831        ipw.increaseIndent();
18832        Collection<PackageParser.Package> packages = null;
18833        if (packageName != null) {
18834            PackageParser.Package targetPackage = mPackages.get(packageName);
18835            if (targetPackage != null) {
18836                packages = Collections.singletonList(targetPackage);
18837            } else {
18838                ipw.println("Unable to find package: " + packageName);
18839                return;
18840            }
18841        } else {
18842            packages = mPackages.values();
18843        }
18844
18845        for (PackageParser.Package pkg : packages) {
18846            ipw.println("[" + pkg.packageName + "]");
18847            ipw.increaseIndent();
18848            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18849            ipw.decreaseIndent();
18850        }
18851    }
18852
18853    private String dumpDomainString(String packageName) {
18854        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18855                .getList();
18856        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18857
18858        ArraySet<String> result = new ArraySet<>();
18859        if (iviList.size() > 0) {
18860            for (IntentFilterVerificationInfo ivi : iviList) {
18861                for (String host : ivi.getDomains()) {
18862                    result.add(host);
18863                }
18864            }
18865        }
18866        if (filters != null && filters.size() > 0) {
18867            for (IntentFilter filter : filters) {
18868                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18869                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18870                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18871                    result.addAll(filter.getHostsList());
18872                }
18873            }
18874        }
18875
18876        StringBuilder sb = new StringBuilder(result.size() * 16);
18877        for (String domain : result) {
18878            if (sb.length() > 0) sb.append(" ");
18879            sb.append(domain);
18880        }
18881        return sb.toString();
18882    }
18883
18884    // ------- apps on sdcard specific code -------
18885    static final boolean DEBUG_SD_INSTALL = false;
18886
18887    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18888
18889    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18890
18891    private boolean mMediaMounted = false;
18892
18893    static String getEncryptKey() {
18894        try {
18895            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18896                    SD_ENCRYPTION_KEYSTORE_NAME);
18897            if (sdEncKey == null) {
18898                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18899                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18900                if (sdEncKey == null) {
18901                    Slog.e(TAG, "Failed to create encryption keys");
18902                    return null;
18903                }
18904            }
18905            return sdEncKey;
18906        } catch (NoSuchAlgorithmException nsae) {
18907            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18908            return null;
18909        } catch (IOException ioe) {
18910            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18911            return null;
18912        }
18913    }
18914
18915    /*
18916     * Update media status on PackageManager.
18917     */
18918    @Override
18919    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18920        int callingUid = Binder.getCallingUid();
18921        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18922            throw new SecurityException("Media status can only be updated by the system");
18923        }
18924        // reader; this apparently protects mMediaMounted, but should probably
18925        // be a different lock in that case.
18926        synchronized (mPackages) {
18927            Log.i(TAG, "Updating external media status from "
18928                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18929                    + (mediaStatus ? "mounted" : "unmounted"));
18930            if (DEBUG_SD_INSTALL)
18931                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18932                        + ", mMediaMounted=" + mMediaMounted);
18933            if (mediaStatus == mMediaMounted) {
18934                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18935                        : 0, -1);
18936                mHandler.sendMessage(msg);
18937                return;
18938            }
18939            mMediaMounted = mediaStatus;
18940        }
18941        // Queue up an async operation since the package installation may take a
18942        // little while.
18943        mHandler.post(new Runnable() {
18944            public void run() {
18945                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18946            }
18947        });
18948    }
18949
18950    /**
18951     * Called by MountService when the initial ASECs to scan are available.
18952     * Should block until all the ASEC containers are finished being scanned.
18953     */
18954    public void scanAvailableAsecs() {
18955        updateExternalMediaStatusInner(true, false, false);
18956    }
18957
18958    /*
18959     * Collect information of applications on external media, map them against
18960     * existing containers and update information based on current mount status.
18961     * Please note that we always have to report status if reportStatus has been
18962     * set to true especially when unloading packages.
18963     */
18964    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18965            boolean externalStorage) {
18966        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18967        int[] uidArr = EmptyArray.INT;
18968
18969        final String[] list = PackageHelper.getSecureContainerList();
18970        if (ArrayUtils.isEmpty(list)) {
18971            Log.i(TAG, "No secure containers found");
18972        } else {
18973            // Process list of secure containers and categorize them
18974            // as active or stale based on their package internal state.
18975
18976            // reader
18977            synchronized (mPackages) {
18978                for (String cid : list) {
18979                    // Leave stages untouched for now; installer service owns them
18980                    if (PackageInstallerService.isStageName(cid)) continue;
18981
18982                    if (DEBUG_SD_INSTALL)
18983                        Log.i(TAG, "Processing container " + cid);
18984                    String pkgName = getAsecPackageName(cid);
18985                    if (pkgName == null) {
18986                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18987                        continue;
18988                    }
18989                    if (DEBUG_SD_INSTALL)
18990                        Log.i(TAG, "Looking for pkg : " + pkgName);
18991
18992                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18993                    if (ps == null) {
18994                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18995                        continue;
18996                    }
18997
18998                    /*
18999                     * Skip packages that are not external if we're unmounting
19000                     * external storage.
19001                     */
19002                    if (externalStorage && !isMounted && !isExternal(ps)) {
19003                        continue;
19004                    }
19005
19006                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19007                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19008                    // The package status is changed only if the code path
19009                    // matches between settings and the container id.
19010                    if (ps.codePathString != null
19011                            && ps.codePathString.startsWith(args.getCodePath())) {
19012                        if (DEBUG_SD_INSTALL) {
19013                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19014                                    + " at code path: " + ps.codePathString);
19015                        }
19016
19017                        // We do have a valid package installed on sdcard
19018                        processCids.put(args, ps.codePathString);
19019                        final int uid = ps.appId;
19020                        if (uid != -1) {
19021                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19022                        }
19023                    } else {
19024                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19025                                + ps.codePathString);
19026                    }
19027                }
19028            }
19029
19030            Arrays.sort(uidArr);
19031        }
19032
19033        // Process packages with valid entries.
19034        if (isMounted) {
19035            if (DEBUG_SD_INSTALL)
19036                Log.i(TAG, "Loading packages");
19037            loadMediaPackages(processCids, uidArr, externalStorage);
19038            startCleaningPackages();
19039            mInstallerService.onSecureContainersAvailable();
19040        } else {
19041            if (DEBUG_SD_INSTALL)
19042                Log.i(TAG, "Unloading packages");
19043            unloadMediaPackages(processCids, uidArr, reportStatus);
19044        }
19045    }
19046
19047    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19048            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19049        final int size = infos.size();
19050        final String[] packageNames = new String[size];
19051        final int[] packageUids = new int[size];
19052        for (int i = 0; i < size; i++) {
19053            final ApplicationInfo info = infos.get(i);
19054            packageNames[i] = info.packageName;
19055            packageUids[i] = info.uid;
19056        }
19057        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19058                finishedReceiver);
19059    }
19060
19061    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19062            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19063        sendResourcesChangedBroadcast(mediaStatus, replacing,
19064                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19065    }
19066
19067    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19068            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19069        int size = pkgList.length;
19070        if (size > 0) {
19071            // Send broadcasts here
19072            Bundle extras = new Bundle();
19073            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19074            if (uidArr != null) {
19075                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19076            }
19077            if (replacing) {
19078                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19079            }
19080            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19081                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19082            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19083        }
19084    }
19085
19086   /*
19087     * Look at potentially valid container ids from processCids If package
19088     * information doesn't match the one on record or package scanning fails,
19089     * the cid is added to list of removeCids. We currently don't delete stale
19090     * containers.
19091     */
19092    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19093            boolean externalStorage) {
19094        ArrayList<String> pkgList = new ArrayList<String>();
19095        Set<AsecInstallArgs> keys = processCids.keySet();
19096
19097        for (AsecInstallArgs args : keys) {
19098            String codePath = processCids.get(args);
19099            if (DEBUG_SD_INSTALL)
19100                Log.i(TAG, "Loading container : " + args.cid);
19101            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19102            try {
19103                // Make sure there are no container errors first.
19104                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19105                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19106                            + " when installing from sdcard");
19107                    continue;
19108                }
19109                // Check code path here.
19110                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19111                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19112                            + " does not match one in settings " + codePath);
19113                    continue;
19114                }
19115                // Parse package
19116                int parseFlags = mDefParseFlags;
19117                if (args.isExternalAsec()) {
19118                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19119                }
19120                if (args.isFwdLocked()) {
19121                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19122                }
19123
19124                synchronized (mInstallLock) {
19125                    PackageParser.Package pkg = null;
19126                    try {
19127                        // Sadly we don't know the package name yet to freeze it
19128                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19129                                SCAN_IGNORE_FROZEN, 0, null);
19130                    } catch (PackageManagerException e) {
19131                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19132                    }
19133                    // Scan the package
19134                    if (pkg != null) {
19135                        /*
19136                         * TODO why is the lock being held? doPostInstall is
19137                         * called in other places without the lock. This needs
19138                         * to be straightened out.
19139                         */
19140                        // writer
19141                        synchronized (mPackages) {
19142                            retCode = PackageManager.INSTALL_SUCCEEDED;
19143                            pkgList.add(pkg.packageName);
19144                            // Post process args
19145                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19146                                    pkg.applicationInfo.uid);
19147                        }
19148                    } else {
19149                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19150                    }
19151                }
19152
19153            } finally {
19154                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19155                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19156                }
19157            }
19158        }
19159        // writer
19160        synchronized (mPackages) {
19161            // If the platform SDK has changed since the last time we booted,
19162            // we need to re-grant app permission to catch any new ones that
19163            // appear. This is really a hack, and means that apps can in some
19164            // cases get permissions that the user didn't initially explicitly
19165            // allow... it would be nice to have some better way to handle
19166            // this situation.
19167            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19168                    : mSettings.getInternalVersion();
19169            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19170                    : StorageManager.UUID_PRIVATE_INTERNAL;
19171
19172            int updateFlags = UPDATE_PERMISSIONS_ALL;
19173            if (ver.sdkVersion != mSdkVersion) {
19174                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19175                        + mSdkVersion + "; regranting permissions for external");
19176                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19177            }
19178            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19179
19180            // Yay, everything is now upgraded
19181            ver.forceCurrent();
19182
19183            // can downgrade to reader
19184            // Persist settings
19185            mSettings.writeLPr();
19186        }
19187        // Send a broadcast to let everyone know we are done processing
19188        if (pkgList.size() > 0) {
19189            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19190        }
19191    }
19192
19193   /*
19194     * Utility method to unload a list of specified containers
19195     */
19196    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19197        // Just unmount all valid containers.
19198        for (AsecInstallArgs arg : cidArgs) {
19199            synchronized (mInstallLock) {
19200                arg.doPostDeleteLI(false);
19201           }
19202       }
19203   }
19204
19205    /*
19206     * Unload packages mounted on external media. This involves deleting package
19207     * data from internal structures, sending broadcasts about disabled packages,
19208     * gc'ing to free up references, unmounting all secure containers
19209     * corresponding to packages on external media, and posting a
19210     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19211     * that we always have to post this message if status has been requested no
19212     * matter what.
19213     */
19214    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19215            final boolean reportStatus) {
19216        if (DEBUG_SD_INSTALL)
19217            Log.i(TAG, "unloading media packages");
19218        ArrayList<String> pkgList = new ArrayList<String>();
19219        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19220        final Set<AsecInstallArgs> keys = processCids.keySet();
19221        for (AsecInstallArgs args : keys) {
19222            String pkgName = args.getPackageName();
19223            if (DEBUG_SD_INSTALL)
19224                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19225            // Delete package internally
19226            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19227            synchronized (mInstallLock) {
19228                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19229                final boolean res;
19230                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19231                        "unloadMediaPackages")) {
19232                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19233                            null);
19234                }
19235                if (res) {
19236                    pkgList.add(pkgName);
19237                } else {
19238                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19239                    failedList.add(args);
19240                }
19241            }
19242        }
19243
19244        // reader
19245        synchronized (mPackages) {
19246            // We didn't update the settings after removing each package;
19247            // write them now for all packages.
19248            mSettings.writeLPr();
19249        }
19250
19251        // We have to absolutely send UPDATED_MEDIA_STATUS only
19252        // after confirming that all the receivers processed the ordered
19253        // broadcast when packages get disabled, force a gc to clean things up.
19254        // and unload all the containers.
19255        if (pkgList.size() > 0) {
19256            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19257                    new IIntentReceiver.Stub() {
19258                public void performReceive(Intent intent, int resultCode, String data,
19259                        Bundle extras, boolean ordered, boolean sticky,
19260                        int sendingUser) throws RemoteException {
19261                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19262                            reportStatus ? 1 : 0, 1, keys);
19263                    mHandler.sendMessage(msg);
19264                }
19265            });
19266        } else {
19267            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19268                    keys);
19269            mHandler.sendMessage(msg);
19270        }
19271    }
19272
19273    private void loadPrivatePackages(final VolumeInfo vol) {
19274        mHandler.post(new Runnable() {
19275            @Override
19276            public void run() {
19277                loadPrivatePackagesInner(vol);
19278            }
19279        });
19280    }
19281
19282    private void loadPrivatePackagesInner(VolumeInfo vol) {
19283        final String volumeUuid = vol.fsUuid;
19284        if (TextUtils.isEmpty(volumeUuid)) {
19285            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19286            return;
19287        }
19288
19289        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19290        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19291        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19292
19293        final VersionInfo ver;
19294        final List<PackageSetting> packages;
19295        synchronized (mPackages) {
19296            ver = mSettings.findOrCreateVersion(volumeUuid);
19297            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19298        }
19299
19300        for (PackageSetting ps : packages) {
19301            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19302            synchronized (mInstallLock) {
19303                final PackageParser.Package pkg;
19304                try {
19305                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19306                    loaded.add(pkg.applicationInfo);
19307
19308                } catch (PackageManagerException e) {
19309                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19310                }
19311
19312                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19313                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19314                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19315                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19316                }
19317            }
19318        }
19319
19320        // Reconcile app data for all started/unlocked users
19321        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19322        final UserManager um = mContext.getSystemService(UserManager.class);
19323        UserManagerInternal umInternal = getUserManagerInternal();
19324        for (UserInfo user : um.getUsers()) {
19325            final int flags;
19326            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19327                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19328            } else if (umInternal.isUserRunning(user.id)) {
19329                flags = StorageManager.FLAG_STORAGE_DE;
19330            } else {
19331                continue;
19332            }
19333
19334            try {
19335                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19336                synchronized (mInstallLock) {
19337                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19338                }
19339            } catch (IllegalStateException e) {
19340                // Device was probably ejected, and we'll process that event momentarily
19341                Slog.w(TAG, "Failed to prepare storage: " + e);
19342            }
19343        }
19344
19345        synchronized (mPackages) {
19346            int updateFlags = UPDATE_PERMISSIONS_ALL;
19347            if (ver.sdkVersion != mSdkVersion) {
19348                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19349                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19350                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19351            }
19352            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19353
19354            // Yay, everything is now upgraded
19355            ver.forceCurrent();
19356
19357            mSettings.writeLPr();
19358        }
19359
19360        for (PackageFreezer freezer : freezers) {
19361            freezer.close();
19362        }
19363
19364        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19365        sendResourcesChangedBroadcast(true, false, loaded, null);
19366    }
19367
19368    private void unloadPrivatePackages(final VolumeInfo vol) {
19369        mHandler.post(new Runnable() {
19370            @Override
19371            public void run() {
19372                unloadPrivatePackagesInner(vol);
19373            }
19374        });
19375    }
19376
19377    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19378        final String volumeUuid = vol.fsUuid;
19379        if (TextUtils.isEmpty(volumeUuid)) {
19380            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19381            return;
19382        }
19383
19384        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19385        synchronized (mInstallLock) {
19386        synchronized (mPackages) {
19387            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19388            for (PackageSetting ps : packages) {
19389                if (ps.pkg == null) continue;
19390
19391                final ApplicationInfo info = ps.pkg.applicationInfo;
19392                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19393                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19394
19395                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19396                        "unloadPrivatePackagesInner")) {
19397                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19398                            false, null)) {
19399                        unloaded.add(info);
19400                    } else {
19401                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19402                    }
19403                }
19404
19405                // Try very hard to release any references to this package
19406                // so we don't risk the system server being killed due to
19407                // open FDs
19408                AttributeCache.instance().removePackage(ps.name);
19409            }
19410
19411            mSettings.writeLPr();
19412        }
19413        }
19414
19415        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19416        sendResourcesChangedBroadcast(false, false, unloaded, null);
19417
19418        // Try very hard to release any references to this path so we don't risk
19419        // the system server being killed due to open FDs
19420        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19421
19422        for (int i = 0; i < 3; i++) {
19423            System.gc();
19424            System.runFinalization();
19425        }
19426    }
19427
19428    /**
19429     * Prepare storage areas for given user on all mounted devices.
19430     */
19431    void prepareUserData(int userId, int userSerial, int flags) {
19432        synchronized (mInstallLock) {
19433            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19434            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19435                final String volumeUuid = vol.getFsUuid();
19436                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19437            }
19438        }
19439    }
19440
19441    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19442            boolean allowRecover) {
19443        // Prepare storage and verify that serial numbers are consistent; if
19444        // there's a mismatch we need to destroy to avoid leaking data
19445        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19446        try {
19447            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19448
19449            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19450                UserManagerService.enforceSerialNumber(
19451                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19452                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19453                    UserManagerService.enforceSerialNumber(
19454                            Environment.getDataSystemDeDirectory(userId), userSerial);
19455                }
19456            }
19457            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19458                UserManagerService.enforceSerialNumber(
19459                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19460                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19461                    UserManagerService.enforceSerialNumber(
19462                            Environment.getDataSystemCeDirectory(userId), userSerial);
19463                }
19464            }
19465
19466            synchronized (mInstallLock) {
19467                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19468            }
19469        } catch (Exception e) {
19470            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19471                    + " because we failed to prepare: " + e);
19472            destroyUserDataLI(volumeUuid, userId,
19473                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19474
19475            if (allowRecover) {
19476                // Try one last time; if we fail again we're really in trouble
19477                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19478            }
19479        }
19480    }
19481
19482    /**
19483     * Destroy storage areas for given user on all mounted devices.
19484     */
19485    void destroyUserData(int userId, int flags) {
19486        synchronized (mInstallLock) {
19487            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19488            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19489                final String volumeUuid = vol.getFsUuid();
19490                destroyUserDataLI(volumeUuid, userId, flags);
19491            }
19492        }
19493    }
19494
19495    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19496        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19497        try {
19498            // Clean up app data, profile data, and media data
19499            mInstaller.destroyUserData(volumeUuid, userId, flags);
19500
19501            // Clean up system data
19502            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19503                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19504                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19505                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19506                }
19507                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19508                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19509                }
19510            }
19511
19512            // Data with special labels is now gone, so finish the job
19513            storage.destroyUserStorage(volumeUuid, userId, flags);
19514
19515        } catch (Exception e) {
19516            logCriticalInfo(Log.WARN,
19517                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19518        }
19519    }
19520
19521    /**
19522     * Examine all users present on given mounted volume, and destroy data
19523     * belonging to users that are no longer valid, or whose user ID has been
19524     * recycled.
19525     */
19526    private void reconcileUsers(String volumeUuid) {
19527        final List<File> files = new ArrayList<>();
19528        Collections.addAll(files, FileUtils
19529                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19530        Collections.addAll(files, FileUtils
19531                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19532        Collections.addAll(files, FileUtils
19533                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19534        Collections.addAll(files, FileUtils
19535                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19536        for (File file : files) {
19537            if (!file.isDirectory()) continue;
19538
19539            final int userId;
19540            final UserInfo info;
19541            try {
19542                userId = Integer.parseInt(file.getName());
19543                info = sUserManager.getUserInfo(userId);
19544            } catch (NumberFormatException e) {
19545                Slog.w(TAG, "Invalid user directory " + file);
19546                continue;
19547            }
19548
19549            boolean destroyUser = false;
19550            if (info == null) {
19551                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19552                        + " because no matching user was found");
19553                destroyUser = true;
19554            } else if (!mOnlyCore) {
19555                try {
19556                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19557                } catch (IOException e) {
19558                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19559                            + " because we failed to enforce serial number: " + e);
19560                    destroyUser = true;
19561                }
19562            }
19563
19564            if (destroyUser) {
19565                synchronized (mInstallLock) {
19566                    destroyUserDataLI(volumeUuid, userId,
19567                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19568                }
19569            }
19570        }
19571    }
19572
19573    private void assertPackageKnown(String volumeUuid, String packageName)
19574            throws PackageManagerException {
19575        synchronized (mPackages) {
19576            final PackageSetting ps = mSettings.mPackages.get(packageName);
19577            if (ps == null) {
19578                throw new PackageManagerException("Package " + packageName + " is unknown");
19579            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19580                throw new PackageManagerException(
19581                        "Package " + packageName + " found on unknown volume " + volumeUuid
19582                                + "; expected volume " + ps.volumeUuid);
19583            }
19584        }
19585    }
19586
19587    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19588            throws PackageManagerException {
19589        synchronized (mPackages) {
19590            final PackageSetting ps = mSettings.mPackages.get(packageName);
19591            if (ps == null) {
19592                throw new PackageManagerException("Package " + packageName + " is unknown");
19593            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19594                throw new PackageManagerException(
19595                        "Package " + packageName + " found on unknown volume " + volumeUuid
19596                                + "; expected volume " + ps.volumeUuid);
19597            } else if (!ps.getInstalled(userId)) {
19598                throw new PackageManagerException(
19599                        "Package " + packageName + " not installed for user " + userId);
19600            }
19601        }
19602    }
19603
19604    /**
19605     * Examine all apps present on given mounted volume, and destroy apps that
19606     * aren't expected, either due to uninstallation or reinstallation on
19607     * another volume.
19608     */
19609    private void reconcileApps(String volumeUuid) {
19610        final File[] files = FileUtils
19611                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19612        for (File file : files) {
19613            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19614                    && !PackageInstallerService.isStageName(file.getName());
19615            if (!isPackage) {
19616                // Ignore entries which are not packages
19617                continue;
19618            }
19619
19620            try {
19621                final PackageLite pkg = PackageParser.parsePackageLite(file,
19622                        PackageParser.PARSE_MUST_BE_APK);
19623                assertPackageKnown(volumeUuid, pkg.packageName);
19624
19625            } catch (PackageParserException | PackageManagerException e) {
19626                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19627                synchronized (mInstallLock) {
19628                    removeCodePathLI(file);
19629                }
19630            }
19631        }
19632    }
19633
19634    /**
19635     * Reconcile all app data for the given user.
19636     * <p>
19637     * Verifies that directories exist and that ownership and labeling is
19638     * correct for all installed apps on all mounted volumes.
19639     */
19640    void reconcileAppsData(int userId, int flags) {
19641        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19642        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19643            final String volumeUuid = vol.getFsUuid();
19644            synchronized (mInstallLock) {
19645                reconcileAppsDataLI(volumeUuid, userId, flags);
19646            }
19647        }
19648    }
19649
19650    /**
19651     * Reconcile all app data on given mounted volume.
19652     * <p>
19653     * Destroys app data that isn't expected, either due to uninstallation or
19654     * reinstallation on another volume.
19655     * <p>
19656     * Verifies that directories exist and that ownership and labeling is
19657     * correct for all installed apps.
19658     */
19659    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19660        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19661                + Integer.toHexString(flags));
19662
19663        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19664        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19665
19666        boolean restoreconNeeded = false;
19667
19668        // First look for stale data that doesn't belong, and check if things
19669        // have changed since we did our last restorecon
19670        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19671            if (StorageManager.isFileEncryptedNativeOrEmulated()
19672                    && !StorageManager.isUserKeyUnlocked(userId)) {
19673                throw new RuntimeException(
19674                        "Yikes, someone asked us to reconcile CE storage while " + userId
19675                                + " was still locked; this would have caused massive data loss!");
19676            }
19677
19678            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19679
19680            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19681            for (File file : files) {
19682                final String packageName = file.getName();
19683                try {
19684                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19685                } catch (PackageManagerException e) {
19686                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19687                    try {
19688                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19689                                StorageManager.FLAG_STORAGE_CE, 0);
19690                    } catch (InstallerException e2) {
19691                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19692                    }
19693                }
19694            }
19695        }
19696        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19697            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19698
19699            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19700            for (File file : files) {
19701                final String packageName = file.getName();
19702                try {
19703                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19704                } catch (PackageManagerException e) {
19705                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19706                    try {
19707                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19708                                StorageManager.FLAG_STORAGE_DE, 0);
19709                    } catch (InstallerException e2) {
19710                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19711                    }
19712                }
19713            }
19714        }
19715
19716        // Ensure that data directories are ready to roll for all packages
19717        // installed for this volume and user
19718        final List<PackageSetting> packages;
19719        synchronized (mPackages) {
19720            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19721        }
19722        int preparedCount = 0;
19723        for (PackageSetting ps : packages) {
19724            final String packageName = ps.name;
19725            if (ps.pkg == null) {
19726                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19727                // TODO: might be due to legacy ASEC apps; we should circle back
19728                // and reconcile again once they're scanned
19729                continue;
19730            }
19731
19732            if (ps.getInstalled(userId)) {
19733                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19734
19735                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19736                    // We may have just shuffled around app data directories, so
19737                    // prepare them one more time
19738                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19739                }
19740
19741                preparedCount++;
19742            }
19743        }
19744
19745        if (restoreconNeeded) {
19746            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19747                SELinuxMMAC.setRestoreconDone(ceDir);
19748            }
19749            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19750                SELinuxMMAC.setRestoreconDone(deDir);
19751            }
19752        }
19753
19754        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19755                + " packages; restoreconNeeded was " + restoreconNeeded);
19756    }
19757
19758    /**
19759     * Prepare app data for the given app just after it was installed or
19760     * upgraded. This method carefully only touches users that it's installed
19761     * for, and it forces a restorecon to handle any seinfo changes.
19762     * <p>
19763     * Verifies that directories exist and that ownership and labeling is
19764     * correct for all installed apps. If there is an ownership mismatch, it
19765     * will try recovering system apps by wiping data; third-party app data is
19766     * left intact.
19767     * <p>
19768     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19769     */
19770    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19771        final PackageSetting ps;
19772        synchronized (mPackages) {
19773            ps = mSettings.mPackages.get(pkg.packageName);
19774            mSettings.writeKernelMappingLPr(ps);
19775        }
19776
19777        final UserManager um = mContext.getSystemService(UserManager.class);
19778        UserManagerInternal umInternal = getUserManagerInternal();
19779        for (UserInfo user : um.getUsers()) {
19780            final int flags;
19781            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19782                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19783            } else if (umInternal.isUserRunning(user.id)) {
19784                flags = StorageManager.FLAG_STORAGE_DE;
19785            } else {
19786                continue;
19787            }
19788
19789            if (ps.getInstalled(user.id)) {
19790                // Whenever an app changes, force a restorecon of its data
19791                // TODO: when user data is locked, mark that we're still dirty
19792                prepareAppDataLIF(pkg, user.id, flags, true);
19793            }
19794        }
19795    }
19796
19797    /**
19798     * Prepare app data for the given app.
19799     * <p>
19800     * Verifies that directories exist and that ownership and labeling is
19801     * correct for all installed apps. If there is an ownership mismatch, this
19802     * will try recovering system apps by wiping data; third-party app data is
19803     * left intact.
19804     */
19805    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19806            boolean restoreconNeeded) {
19807        if (pkg == null) {
19808            Slog.wtf(TAG, "Package was null!", new Throwable());
19809            return;
19810        }
19811        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19812        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19813        for (int i = 0; i < childCount; i++) {
19814            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19815        }
19816    }
19817
19818    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19819            boolean restoreconNeeded) {
19820        if (DEBUG_APP_DATA) {
19821            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19822                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19823        }
19824
19825        final String volumeUuid = pkg.volumeUuid;
19826        final String packageName = pkg.packageName;
19827        final ApplicationInfo app = pkg.applicationInfo;
19828        final int appId = UserHandle.getAppId(app.uid);
19829
19830        Preconditions.checkNotNull(app.seinfo);
19831
19832        try {
19833            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19834                    appId, app.seinfo, app.targetSdkVersion);
19835        } catch (InstallerException e) {
19836            if (app.isSystemApp()) {
19837                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19838                        + ", but trying to recover: " + e);
19839                destroyAppDataLeafLIF(pkg, userId, flags);
19840                try {
19841                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19842                            appId, app.seinfo, app.targetSdkVersion);
19843                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19844                } catch (InstallerException e2) {
19845                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19846                }
19847            } else {
19848                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19849            }
19850        }
19851
19852        if (restoreconNeeded) {
19853            try {
19854                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19855                        app.seinfo);
19856            } catch (InstallerException e) {
19857                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19858            }
19859        }
19860
19861        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19862            try {
19863                // CE storage is unlocked right now, so read out the inode and
19864                // remember for use later when it's locked
19865                // TODO: mark this structure as dirty so we persist it!
19866                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19867                        StorageManager.FLAG_STORAGE_CE);
19868                synchronized (mPackages) {
19869                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19870                    if (ps != null) {
19871                        ps.setCeDataInode(ceDataInode, userId);
19872                    }
19873                }
19874            } catch (InstallerException e) {
19875                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19876            }
19877        }
19878
19879        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19880    }
19881
19882    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19883        if (pkg == null) {
19884            Slog.wtf(TAG, "Package was null!", new Throwable());
19885            return;
19886        }
19887        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19888        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19889        for (int i = 0; i < childCount; i++) {
19890            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19891        }
19892    }
19893
19894    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19895        final String volumeUuid = pkg.volumeUuid;
19896        final String packageName = pkg.packageName;
19897        final ApplicationInfo app = pkg.applicationInfo;
19898
19899        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19900            // Create a native library symlink only if we have native libraries
19901            // and if the native libraries are 32 bit libraries. We do not provide
19902            // this symlink for 64 bit libraries.
19903            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19904                final String nativeLibPath = app.nativeLibraryDir;
19905                try {
19906                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19907                            nativeLibPath, userId);
19908                } catch (InstallerException e) {
19909                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19910                }
19911            }
19912        }
19913    }
19914
19915    /**
19916     * For system apps on non-FBE devices, this method migrates any existing
19917     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19918     * requested by the app.
19919     */
19920    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19921        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19922                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19923            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19924                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19925            try {
19926                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19927                        storageTarget);
19928            } catch (InstallerException e) {
19929                logCriticalInfo(Log.WARN,
19930                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19931            }
19932            return true;
19933        } else {
19934            return false;
19935        }
19936    }
19937
19938    public PackageFreezer freezePackage(String packageName, String killReason) {
19939        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19940    }
19941
19942    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19943        return new PackageFreezer(packageName, userId, killReason);
19944    }
19945
19946    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19947            String killReason) {
19948        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19949    }
19950
19951    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19952            String killReason) {
19953        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19954            return new PackageFreezer();
19955        } else {
19956            return freezePackage(packageName, userId, killReason);
19957        }
19958    }
19959
19960    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19961            String killReason) {
19962        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19963    }
19964
19965    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19966            String killReason) {
19967        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19968            return new PackageFreezer();
19969        } else {
19970            return freezePackage(packageName, userId, killReason);
19971        }
19972    }
19973
19974    /**
19975     * Class that freezes and kills the given package upon creation, and
19976     * unfreezes it upon closing. This is typically used when doing surgery on
19977     * app code/data to prevent the app from running while you're working.
19978     */
19979    private class PackageFreezer implements AutoCloseable {
19980        private final String mPackageName;
19981        private final PackageFreezer[] mChildren;
19982
19983        private final boolean mWeFroze;
19984
19985        private final AtomicBoolean mClosed = new AtomicBoolean();
19986        private final CloseGuard mCloseGuard = CloseGuard.get();
19987
19988        /**
19989         * Create and return a stub freezer that doesn't actually do anything,
19990         * typically used when someone requested
19991         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19992         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19993         */
19994        public PackageFreezer() {
19995            mPackageName = null;
19996            mChildren = null;
19997            mWeFroze = false;
19998            mCloseGuard.open("close");
19999        }
20000
20001        public PackageFreezer(String packageName, int userId, String killReason) {
20002            synchronized (mPackages) {
20003                mPackageName = packageName;
20004                mWeFroze = mFrozenPackages.add(mPackageName);
20005
20006                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20007                if (ps != null) {
20008                    killApplication(ps.name, ps.appId, userId, killReason);
20009                }
20010
20011                final PackageParser.Package p = mPackages.get(packageName);
20012                if (p != null && p.childPackages != null) {
20013                    final int N = p.childPackages.size();
20014                    mChildren = new PackageFreezer[N];
20015                    for (int i = 0; i < N; i++) {
20016                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20017                                userId, killReason);
20018                    }
20019                } else {
20020                    mChildren = null;
20021                }
20022            }
20023            mCloseGuard.open("close");
20024        }
20025
20026        @Override
20027        protected void finalize() throws Throwable {
20028            try {
20029                mCloseGuard.warnIfOpen();
20030                close();
20031            } finally {
20032                super.finalize();
20033            }
20034        }
20035
20036        @Override
20037        public void close() {
20038            mCloseGuard.close();
20039            if (mClosed.compareAndSet(false, true)) {
20040                synchronized (mPackages) {
20041                    if (mWeFroze) {
20042                        mFrozenPackages.remove(mPackageName);
20043                    }
20044
20045                    if (mChildren != null) {
20046                        for (PackageFreezer freezer : mChildren) {
20047                            freezer.close();
20048                        }
20049                    }
20050                }
20051            }
20052        }
20053    }
20054
20055    /**
20056     * Verify that given package is currently frozen.
20057     */
20058    private void checkPackageFrozen(String packageName) {
20059        synchronized (mPackages) {
20060            if (!mFrozenPackages.contains(packageName)) {
20061                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20062            }
20063        }
20064    }
20065
20066    @Override
20067    public int movePackage(final String packageName, final String volumeUuid) {
20068        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20069
20070        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20071        final int moveId = mNextMoveId.getAndIncrement();
20072        mHandler.post(new Runnable() {
20073            @Override
20074            public void run() {
20075                try {
20076                    movePackageInternal(packageName, volumeUuid, moveId, user);
20077                } catch (PackageManagerException e) {
20078                    Slog.w(TAG, "Failed to move " + packageName, e);
20079                    mMoveCallbacks.notifyStatusChanged(moveId,
20080                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20081                }
20082            }
20083        });
20084        return moveId;
20085    }
20086
20087    private void movePackageInternal(final String packageName, final String volumeUuid,
20088            final int moveId, UserHandle user) throws PackageManagerException {
20089        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20090        final PackageManager pm = mContext.getPackageManager();
20091
20092        final boolean currentAsec;
20093        final String currentVolumeUuid;
20094        final File codeFile;
20095        final String installerPackageName;
20096        final String packageAbiOverride;
20097        final int appId;
20098        final String seinfo;
20099        final String label;
20100        final int targetSdkVersion;
20101        final PackageFreezer freezer;
20102        final int[] installedUserIds;
20103
20104        // reader
20105        synchronized (mPackages) {
20106            final PackageParser.Package pkg = mPackages.get(packageName);
20107            final PackageSetting ps = mSettings.mPackages.get(packageName);
20108            if (pkg == null || ps == null) {
20109                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20110            }
20111
20112            if (pkg.applicationInfo.isSystemApp()) {
20113                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20114                        "Cannot move system application");
20115            }
20116
20117            if (pkg.applicationInfo.isExternalAsec()) {
20118                currentAsec = true;
20119                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20120            } else if (pkg.applicationInfo.isForwardLocked()) {
20121                currentAsec = true;
20122                currentVolumeUuid = "forward_locked";
20123            } else {
20124                currentAsec = false;
20125                currentVolumeUuid = ps.volumeUuid;
20126
20127                final File probe = new File(pkg.codePath);
20128                final File probeOat = new File(probe, "oat");
20129                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20130                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20131                            "Move only supported for modern cluster style installs");
20132                }
20133            }
20134
20135            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20136                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20137                        "Package already moved to " + volumeUuid);
20138            }
20139            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20140                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20141                        "Device admin cannot be moved");
20142            }
20143
20144            if (mFrozenPackages.contains(packageName)) {
20145                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20146                        "Failed to move already frozen package");
20147            }
20148
20149            codeFile = new File(pkg.codePath);
20150            installerPackageName = ps.installerPackageName;
20151            packageAbiOverride = ps.cpuAbiOverrideString;
20152            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20153            seinfo = pkg.applicationInfo.seinfo;
20154            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20155            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20156            freezer = freezePackage(packageName, "movePackageInternal");
20157            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20158        }
20159
20160        final Bundle extras = new Bundle();
20161        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20162        extras.putString(Intent.EXTRA_TITLE, label);
20163        mMoveCallbacks.notifyCreated(moveId, extras);
20164
20165        int installFlags;
20166        final boolean moveCompleteApp;
20167        final File measurePath;
20168
20169        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20170            installFlags = INSTALL_INTERNAL;
20171            moveCompleteApp = !currentAsec;
20172            measurePath = Environment.getDataAppDirectory(volumeUuid);
20173        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20174            installFlags = INSTALL_EXTERNAL;
20175            moveCompleteApp = false;
20176            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20177        } else {
20178            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20179            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20180                    || !volume.isMountedWritable()) {
20181                freezer.close();
20182                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20183                        "Move location not mounted private volume");
20184            }
20185
20186            Preconditions.checkState(!currentAsec);
20187
20188            installFlags = INSTALL_INTERNAL;
20189            moveCompleteApp = true;
20190            measurePath = Environment.getDataAppDirectory(volumeUuid);
20191        }
20192
20193        final PackageStats stats = new PackageStats(null, -1);
20194        synchronized (mInstaller) {
20195            for (int userId : installedUserIds) {
20196                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20197                    freezer.close();
20198                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20199                            "Failed to measure package size");
20200                }
20201            }
20202        }
20203
20204        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20205                + stats.dataSize);
20206
20207        final long startFreeBytes = measurePath.getFreeSpace();
20208        final long sizeBytes;
20209        if (moveCompleteApp) {
20210            sizeBytes = stats.codeSize + stats.dataSize;
20211        } else {
20212            sizeBytes = stats.codeSize;
20213        }
20214
20215        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20216            freezer.close();
20217            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20218                    "Not enough free space to move");
20219        }
20220
20221        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20222
20223        final CountDownLatch installedLatch = new CountDownLatch(1);
20224        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20225            @Override
20226            public void onUserActionRequired(Intent intent) throws RemoteException {
20227                throw new IllegalStateException();
20228            }
20229
20230            @Override
20231            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20232                    Bundle extras) throws RemoteException {
20233                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20234                        + PackageManager.installStatusToString(returnCode, msg));
20235
20236                installedLatch.countDown();
20237                freezer.close();
20238
20239                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20240                switch (status) {
20241                    case PackageInstaller.STATUS_SUCCESS:
20242                        mMoveCallbacks.notifyStatusChanged(moveId,
20243                                PackageManager.MOVE_SUCCEEDED);
20244                        break;
20245                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20246                        mMoveCallbacks.notifyStatusChanged(moveId,
20247                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20248                        break;
20249                    default:
20250                        mMoveCallbacks.notifyStatusChanged(moveId,
20251                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20252                        break;
20253                }
20254            }
20255        };
20256
20257        final MoveInfo move;
20258        if (moveCompleteApp) {
20259            // Kick off a thread to report progress estimates
20260            new Thread() {
20261                @Override
20262                public void run() {
20263                    while (true) {
20264                        try {
20265                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20266                                break;
20267                            }
20268                        } catch (InterruptedException ignored) {
20269                        }
20270
20271                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20272                        final int progress = 10 + (int) MathUtils.constrain(
20273                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20274                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20275                    }
20276                }
20277            }.start();
20278
20279            final String dataAppName = codeFile.getName();
20280            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20281                    dataAppName, appId, seinfo, targetSdkVersion);
20282        } else {
20283            move = null;
20284        }
20285
20286        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20287
20288        final Message msg = mHandler.obtainMessage(INIT_COPY);
20289        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20290        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20291                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20292                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20293        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20294        msg.obj = params;
20295
20296        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20297                System.identityHashCode(msg.obj));
20298        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20299                System.identityHashCode(msg.obj));
20300
20301        mHandler.sendMessage(msg);
20302    }
20303
20304    @Override
20305    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20306        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20307
20308        final int realMoveId = mNextMoveId.getAndIncrement();
20309        final Bundle extras = new Bundle();
20310        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20311        mMoveCallbacks.notifyCreated(realMoveId, extras);
20312
20313        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20314            @Override
20315            public void onCreated(int moveId, Bundle extras) {
20316                // Ignored
20317            }
20318
20319            @Override
20320            public void onStatusChanged(int moveId, int status, long estMillis) {
20321                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20322            }
20323        };
20324
20325        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20326        storage.setPrimaryStorageUuid(volumeUuid, callback);
20327        return realMoveId;
20328    }
20329
20330    @Override
20331    public int getMoveStatus(int moveId) {
20332        mContext.enforceCallingOrSelfPermission(
20333                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20334        return mMoveCallbacks.mLastStatus.get(moveId);
20335    }
20336
20337    @Override
20338    public void registerMoveCallback(IPackageMoveObserver callback) {
20339        mContext.enforceCallingOrSelfPermission(
20340                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20341        mMoveCallbacks.register(callback);
20342    }
20343
20344    @Override
20345    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20346        mContext.enforceCallingOrSelfPermission(
20347                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20348        mMoveCallbacks.unregister(callback);
20349    }
20350
20351    @Override
20352    public boolean setInstallLocation(int loc) {
20353        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20354                null);
20355        if (getInstallLocation() == loc) {
20356            return true;
20357        }
20358        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20359                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20360            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20361                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20362            return true;
20363        }
20364        return false;
20365   }
20366
20367    @Override
20368    public int getInstallLocation() {
20369        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20370                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20371                PackageHelper.APP_INSTALL_AUTO);
20372    }
20373
20374    /** Called by UserManagerService */
20375    void cleanUpUser(UserManagerService userManager, int userHandle) {
20376        synchronized (mPackages) {
20377            mDirtyUsers.remove(userHandle);
20378            mUserNeedsBadging.delete(userHandle);
20379            mSettings.removeUserLPw(userHandle);
20380            mPendingBroadcasts.remove(userHandle);
20381            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20382            removeUnusedPackagesLPw(userManager, userHandle);
20383        }
20384    }
20385
20386    /**
20387     * We're removing userHandle and would like to remove any downloaded packages
20388     * that are no longer in use by any other user.
20389     * @param userHandle the user being removed
20390     */
20391    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20392        final boolean DEBUG_CLEAN_APKS = false;
20393        int [] users = userManager.getUserIds();
20394        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20395        while (psit.hasNext()) {
20396            PackageSetting ps = psit.next();
20397            if (ps.pkg == null) {
20398                continue;
20399            }
20400            final String packageName = ps.pkg.packageName;
20401            // Skip over if system app
20402            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20403                continue;
20404            }
20405            if (DEBUG_CLEAN_APKS) {
20406                Slog.i(TAG, "Checking package " + packageName);
20407            }
20408            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20409            if (keep) {
20410                if (DEBUG_CLEAN_APKS) {
20411                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20412                }
20413            } else {
20414                for (int i = 0; i < users.length; i++) {
20415                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20416                        keep = true;
20417                        if (DEBUG_CLEAN_APKS) {
20418                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20419                                    + users[i]);
20420                        }
20421                        break;
20422                    }
20423                }
20424            }
20425            if (!keep) {
20426                if (DEBUG_CLEAN_APKS) {
20427                    Slog.i(TAG, "  Removing package " + packageName);
20428                }
20429                mHandler.post(new Runnable() {
20430                    public void run() {
20431                        deletePackageX(packageName, userHandle, 0);
20432                    } //end run
20433                });
20434            }
20435        }
20436    }
20437
20438    /** Called by UserManagerService */
20439    void createNewUser(int userId) {
20440        synchronized (mInstallLock) {
20441            mSettings.createNewUserLI(this, mInstaller, userId);
20442        }
20443        synchronized (mPackages) {
20444            scheduleWritePackageRestrictionsLocked(userId);
20445            scheduleWritePackageListLocked(userId);
20446            applyFactoryDefaultBrowserLPw(userId);
20447            primeDomainVerificationsLPw(userId);
20448        }
20449    }
20450
20451    void onBeforeUserStartUninitialized(final int userId) {
20452        synchronized (mPackages) {
20453            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20454                return;
20455            }
20456        }
20457        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20458        // If permission review for legacy apps is required, we represent
20459        // dagerous permissions for such apps as always granted runtime
20460        // permissions to keep per user flag state whether review is needed.
20461        // Hence, if a new user is added we have to propagate dangerous
20462        // permission grants for these legacy apps.
20463        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20464            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20465                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20466        }
20467    }
20468
20469    @Override
20470    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20471        mContext.enforceCallingOrSelfPermission(
20472                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20473                "Only package verification agents can read the verifier device identity");
20474
20475        synchronized (mPackages) {
20476            return mSettings.getVerifierDeviceIdentityLPw();
20477        }
20478    }
20479
20480    @Override
20481    public void setPermissionEnforced(String permission, boolean enforced) {
20482        // TODO: Now that we no longer change GID for storage, this should to away.
20483        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20484                "setPermissionEnforced");
20485        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20486            synchronized (mPackages) {
20487                if (mSettings.mReadExternalStorageEnforced == null
20488                        || mSettings.mReadExternalStorageEnforced != enforced) {
20489                    mSettings.mReadExternalStorageEnforced = enforced;
20490                    mSettings.writeLPr();
20491                }
20492            }
20493            // kill any non-foreground processes so we restart them and
20494            // grant/revoke the GID.
20495            final IActivityManager am = ActivityManagerNative.getDefault();
20496            if (am != null) {
20497                final long token = Binder.clearCallingIdentity();
20498                try {
20499                    am.killProcessesBelowForeground("setPermissionEnforcement");
20500                } catch (RemoteException e) {
20501                } finally {
20502                    Binder.restoreCallingIdentity(token);
20503                }
20504            }
20505        } else {
20506            throw new IllegalArgumentException("No selective enforcement for " + permission);
20507        }
20508    }
20509
20510    @Override
20511    @Deprecated
20512    public boolean isPermissionEnforced(String permission) {
20513        return true;
20514    }
20515
20516    @Override
20517    public boolean isStorageLow() {
20518        final long token = Binder.clearCallingIdentity();
20519        try {
20520            final DeviceStorageMonitorInternal
20521                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20522            if (dsm != null) {
20523                return dsm.isMemoryLow();
20524            } else {
20525                return false;
20526            }
20527        } finally {
20528            Binder.restoreCallingIdentity(token);
20529        }
20530    }
20531
20532    @Override
20533    public IPackageInstaller getPackageInstaller() {
20534        return mInstallerService;
20535    }
20536
20537    private boolean userNeedsBadging(int userId) {
20538        int index = mUserNeedsBadging.indexOfKey(userId);
20539        if (index < 0) {
20540            final UserInfo userInfo;
20541            final long token = Binder.clearCallingIdentity();
20542            try {
20543                userInfo = sUserManager.getUserInfo(userId);
20544            } finally {
20545                Binder.restoreCallingIdentity(token);
20546            }
20547            final boolean b;
20548            if (userInfo != null && userInfo.isManagedProfile()) {
20549                b = true;
20550            } else {
20551                b = false;
20552            }
20553            mUserNeedsBadging.put(userId, b);
20554            return b;
20555        }
20556        return mUserNeedsBadging.valueAt(index);
20557    }
20558
20559    @Override
20560    public KeySet getKeySetByAlias(String packageName, String alias) {
20561        if (packageName == null || alias == null) {
20562            return null;
20563        }
20564        synchronized(mPackages) {
20565            final PackageParser.Package pkg = mPackages.get(packageName);
20566            if (pkg == null) {
20567                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20568                throw new IllegalArgumentException("Unknown package: " + packageName);
20569            }
20570            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20571            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20572        }
20573    }
20574
20575    @Override
20576    public KeySet getSigningKeySet(String packageName) {
20577        if (packageName == null) {
20578            return null;
20579        }
20580        synchronized(mPackages) {
20581            final PackageParser.Package pkg = mPackages.get(packageName);
20582            if (pkg == null) {
20583                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20584                throw new IllegalArgumentException("Unknown package: " + packageName);
20585            }
20586            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20587                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20588                throw new SecurityException("May not access signing KeySet of other apps.");
20589            }
20590            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20591            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20592        }
20593    }
20594
20595    @Override
20596    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20597        if (packageName == null || ks == null) {
20598            return false;
20599        }
20600        synchronized(mPackages) {
20601            final PackageParser.Package pkg = mPackages.get(packageName);
20602            if (pkg == null) {
20603                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20604                throw new IllegalArgumentException("Unknown package: " + packageName);
20605            }
20606            IBinder ksh = ks.getToken();
20607            if (ksh instanceof KeySetHandle) {
20608                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20609                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20610            }
20611            return false;
20612        }
20613    }
20614
20615    @Override
20616    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20617        if (packageName == null || ks == null) {
20618            return false;
20619        }
20620        synchronized(mPackages) {
20621            final PackageParser.Package pkg = mPackages.get(packageName);
20622            if (pkg == null) {
20623                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20624                throw new IllegalArgumentException("Unknown package: " + packageName);
20625            }
20626            IBinder ksh = ks.getToken();
20627            if (ksh instanceof KeySetHandle) {
20628                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20629                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20630            }
20631            return false;
20632        }
20633    }
20634
20635    private void deletePackageIfUnusedLPr(final String packageName) {
20636        PackageSetting ps = mSettings.mPackages.get(packageName);
20637        if (ps == null) {
20638            return;
20639        }
20640        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20641            // TODO Implement atomic delete if package is unused
20642            // It is currently possible that the package will be deleted even if it is installed
20643            // after this method returns.
20644            mHandler.post(new Runnable() {
20645                public void run() {
20646                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20647                }
20648            });
20649        }
20650    }
20651
20652    /**
20653     * Check and throw if the given before/after packages would be considered a
20654     * downgrade.
20655     */
20656    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20657            throws PackageManagerException {
20658        if (after.versionCode < before.mVersionCode) {
20659            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20660                    "Update version code " + after.versionCode + " is older than current "
20661                    + before.mVersionCode);
20662        } else if (after.versionCode == before.mVersionCode) {
20663            if (after.baseRevisionCode < before.baseRevisionCode) {
20664                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20665                        "Update base revision code " + after.baseRevisionCode
20666                        + " is older than current " + before.baseRevisionCode);
20667            }
20668
20669            if (!ArrayUtils.isEmpty(after.splitNames)) {
20670                for (int i = 0; i < after.splitNames.length; i++) {
20671                    final String splitName = after.splitNames[i];
20672                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20673                    if (j != -1) {
20674                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20675                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20676                                    "Update split " + splitName + " revision code "
20677                                    + after.splitRevisionCodes[i] + " is older than current "
20678                                    + before.splitRevisionCodes[j]);
20679                        }
20680                    }
20681                }
20682            }
20683        }
20684    }
20685
20686    private static class MoveCallbacks extends Handler {
20687        private static final int MSG_CREATED = 1;
20688        private static final int MSG_STATUS_CHANGED = 2;
20689
20690        private final RemoteCallbackList<IPackageMoveObserver>
20691                mCallbacks = new RemoteCallbackList<>();
20692
20693        private final SparseIntArray mLastStatus = new SparseIntArray();
20694
20695        public MoveCallbacks(Looper looper) {
20696            super(looper);
20697        }
20698
20699        public void register(IPackageMoveObserver callback) {
20700            mCallbacks.register(callback);
20701        }
20702
20703        public void unregister(IPackageMoveObserver callback) {
20704            mCallbacks.unregister(callback);
20705        }
20706
20707        @Override
20708        public void handleMessage(Message msg) {
20709            final SomeArgs args = (SomeArgs) msg.obj;
20710            final int n = mCallbacks.beginBroadcast();
20711            for (int i = 0; i < n; i++) {
20712                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20713                try {
20714                    invokeCallback(callback, msg.what, args);
20715                } catch (RemoteException ignored) {
20716                }
20717            }
20718            mCallbacks.finishBroadcast();
20719            args.recycle();
20720        }
20721
20722        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20723                throws RemoteException {
20724            switch (what) {
20725                case MSG_CREATED: {
20726                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20727                    break;
20728                }
20729                case MSG_STATUS_CHANGED: {
20730                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20731                    break;
20732                }
20733            }
20734        }
20735
20736        private void notifyCreated(int moveId, Bundle extras) {
20737            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20738
20739            final SomeArgs args = SomeArgs.obtain();
20740            args.argi1 = moveId;
20741            args.arg2 = extras;
20742            obtainMessage(MSG_CREATED, args).sendToTarget();
20743        }
20744
20745        private void notifyStatusChanged(int moveId, int status) {
20746            notifyStatusChanged(moveId, status, -1);
20747        }
20748
20749        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20750            Slog.v(TAG, "Move " + moveId + " status " + status);
20751
20752            final SomeArgs args = SomeArgs.obtain();
20753            args.argi1 = moveId;
20754            args.argi2 = status;
20755            args.arg3 = estMillis;
20756            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20757
20758            synchronized (mLastStatus) {
20759                mLastStatus.put(moveId, status);
20760            }
20761        }
20762    }
20763
20764    private final static class OnPermissionChangeListeners extends Handler {
20765        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20766
20767        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20768                new RemoteCallbackList<>();
20769
20770        public OnPermissionChangeListeners(Looper looper) {
20771            super(looper);
20772        }
20773
20774        @Override
20775        public void handleMessage(Message msg) {
20776            switch (msg.what) {
20777                case MSG_ON_PERMISSIONS_CHANGED: {
20778                    final int uid = msg.arg1;
20779                    handleOnPermissionsChanged(uid);
20780                } break;
20781            }
20782        }
20783
20784        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20785            mPermissionListeners.register(listener);
20786
20787        }
20788
20789        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20790            mPermissionListeners.unregister(listener);
20791        }
20792
20793        public void onPermissionsChanged(int uid) {
20794            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20795                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20796            }
20797        }
20798
20799        private void handleOnPermissionsChanged(int uid) {
20800            final int count = mPermissionListeners.beginBroadcast();
20801            try {
20802                for (int i = 0; i < count; i++) {
20803                    IOnPermissionsChangeListener callback = mPermissionListeners
20804                            .getBroadcastItem(i);
20805                    try {
20806                        callback.onPermissionsChanged(uid);
20807                    } catch (RemoteException e) {
20808                        Log.e(TAG, "Permission listener is dead", e);
20809                    }
20810                }
20811            } finally {
20812                mPermissionListeners.finishBroadcast();
20813            }
20814        }
20815    }
20816
20817    private class PackageManagerInternalImpl extends PackageManagerInternal {
20818        @Override
20819        public void setLocationPackagesProvider(PackagesProvider provider) {
20820            synchronized (mPackages) {
20821                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20822            }
20823        }
20824
20825        @Override
20826        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20827            synchronized (mPackages) {
20828                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20829            }
20830        }
20831
20832        @Override
20833        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20834            synchronized (mPackages) {
20835                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20836            }
20837        }
20838
20839        @Override
20840        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20841            synchronized (mPackages) {
20842                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20843            }
20844        }
20845
20846        @Override
20847        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20848            synchronized (mPackages) {
20849                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20850            }
20851        }
20852
20853        @Override
20854        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20855            synchronized (mPackages) {
20856                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20857            }
20858        }
20859
20860        @Override
20861        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20862            synchronized (mPackages) {
20863                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20864                        packageName, userId);
20865            }
20866        }
20867
20868        @Override
20869        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20870            synchronized (mPackages) {
20871                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20872                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20873                        packageName, userId);
20874            }
20875        }
20876
20877        @Override
20878        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20879            synchronized (mPackages) {
20880                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20881                        packageName, userId);
20882            }
20883        }
20884
20885        @Override
20886        public void setKeepUninstalledPackages(final List<String> packageList) {
20887            Preconditions.checkNotNull(packageList);
20888            List<String> removedFromList = null;
20889            synchronized (mPackages) {
20890                if (mKeepUninstalledPackages != null) {
20891                    final int packagesCount = mKeepUninstalledPackages.size();
20892                    for (int i = 0; i < packagesCount; i++) {
20893                        String oldPackage = mKeepUninstalledPackages.get(i);
20894                        if (packageList != null && packageList.contains(oldPackage)) {
20895                            continue;
20896                        }
20897                        if (removedFromList == null) {
20898                            removedFromList = new ArrayList<>();
20899                        }
20900                        removedFromList.add(oldPackage);
20901                    }
20902                }
20903                mKeepUninstalledPackages = new ArrayList<>(packageList);
20904                if (removedFromList != null) {
20905                    final int removedCount = removedFromList.size();
20906                    for (int i = 0; i < removedCount; i++) {
20907                        deletePackageIfUnusedLPr(removedFromList.get(i));
20908                    }
20909                }
20910            }
20911        }
20912
20913        @Override
20914        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20915            synchronized (mPackages) {
20916                // If we do not support permission review, done.
20917                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20918                    return false;
20919                }
20920
20921                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20922                if (packageSetting == null) {
20923                    return false;
20924                }
20925
20926                // Permission review applies only to apps not supporting the new permission model.
20927                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20928                    return false;
20929                }
20930
20931                // Legacy apps have the permission and get user consent on launch.
20932                PermissionsState permissionsState = packageSetting.getPermissionsState();
20933                return permissionsState.isPermissionReviewRequired(userId);
20934            }
20935        }
20936
20937        @Override
20938        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20939            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20940        }
20941
20942        @Override
20943        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20944                int userId) {
20945            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20946        }
20947
20948        @Override
20949        public void setDeviceAndProfileOwnerPackages(
20950                int deviceOwnerUserId, String deviceOwnerPackage,
20951                SparseArray<String> profileOwnerPackages) {
20952            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20953                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20954        }
20955
20956        @Override
20957        public boolean isPackageDataProtected(int userId, String packageName) {
20958            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20959        }
20960    }
20961
20962    @Override
20963    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20964        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20965        synchronized (mPackages) {
20966            final long identity = Binder.clearCallingIdentity();
20967            try {
20968                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20969                        packageNames, userId);
20970            } finally {
20971                Binder.restoreCallingIdentity(identity);
20972            }
20973        }
20974    }
20975
20976    private static void enforceSystemOrPhoneCaller(String tag) {
20977        int callingUid = Binder.getCallingUid();
20978        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20979            throw new SecurityException(
20980                    "Cannot call " + tag + " from UID " + callingUid);
20981        }
20982    }
20983
20984    boolean isHistoricalPackageUsageAvailable() {
20985        return mPackageUsage.isHistoricalPackageUsageAvailable();
20986    }
20987
20988    /**
20989     * Return a <b>copy</b> of the collection of packages known to the package manager.
20990     * @return A copy of the values of mPackages.
20991     */
20992    Collection<PackageParser.Package> getPackages() {
20993        synchronized (mPackages) {
20994            return new ArrayList<>(mPackages.values());
20995        }
20996    }
20997
20998    /**
20999     * Logs process start information (including base APK hash) to the security log.
21000     * @hide
21001     */
21002    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21003            String apkFile, int pid) {
21004        if (!SecurityLog.isLoggingEnabled()) {
21005            return;
21006        }
21007        Bundle data = new Bundle();
21008        data.putLong("startTimestamp", System.currentTimeMillis());
21009        data.putString("processName", processName);
21010        data.putInt("uid", uid);
21011        data.putString("seinfo", seinfo);
21012        data.putString("apkFile", apkFile);
21013        data.putInt("pid", pid);
21014        Message msg = mProcessLoggingHandler.obtainMessage(
21015                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21016        msg.setData(data);
21017        mProcessLoggingHandler.sendMessage(msg);
21018    }
21019}
21020