PackageManagerService.java revision bbfb1c174a83d8f87cc072e3a6d4a17528f1e5b7
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.Signature;
163import android.content.pm.UserInfo;
164import android.content.pm.VerifierDeviceIdentity;
165import android.content.pm.VerifierInfo;
166import android.content.res.Resources;
167import android.graphics.Bitmap;
168import android.hardware.display.DisplayManager;
169import android.net.Uri;
170import android.os.Binder;
171import android.os.Build;
172import android.os.Bundle;
173import android.os.Debug;
174import android.os.Environment;
175import android.os.Environment.UserEnvironment;
176import android.os.FileUtils;
177import android.os.Handler;
178import android.os.IBinder;
179import android.os.Looper;
180import android.os.Message;
181import android.os.Parcel;
182import android.os.ParcelFileDescriptor;
183import android.os.Process;
184import android.os.RemoteCallbackList;
185import android.os.RemoteException;
186import android.os.ResultReceiver;
187import android.os.SELinux;
188import android.os.ServiceManager;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.AtomicFile;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.PrintStreamPrinter;
218import android.util.Slog;
219import android.util.SparseArray;
220import android.util.SparseBooleanArray;
221import android.util.SparseIntArray;
222import android.util.Xml;
223import android.util.jar.StrictJarFile;
224import android.view.Display;
225
226import com.android.internal.R;
227import com.android.internal.annotations.GuardedBy;
228import com.android.internal.app.IMediaContainerService;
229import com.android.internal.app.ResolverActivity;
230import com.android.internal.content.NativeLibraryHelper;
231import com.android.internal.content.PackageHelper;
232import com.android.internal.logging.MetricsLogger;
233import com.android.internal.os.IParcelFileDescriptorFactory;
234import com.android.internal.os.InstallerConnection.InstallerException;
235import com.android.internal.os.SomeArgs;
236import com.android.internal.os.Zygote;
237import com.android.internal.telephony.CarrierAppUtils;
238import com.android.internal.util.ArrayUtils;
239import com.android.internal.util.FastPrintWriter;
240import com.android.internal.util.FastXmlSerializer;
241import com.android.internal.util.IndentingPrintWriter;
242import com.android.internal.util.Preconditions;
243import com.android.internal.util.XmlUtils;
244import com.android.server.AttributeCache;
245import com.android.server.EventLogTags;
246import com.android.server.FgThread;
247import com.android.server.IntentResolver;
248import com.android.server.LocalServices;
249import com.android.server.ServiceThread;
250import com.android.server.SystemConfig;
251import com.android.server.Watchdog;
252import com.android.server.net.NetworkPolicyManagerInternal;
253import com.android.server.pm.PermissionsState.PermissionState;
254import com.android.server.pm.Settings.DatabaseVersion;
255import com.android.server.pm.Settings.VersionInfo;
256import com.android.server.storage.DeviceStorageMonitorInternal;
257
258import dalvik.system.CloseGuard;
259import dalvik.system.DexFile;
260import dalvik.system.VMRuntime;
261
262import libcore.io.IoUtils;
263import libcore.util.EmptyArray;
264
265import org.xmlpull.v1.XmlPullParser;
266import org.xmlpull.v1.XmlPullParserException;
267import org.xmlpull.v1.XmlSerializer;
268
269import java.io.BufferedInputStream;
270import java.io.BufferedOutputStream;
271import java.io.BufferedReader;
272import java.io.ByteArrayInputStream;
273import java.io.ByteArrayOutputStream;
274import java.io.File;
275import java.io.FileDescriptor;
276import java.io.FileInputStream;
277import java.io.FileNotFoundException;
278import java.io.FileOutputStream;
279import java.io.FileReader;
280import java.io.FilenameFilter;
281import java.io.IOException;
282import java.io.InputStream;
283import java.io.PrintWriter;
284import java.nio.charset.StandardCharsets;
285import java.security.DigestInputStream;
286import java.security.MessageDigest;
287import java.security.NoSuchAlgorithmException;
288import java.security.PublicKey;
289import java.security.cert.Certificate;
290import java.security.cert.CertificateEncodingException;
291import java.security.cert.CertificateException;
292import java.text.SimpleDateFormat;
293import java.util.ArrayList;
294import java.util.Arrays;
295import java.util.Collection;
296import java.util.Collections;
297import java.util.Comparator;
298import java.util.Date;
299import java.util.HashSet;
300import java.util.Iterator;
301import java.util.List;
302import java.util.Map;
303import java.util.Objects;
304import java.util.Set;
305import java.util.concurrent.CountDownLatch;
306import java.util.concurrent.TimeUnit;
307import java.util.concurrent.atomic.AtomicBoolean;
308import java.util.concurrent.atomic.AtomicInteger;
309import java.util.concurrent.atomic.AtomicLong;
310
311/**
312 * Keep track of all those APKs everywhere.
313 * <p>
314 * Internally there are two important locks:
315 * <ul>
316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
317 * and other related state. It is a fine-grained lock that should only be held
318 * momentarily, as it's one of the most contended locks in the system.
319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
320 * operations typically involve heavy lifting of application data on disk. Since
321 * {@code installd} is single-threaded, and it's operations can often be slow,
322 * this lock should never be acquired while already holding {@link #mPackages}.
323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
324 * holding {@link #mInstallLock}.
325 * </ul>
326 * Many internal methods rely on the caller to hold the appropriate locks, and
327 * this contract is expressed through method name suffixes:
328 * <ul>
329 * <li>fooLI(): the caller must hold {@link #mInstallLock}
330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
331 * being modified must be frozen
332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
334 * </ul>
335 * <p>
336 * Because this class is very central to the platform's security; please run all
337 * CTS and unit tests whenever making modifications:
338 *
339 * <pre>
340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
341 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
342 * </pre>
343 */
344public class PackageManagerService extends IPackageManager.Stub {
345    static final String TAG = "PackageManager";
346    static final boolean DEBUG_SETTINGS = false;
347    static final boolean DEBUG_PREFERRED = false;
348    static final boolean DEBUG_UPGRADE = false;
349    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
350    private static final boolean DEBUG_BACKUP = false;
351    private static final boolean DEBUG_INSTALL = false;
352    private static final boolean DEBUG_REMOVE = false;
353    private static final boolean DEBUG_BROADCASTS = false;
354    private static final boolean DEBUG_SHOW_INFO = false;
355    private static final boolean DEBUG_PACKAGE_INFO = false;
356    private static final boolean DEBUG_INTENT_MATCHING = false;
357    private static final boolean DEBUG_PACKAGE_SCANNING = false;
358    private static final boolean DEBUG_VERIFY = false;
359    private static final boolean DEBUG_FILTERS = false;
360
361    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
362    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
363    // user, but by default initialize to this.
364    static final boolean DEBUG_DEXOPT = false;
365
366    private static final boolean DEBUG_ABI_SELECTION = false;
367    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
368    private static final boolean DEBUG_TRIAGED_MISSING = false;
369    private static final boolean DEBUG_APP_DATA = false;
370
371    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
372
373    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
374
375    private static final int RADIO_UID = Process.PHONE_UID;
376    private static final int LOG_UID = Process.LOG_UID;
377    private static final int NFC_UID = Process.NFC_UID;
378    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
379    private static final int SHELL_UID = Process.SHELL_UID;
380
381    // Cap the size of permission trees that 3rd party apps can define
382    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
383
384    // Suffix used during package installation when copying/moving
385    // package apks to install directory.
386    private static final String INSTALL_PACKAGE_SUFFIX = "-";
387
388    static final int SCAN_NO_DEX = 1<<1;
389    static final int SCAN_FORCE_DEX = 1<<2;
390    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
391    static final int SCAN_NEW_INSTALL = 1<<4;
392    static final int SCAN_NO_PATHS = 1<<5;
393    static final int SCAN_UPDATE_TIME = 1<<6;
394    static final int SCAN_DEFER_DEX = 1<<7;
395    static final int SCAN_BOOTING = 1<<8;
396    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
397    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
398    static final int SCAN_REPLACING = 1<<11;
399    static final int SCAN_REQUIRE_KNOWN = 1<<12;
400    static final int SCAN_MOVE = 1<<13;
401    static final int SCAN_INITIAL = 1<<14;
402    static final int SCAN_CHECK_ONLY = 1<<15;
403    static final int SCAN_DONT_KILL_APP = 1<<17;
404    static final int SCAN_IGNORE_FROZEN = 1<<18;
405
406    static final int REMOVE_CHATTY = 1<<16;
407
408    private static final int[] EMPTY_INT_ARRAY = new int[0];
409
410    /**
411     * Timeout (in milliseconds) after which the watchdog should declare that
412     * our handler thread is wedged.  The usual default for such things is one
413     * minute but we sometimes do very lengthy I/O operations on this thread,
414     * such as installing multi-gigabyte applications, so ours needs to be longer.
415     */
416    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
417
418    /**
419     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
420     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
421     * settings entry if available, otherwise we use the hardcoded default.  If it's been
422     * more than this long since the last fstrim, we force one during the boot sequence.
423     *
424     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
425     * one gets run at the next available charging+idle time.  This final mandatory
426     * no-fstrim check kicks in only of the other scheduling criteria is never met.
427     */
428    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429
430    /**
431     * Whether verification is enabled by default.
432     */
433    private static final boolean DEFAULT_VERIFY_ENABLE = true;
434
435    /**
436     * The default maximum time to wait for the verification agent to return in
437     * milliseconds.
438     */
439    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440
441    /**
442     * The default response for package verification timeout.
443     *
444     * This can be either PackageManager.VERIFICATION_ALLOW or
445     * PackageManager.VERIFICATION_REJECT.
446     */
447    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448
449    static final String PLATFORM_PACKAGE_NAME = "android";
450
451    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452
453    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
454            DEFAULT_CONTAINER_PACKAGE,
455            "com.android.defcontainer.DefaultContainerService");
456
457    private static final String KILL_APP_REASON_GIDS_CHANGED =
458            "permission grant or revoke changed gids";
459
460    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
461            "permissions revoked";
462
463    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464
465    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
466
467    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
468    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
469
470    /** Permission grant: not grant the permission. */
471    private static final int GRANT_DENIED = 1;
472
473    /** Permission grant: grant the permission as an install permission. */
474    private static final int GRANT_INSTALL = 2;
475
476    /** Permission grant: grant the permission as a runtime one. */
477    private static final int GRANT_RUNTIME = 3;
478
479    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
480    private static final int GRANT_UPGRADE = 4;
481
482    /** Canonical intent used to identify what counts as a "web browser" app */
483    private static final Intent sBrowserIntent;
484    static {
485        sBrowserIntent = new Intent();
486        sBrowserIntent.setAction(Intent.ACTION_VIEW);
487        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
488        sBrowserIntent.setData(Uri.parse("http:"));
489    }
490
491    /**
492     * The set of all protected actions [i.e. those actions for which a high priority
493     * intent filter is disallowed].
494     */
495    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
496    static {
497        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
498        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
499        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
500        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
501    }
502
503    // Compilation reasons.
504    public static final int REASON_FIRST_BOOT = 0;
505    public static final int REASON_BOOT = 1;
506    public static final int REASON_INSTALL = 2;
507    public static final int REASON_BACKGROUND_DEXOPT = 3;
508    public static final int REASON_AB_OTA = 4;
509    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
510    public static final int REASON_SHARED_APK = 6;
511    public static final int REASON_FORCED_DEXOPT = 7;
512    public static final int REASON_CORE_APP = 8;
513
514    public static final int REASON_LAST = REASON_CORE_APP;
515
516    /** Special library name that skips shared libraries check during compilation. */
517    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
518
519    final ServiceThread mHandlerThread;
520
521    final PackageHandler mHandler;
522
523    private final ProcessLoggingHandler mProcessLoggingHandler;
524
525    /**
526     * Messages for {@link #mHandler} that need to wait for system ready before
527     * being dispatched.
528     */
529    private ArrayList<Message> mPostSystemReadyMessages;
530
531    final int mSdkVersion = Build.VERSION.SDK_INT;
532
533    final Context mContext;
534    final boolean mFactoryTest;
535    final boolean mOnlyCore;
536    final DisplayMetrics mMetrics;
537    final int mDefParseFlags;
538    final String[] mSeparateProcesses;
539    final boolean mIsUpgrade;
540    final boolean mIsPreNUpgrade;
541
542    /** The location for ASEC container files on internal storage. */
543    final String mAsecInternalPath;
544
545    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
546    // LOCK HELD.  Can be called with mInstallLock held.
547    @GuardedBy("mInstallLock")
548    final Installer mInstaller;
549
550    /** Directory where installed third-party apps stored */
551    final File mAppInstallDir;
552    final File mEphemeralInstallDir;
553
554    /**
555     * Directory to which applications installed internally have their
556     * 32 bit native libraries copied.
557     */
558    private File mAppLib32InstallDir;
559
560    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
561    // apps.
562    final File mDrmAppPrivateInstallDir;
563
564    // ----------------------------------------------------------------
565
566    // Lock for state used when installing and doing other long running
567    // operations.  Methods that must be called with this lock held have
568    // the suffix "LI".
569    final Object mInstallLock = new Object();
570
571    // ----------------------------------------------------------------
572
573    // Keys are String (package name), values are Package.  This also serves
574    // as the lock for the global state.  Methods that must be called with
575    // this lock held have the prefix "LP".
576    @GuardedBy("mPackages")
577    final ArrayMap<String, PackageParser.Package> mPackages =
578            new ArrayMap<String, PackageParser.Package>();
579
580    final ArrayMap<String, Set<String>> mKnownCodebase =
581            new ArrayMap<String, Set<String>>();
582
583    // Tracks available target package names -> overlay package paths.
584    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
585        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
586
587    /**
588     * Tracks new system packages [received in an OTA] that we expect to
589     * find updated user-installed versions. Keys are package name, values
590     * are package location.
591     */
592    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
593    /**
594     * Tracks high priority intent filters for protected actions. During boot, certain
595     * filter actions are protected and should never be allowed to have a high priority
596     * intent filter for them. However, there is one, and only one exception -- the
597     * setup wizard. It must be able to define a high priority intent filter for these
598     * actions to ensure there are no escapes from the wizard. We need to delay processing
599     * of these during boot as we need to look at all of the system packages in order
600     * to know which component is the setup wizard.
601     */
602    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
603    /**
604     * Whether or not processing protected filters should be deferred.
605     */
606    private boolean mDeferProtectedFilters = true;
607
608    /**
609     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
610     */
611    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
612    /**
613     * Whether or not system app permissions should be promoted from install to runtime.
614     */
615    boolean mPromoteSystemApps;
616
617    @GuardedBy("mPackages")
618    final Settings mSettings;
619
620    /**
621     * Set of package names that are currently "frozen", which means active
622     * surgery is being done on the code/data for that package. The platform
623     * will refuse to launch frozen packages to avoid race conditions.
624     *
625     * @see PackageFreezer
626     */
627    @GuardedBy("mPackages")
628    final ArraySet<String> mFrozenPackages = new ArraySet<>();
629
630    final ProtectedPackages mProtectedPackages;
631
632    boolean mRestoredSettings;
633
634    // System configuration read by SystemConfig.
635    final int[] mGlobalGids;
636    final SparseArray<ArraySet<String>> mSystemPermissions;
637    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
638
639    // If mac_permissions.xml was found for seinfo labeling.
640    boolean mFoundPolicyFile;
641
642    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
643
644    public static final class SharedLibraryEntry {
645        public final String path;
646        public final String apk;
647
648        SharedLibraryEntry(String _path, String _apk) {
649            path = _path;
650            apk = _apk;
651        }
652    }
653
654    // Currently known shared libraries.
655    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
656            new ArrayMap<String, SharedLibraryEntry>();
657
658    // All available activities, for your resolving pleasure.
659    final ActivityIntentResolver mActivities =
660            new ActivityIntentResolver();
661
662    // All available receivers, for your resolving pleasure.
663    final ActivityIntentResolver mReceivers =
664            new ActivityIntentResolver();
665
666    // All available services, for your resolving pleasure.
667    final ServiceIntentResolver mServices = new ServiceIntentResolver();
668
669    // All available providers, for your resolving pleasure.
670    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
671
672    // Mapping from provider base names (first directory in content URI codePath)
673    // to the provider information.
674    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
675            new ArrayMap<String, PackageParser.Provider>();
676
677    // Mapping from instrumentation class names to info about them.
678    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
679            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
680
681    // Mapping from permission names to info about them.
682    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
683            new ArrayMap<String, PackageParser.PermissionGroup>();
684
685    // Packages whose data we have transfered into another package, thus
686    // should no longer exist.
687    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
688
689    // Broadcast actions that are only available to the system.
690    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
691
692    /** List of packages waiting for verification. */
693    final SparseArray<PackageVerificationState> mPendingVerification
694            = new SparseArray<PackageVerificationState>();
695
696    /** Set of packages associated with each app op permission. */
697    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
698
699    final PackageInstallerService mInstallerService;
700
701    private final PackageDexOptimizer mPackageDexOptimizer;
702
703    private AtomicInteger mNextMoveId = new AtomicInteger();
704    private final MoveCallbacks mMoveCallbacks;
705
706    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
707
708    // Cache of users who need badging.
709    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
710
711    /** Token for keys in mPendingVerification. */
712    private int mPendingVerificationToken = 0;
713
714    volatile boolean mSystemReady;
715    volatile boolean mSafeMode;
716    volatile boolean mHasSystemUidErrors;
717
718    ApplicationInfo mAndroidApplication;
719    final ActivityInfo mResolveActivity = new ActivityInfo();
720    final ResolveInfo mResolveInfo = new ResolveInfo();
721    ComponentName mResolveComponentName;
722    PackageParser.Package mPlatformPackage;
723    ComponentName mCustomResolverComponentName;
724
725    boolean mResolverReplaced = false;
726
727    private final @Nullable ComponentName mIntentFilterVerifierComponent;
728    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
729
730    private int mIntentFilterVerificationToken = 0;
731
732    /** Component that knows whether or not an ephemeral application exists */
733    final ComponentName mEphemeralResolverComponent;
734    /** The service connection to the ephemeral resolver */
735    final EphemeralResolverConnection mEphemeralResolverConnection;
736
737    /** Component used to install ephemeral applications */
738    final ComponentName mEphemeralInstallerComponent;
739    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
740    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
741
742    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
743            = new SparseArray<IntentFilterVerificationState>();
744
745    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
746            new DefaultPermissionGrantPolicy(this);
747
748    // List of packages names to keep cached, even if they are uninstalled for all users
749    private List<String> mKeepUninstalledPackages;
750
751    private UserManagerInternal mUserManagerInternal;
752
753    private static class IFVerificationParams {
754        PackageParser.Package pkg;
755        boolean replacing;
756        int userId;
757        int verifierUid;
758
759        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
760                int _userId, int _verifierUid) {
761            pkg = _pkg;
762            replacing = _replacing;
763            userId = _userId;
764            replacing = _replacing;
765            verifierUid = _verifierUid;
766        }
767    }
768
769    private interface IntentFilterVerifier<T extends IntentFilter> {
770        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
771                                               T filter, String packageName);
772        void startVerifications(int userId);
773        void receiveVerificationResponse(int verificationId);
774    }
775
776    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
777        private Context mContext;
778        private ComponentName mIntentFilterVerifierComponent;
779        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
780
781        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
782            mContext = context;
783            mIntentFilterVerifierComponent = verifierComponent;
784        }
785
786        private String getDefaultScheme() {
787            return IntentFilter.SCHEME_HTTPS;
788        }
789
790        @Override
791        public void startVerifications(int userId) {
792            // Launch verifications requests
793            int count = mCurrentIntentFilterVerifications.size();
794            for (int n=0; n<count; n++) {
795                int verificationId = mCurrentIntentFilterVerifications.get(n);
796                final IntentFilterVerificationState ivs =
797                        mIntentFilterVerificationStates.get(verificationId);
798
799                String packageName = ivs.getPackageName();
800
801                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
802                final int filterCount = filters.size();
803                ArraySet<String> domainsSet = new ArraySet<>();
804                for (int m=0; m<filterCount; m++) {
805                    PackageParser.ActivityIntentInfo filter = filters.get(m);
806                    domainsSet.addAll(filter.getHostsList());
807                }
808                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
809                synchronized (mPackages) {
810                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
811                            packageName, domainsList) != null) {
812                        scheduleWriteSettingsLocked();
813                    }
814                }
815                sendVerificationRequest(userId, verificationId, ivs);
816            }
817            mCurrentIntentFilterVerifications.clear();
818        }
819
820        private void sendVerificationRequest(int userId, int verificationId,
821                IntentFilterVerificationState ivs) {
822
823            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
824            verificationIntent.putExtra(
825                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
826                    verificationId);
827            verificationIntent.putExtra(
828                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
829                    getDefaultScheme());
830            verificationIntent.putExtra(
831                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
832                    ivs.getHostsString());
833            verificationIntent.putExtra(
834                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
835                    ivs.getPackageName());
836            verificationIntent.setComponent(mIntentFilterVerifierComponent);
837            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
838
839            UserHandle user = new UserHandle(userId);
840            mContext.sendBroadcastAsUser(verificationIntent, user);
841            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
842                    "Sending IntentFilter verification broadcast");
843        }
844
845        public void receiveVerificationResponse(int verificationId) {
846            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
847
848            final boolean verified = ivs.isVerified();
849
850            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
851            final int count = filters.size();
852            if (DEBUG_DOMAIN_VERIFICATION) {
853                Slog.i(TAG, "Received verification response " + verificationId
854                        + " for " + count + " filters, verified=" + verified);
855            }
856            for (int n=0; n<count; n++) {
857                PackageParser.ActivityIntentInfo filter = filters.get(n);
858                filter.setVerified(verified);
859
860                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
861                        + " verified with result:" + verified + " and hosts:"
862                        + ivs.getHostsString());
863            }
864
865            mIntentFilterVerificationStates.remove(verificationId);
866
867            final String packageName = ivs.getPackageName();
868            IntentFilterVerificationInfo ivi = null;
869
870            synchronized (mPackages) {
871                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
872            }
873            if (ivi == null) {
874                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
875                        + verificationId + " packageName:" + packageName);
876                return;
877            }
878            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
879                    "Updating IntentFilterVerificationInfo for package " + packageName
880                            +" verificationId:" + verificationId);
881
882            synchronized (mPackages) {
883                if (verified) {
884                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
885                } else {
886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
887                }
888                scheduleWriteSettingsLocked();
889
890                final int userId = ivs.getUserId();
891                if (userId != UserHandle.USER_ALL) {
892                    final int userStatus =
893                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
894
895                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
896                    boolean needUpdate = false;
897
898                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
899                    // already been set by the User thru the Disambiguation dialog
900                    switch (userStatus) {
901                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
902                            if (verified) {
903                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
904                            } else {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
906                            }
907                            needUpdate = true;
908                            break;
909
910                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
911                            if (verified) {
912                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
913                                needUpdate = true;
914                            }
915                            break;
916
917                        default:
918                            // Nothing to do
919                    }
920
921                    if (needUpdate) {
922                        mSettings.updateIntentFilterVerificationStatusLPw(
923                                packageName, updatedStatus, userId);
924                        scheduleWritePackageRestrictionsLocked(userId);
925                    }
926                }
927            }
928        }
929
930        @Override
931        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
932                    ActivityIntentInfo filter, String packageName) {
933            if (!hasValidDomains(filter)) {
934                return false;
935            }
936            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
937            if (ivs == null) {
938                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
939                        packageName);
940            }
941            if (DEBUG_DOMAIN_VERIFICATION) {
942                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
943            }
944            ivs.addFilter(filter);
945            return true;
946        }
947
948        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
949                int userId, int verificationId, String packageName) {
950            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
951                    verifierUid, userId, packageName);
952            ivs.setPendingState();
953            synchronized (mPackages) {
954                mIntentFilterVerificationStates.append(verificationId, ivs);
955                mCurrentIntentFilterVerifications.add(verificationId);
956            }
957            return ivs;
958        }
959    }
960
961    private static boolean hasValidDomains(ActivityIntentInfo filter) {
962        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
963                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
964                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
965    }
966
967    // Set of pending broadcasts for aggregating enable/disable of components.
968    static class PendingPackageBroadcasts {
969        // for each user id, a map of <package name -> components within that package>
970        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
971
972        public PendingPackageBroadcasts() {
973            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
974        }
975
976        public ArrayList<String> get(int userId, String packageName) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            return packages.get(packageName);
979        }
980
981        public void put(int userId, String packageName, ArrayList<String> components) {
982            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
983            packages.put(packageName, components);
984        }
985
986        public void remove(int userId, String packageName) {
987            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
988            if (packages != null) {
989                packages.remove(packageName);
990            }
991        }
992
993        public void remove(int userId) {
994            mUidMap.remove(userId);
995        }
996
997        public int userIdCount() {
998            return mUidMap.size();
999        }
1000
1001        public int userIdAt(int n) {
1002            return mUidMap.keyAt(n);
1003        }
1004
1005        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1006            return mUidMap.get(userId);
1007        }
1008
1009        public int size() {
1010            // total number of pending broadcast entries across all userIds
1011            int num = 0;
1012            for (int i = 0; i< mUidMap.size(); i++) {
1013                num += mUidMap.valueAt(i).size();
1014            }
1015            return num;
1016        }
1017
1018        public void clear() {
1019            mUidMap.clear();
1020        }
1021
1022        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1023            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1024            if (map == null) {
1025                map = new ArrayMap<String, ArrayList<String>>();
1026                mUidMap.put(userId, map);
1027            }
1028            return map;
1029        }
1030    }
1031    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1032
1033    // Service Connection to remote media container service to copy
1034    // package uri's from external media onto secure containers
1035    // or internal storage.
1036    private IMediaContainerService mContainerService = null;
1037
1038    static final int SEND_PENDING_BROADCAST = 1;
1039    static final int MCS_BOUND = 3;
1040    static final int END_COPY = 4;
1041    static final int INIT_COPY = 5;
1042    static final int MCS_UNBIND = 6;
1043    static final int START_CLEANING_PACKAGE = 7;
1044    static final int FIND_INSTALL_LOC = 8;
1045    static final int POST_INSTALL = 9;
1046    static final int MCS_RECONNECT = 10;
1047    static final int MCS_GIVE_UP = 11;
1048    static final int UPDATED_MEDIA_STATUS = 12;
1049    static final int WRITE_SETTINGS = 13;
1050    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1051    static final int PACKAGE_VERIFIED = 15;
1052    static final int CHECK_PENDING_VERIFICATION = 16;
1053    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1054    static final int INTENT_FILTER_VERIFIED = 18;
1055    static final int WRITE_PACKAGE_LIST = 19;
1056
1057    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1058
1059    // Delay time in millisecs
1060    static final int BROADCAST_DELAY = 10 * 1000;
1061
1062    static UserManagerService sUserManager;
1063
1064    // Stores a list of users whose package restrictions file needs to be updated
1065    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1066
1067    final private DefaultContainerConnection mDefContainerConn =
1068            new DefaultContainerConnection();
1069    class DefaultContainerConnection implements ServiceConnection {
1070        public void onServiceConnected(ComponentName name, IBinder service) {
1071            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1072            IMediaContainerService imcs =
1073                IMediaContainerService.Stub.asInterface(service);
1074            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1075        }
1076
1077        public void onServiceDisconnected(ComponentName name) {
1078            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1079        }
1080    }
1081
1082    // Recordkeeping of restore-after-install operations that are currently in flight
1083    // between the Package Manager and the Backup Manager
1084    static class PostInstallData {
1085        public InstallArgs args;
1086        public PackageInstalledInfo res;
1087
1088        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1089            args = _a;
1090            res = _r;
1091        }
1092    }
1093
1094    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1095    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1096
1097    // XML tags for backup/restore of various bits of state
1098    private static final String TAG_PREFERRED_BACKUP = "pa";
1099    private static final String TAG_DEFAULT_APPS = "da";
1100    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1101
1102    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1103    private static final String TAG_ALL_GRANTS = "rt-grants";
1104    private static final String TAG_GRANT = "grant";
1105    private static final String ATTR_PACKAGE_NAME = "pkg";
1106
1107    private static final String TAG_PERMISSION = "perm";
1108    private static final String ATTR_PERMISSION_NAME = "name";
1109    private static final String ATTR_IS_GRANTED = "g";
1110    private static final String ATTR_USER_SET = "set";
1111    private static final String ATTR_USER_FIXED = "fixed";
1112    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1113
1114    // System/policy permission grants are not backed up
1115    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1116            FLAG_PERMISSION_POLICY_FIXED
1117            | FLAG_PERMISSION_SYSTEM_FIXED
1118            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1119
1120    // And we back up these user-adjusted states
1121    private static final int USER_RUNTIME_GRANT_MASK =
1122            FLAG_PERMISSION_USER_SET
1123            | FLAG_PERMISSION_USER_FIXED
1124            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1125
1126    final @Nullable String mRequiredVerifierPackage;
1127    final @NonNull String mRequiredInstallerPackage;
1128    final @Nullable String mSetupWizardPackage;
1129    final @NonNull String mServicesSystemSharedLibraryPackageName;
1130    final @NonNull String mSharedSystemSharedLibraryPackageName;
1131
1132    private final PackageUsage mPackageUsage = new PackageUsage();
1133
1134    private class PackageUsage {
1135        private static final int WRITE_INTERVAL
1136            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1137
1138        private final Object mFileLock = new Object();
1139        private final AtomicLong mLastWritten = new AtomicLong(0);
1140        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1141
1142        private boolean mIsHistoricalPackageUsageAvailable = true;
1143
1144        boolean isHistoricalPackageUsageAvailable() {
1145            return mIsHistoricalPackageUsageAvailable;
1146        }
1147
1148        void write(boolean force) {
1149            if (force) {
1150                writeInternal();
1151                return;
1152            }
1153            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1154                && !DEBUG_DEXOPT) {
1155                return;
1156            }
1157            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1158                new Thread("PackageUsage_DiskWriter") {
1159                    @Override
1160                    public void run() {
1161                        try {
1162                            writeInternal();
1163                        } finally {
1164                            mBackgroundWriteRunning.set(false);
1165                        }
1166                    }
1167                }.start();
1168            }
1169        }
1170
1171        private void writeInternal() {
1172            synchronized (mPackages) {
1173                synchronized (mFileLock) {
1174                    AtomicFile file = getFile();
1175                    FileOutputStream f = null;
1176                    try {
1177                        f = file.startWrite();
1178                        BufferedOutputStream out = new BufferedOutputStream(f);
1179                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1180                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1181                        StringBuilder sb = new StringBuilder();
1182
1183                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1184                        sb.append('\n');
1185                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1186
1187                        for (PackageParser.Package pkg : mPackages.values()) {
1188                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1189                                continue;
1190                            }
1191                            sb.setLength(0);
1192                            sb.append(pkg.packageName);
1193                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1194                                sb.append(' ');
1195                                sb.append(usageTimeInMillis);
1196                            }
1197                            sb.append('\n');
1198                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1199                        }
1200                        out.flush();
1201                        file.finishWrite(f);
1202                    } catch (IOException e) {
1203                        if (f != null) {
1204                            file.failWrite(f);
1205                        }
1206                        Log.e(TAG, "Failed to write package usage times", e);
1207                    }
1208                }
1209            }
1210            mLastWritten.set(SystemClock.elapsedRealtime());
1211        }
1212
1213        void readLP() {
1214            synchronized (mFileLock) {
1215                AtomicFile file = getFile();
1216                BufferedInputStream in = null;
1217                try {
1218                    in = new BufferedInputStream(file.openRead());
1219                    StringBuffer sb = new StringBuffer();
1220
1221                    String firstLine = readLine(in, sb);
1222                    if (firstLine == null) {
1223                        // Empty file. Do nothing.
1224                    } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) {
1225                        readVersion1LP(in, sb);
1226                    } else {
1227                        readVersion0LP(in, sb, firstLine);
1228                    }
1229                } catch (FileNotFoundException expected) {
1230                    mIsHistoricalPackageUsageAvailable = false;
1231                } catch (IOException e) {
1232                    Log.w(TAG, "Failed to read package usage times", e);
1233                } finally {
1234                    IoUtils.closeQuietly(in);
1235                }
1236            }
1237            mLastWritten.set(SystemClock.elapsedRealtime());
1238        }
1239
1240        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1241                throws IOException {
1242            // Initial version of the file had no version number and stored one
1243            // package-timestamp pair per line.
1244            // Note that the first line has already been read from the InputStream.
1245            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1246                String[] tokens = line.split(" ");
1247                if (tokens.length != 2) {
1248                    throw new IOException("Failed to parse " + line +
1249                            " as package-timestamp pair.");
1250                }
1251
1252                String packageName = tokens[0];
1253                PackageParser.Package pkg = mPackages.get(packageName);
1254                if (pkg == null) {
1255                    continue;
1256                }
1257
1258                long timestamp = parseAsLong(tokens[1]);
1259                for (int reason = 0;
1260                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1261                        reason++) {
1262                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1263                }
1264            }
1265        }
1266
1267        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1268            // Version 1 of the file started with the corresponding version
1269            // number and then stored a package name and eight timestamps per line.
1270            String line;
1271            while ((line = readLine(in, sb)) != null) {
1272                String[] tokens = line.split(" ");
1273                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1274                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1275                }
1276
1277                String packageName = tokens[0];
1278                PackageParser.Package pkg = mPackages.get(packageName);
1279                if (pkg == null) {
1280                    continue;
1281                }
1282
1283                for (int reason = 0;
1284                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1285                        reason++) {
1286                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1287                }
1288            }
1289        }
1290
1291        private long parseAsLong(String token) throws IOException {
1292            try {
1293                return Long.parseLong(token);
1294            } catch (NumberFormatException e) {
1295                throw new IOException("Failed to parse " + token + " as a long.", e);
1296            }
1297        }
1298
1299        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1300            return readToken(in, sb, '\n');
1301        }
1302
1303        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1304                throws IOException {
1305            sb.setLength(0);
1306            while (true) {
1307                int ch = in.read();
1308                if (ch == -1) {
1309                    if (sb.length() == 0) {
1310                        return null;
1311                    }
1312                    throw new IOException("Unexpected EOF");
1313                }
1314                if (ch == endOfToken) {
1315                    return sb.toString();
1316                }
1317                sb.append((char)ch);
1318            }
1319        }
1320
1321        private AtomicFile getFile() {
1322            File dataDir = Environment.getDataDirectory();
1323            File systemDir = new File(dataDir, "system");
1324            File fname = new File(systemDir, "package-usage.list");
1325            return new AtomicFile(fname);
1326        }
1327
1328        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1329        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1330    }
1331
1332    class PackageHandler extends Handler {
1333        private boolean mBound = false;
1334        final ArrayList<HandlerParams> mPendingInstalls =
1335            new ArrayList<HandlerParams>();
1336
1337        private boolean connectToService() {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1339                    " DefaultContainerService");
1340            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1341            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1342            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1343                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1344                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1345                mBound = true;
1346                return true;
1347            }
1348            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1349            return false;
1350        }
1351
1352        private void disconnectService() {
1353            mContainerService = null;
1354            mBound = false;
1355            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1356            mContext.unbindService(mDefContainerConn);
1357            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1358        }
1359
1360        PackageHandler(Looper looper) {
1361            super(looper);
1362        }
1363
1364        public void handleMessage(Message msg) {
1365            try {
1366                doHandleMessage(msg);
1367            } finally {
1368                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1369            }
1370        }
1371
1372        void doHandleMessage(Message msg) {
1373            switch (msg.what) {
1374                case INIT_COPY: {
1375                    HandlerParams params = (HandlerParams) msg.obj;
1376                    int idx = mPendingInstalls.size();
1377                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1378                    // If a bind was already initiated we dont really
1379                    // need to do anything. The pending install
1380                    // will be processed later on.
1381                    if (!mBound) {
1382                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1383                                System.identityHashCode(mHandler));
1384                        // If this is the only one pending we might
1385                        // have to bind to the service again.
1386                        if (!connectToService()) {
1387                            Slog.e(TAG, "Failed to bind to media container service");
1388                            params.serviceError();
1389                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1390                                    System.identityHashCode(mHandler));
1391                            if (params.traceMethod != null) {
1392                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1393                                        params.traceCookie);
1394                            }
1395                            return;
1396                        } else {
1397                            // Once we bind to the service, the first
1398                            // pending request will be processed.
1399                            mPendingInstalls.add(idx, params);
1400                        }
1401                    } else {
1402                        mPendingInstalls.add(idx, params);
1403                        // Already bound to the service. Just make
1404                        // sure we trigger off processing the first request.
1405                        if (idx == 0) {
1406                            mHandler.sendEmptyMessage(MCS_BOUND);
1407                        }
1408                    }
1409                    break;
1410                }
1411                case MCS_BOUND: {
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1413                    if (msg.obj != null) {
1414                        mContainerService = (IMediaContainerService) msg.obj;
1415                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1416                                System.identityHashCode(mHandler));
1417                    }
1418                    if (mContainerService == null) {
1419                        if (!mBound) {
1420                            // Something seriously wrong since we are not bound and we are not
1421                            // waiting for connection. Bail out.
1422                            Slog.e(TAG, "Cannot bind to media container service");
1423                            for (HandlerParams params : mPendingInstalls) {
1424                                // Indicate service bind error
1425                                params.serviceError();
1426                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1427                                        System.identityHashCode(params));
1428                                if (params.traceMethod != null) {
1429                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1430                                            params.traceMethod, params.traceCookie);
1431                                }
1432                                return;
1433                            }
1434                            mPendingInstalls.clear();
1435                        } else {
1436                            Slog.w(TAG, "Waiting to connect to media container service");
1437                        }
1438                    } else if (mPendingInstalls.size() > 0) {
1439                        HandlerParams params = mPendingInstalls.get(0);
1440                        if (params != null) {
1441                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                                    System.identityHashCode(params));
1443                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1444                            if (params.startCopy()) {
1445                                // We are done...  look for more work or to
1446                                // go idle.
1447                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1448                                        "Checking for more work or unbind...");
1449                                // Delete pending install
1450                                if (mPendingInstalls.size() > 0) {
1451                                    mPendingInstalls.remove(0);
1452                                }
1453                                if (mPendingInstalls.size() == 0) {
1454                                    if (mBound) {
1455                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1456                                                "Posting delayed MCS_UNBIND");
1457                                        removeMessages(MCS_UNBIND);
1458                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1459                                        // Unbind after a little delay, to avoid
1460                                        // continual thrashing.
1461                                        sendMessageDelayed(ubmsg, 10000);
1462                                    }
1463                                } else {
1464                                    // There are more pending requests in queue.
1465                                    // Just post MCS_BOUND message to trigger processing
1466                                    // of next pending install.
1467                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1468                                            "Posting MCS_BOUND for next work");
1469                                    mHandler.sendEmptyMessage(MCS_BOUND);
1470                                }
1471                            }
1472                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1473                        }
1474                    } else {
1475                        // Should never happen ideally.
1476                        Slog.w(TAG, "Empty queue");
1477                    }
1478                    break;
1479                }
1480                case MCS_RECONNECT: {
1481                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1482                    if (mPendingInstalls.size() > 0) {
1483                        if (mBound) {
1484                            disconnectService();
1485                        }
1486                        if (!connectToService()) {
1487                            Slog.e(TAG, "Failed to bind to media container service");
1488                            for (HandlerParams params : mPendingInstalls) {
1489                                // Indicate service bind error
1490                                params.serviceError();
1491                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                        System.identityHashCode(params));
1493                            }
1494                            mPendingInstalls.clear();
1495                        }
1496                    }
1497                    break;
1498                }
1499                case MCS_UNBIND: {
1500                    // If there is no actual work left, then time to unbind.
1501                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1502
1503                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1504                        if (mBound) {
1505                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1506
1507                            disconnectService();
1508                        }
1509                    } else if (mPendingInstalls.size() > 0) {
1510                        // There are more pending requests in queue.
1511                        // Just post MCS_BOUND message to trigger processing
1512                        // of next pending install.
1513                        mHandler.sendEmptyMessage(MCS_BOUND);
1514                    }
1515
1516                    break;
1517                }
1518                case MCS_GIVE_UP: {
1519                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1520                    HandlerParams params = mPendingInstalls.remove(0);
1521                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                            System.identityHashCode(params));
1523                    break;
1524                }
1525                case SEND_PENDING_BROADCAST: {
1526                    String packages[];
1527                    ArrayList<String> components[];
1528                    int size = 0;
1529                    int uids[];
1530                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1531                    synchronized (mPackages) {
1532                        if (mPendingBroadcasts == null) {
1533                            return;
1534                        }
1535                        size = mPendingBroadcasts.size();
1536                        if (size <= 0) {
1537                            // Nothing to be done. Just return
1538                            return;
1539                        }
1540                        packages = new String[size];
1541                        components = new ArrayList[size];
1542                        uids = new int[size];
1543                        int i = 0;  // filling out the above arrays
1544
1545                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1546                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1547                            Iterator<Map.Entry<String, ArrayList<String>>> it
1548                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1549                                            .entrySet().iterator();
1550                            while (it.hasNext() && i < size) {
1551                                Map.Entry<String, ArrayList<String>> ent = it.next();
1552                                packages[i] = ent.getKey();
1553                                components[i] = ent.getValue();
1554                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1555                                uids[i] = (ps != null)
1556                                        ? UserHandle.getUid(packageUserId, ps.appId)
1557                                        : -1;
1558                                i++;
1559                            }
1560                        }
1561                        size = i;
1562                        mPendingBroadcasts.clear();
1563                    }
1564                    // Send broadcasts
1565                    for (int i = 0; i < size; i++) {
1566                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1567                    }
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1569                    break;
1570                }
1571                case START_CLEANING_PACKAGE: {
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1573                    final String packageName = (String)msg.obj;
1574                    final int userId = msg.arg1;
1575                    final boolean andCode = msg.arg2 != 0;
1576                    synchronized (mPackages) {
1577                        if (userId == UserHandle.USER_ALL) {
1578                            int[] users = sUserManager.getUserIds();
1579                            for (int user : users) {
1580                                mSettings.addPackageToCleanLPw(
1581                                        new PackageCleanItem(user, packageName, andCode));
1582                            }
1583                        } else {
1584                            mSettings.addPackageToCleanLPw(
1585                                    new PackageCleanItem(userId, packageName, andCode));
1586                        }
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                    startCleaningPackages();
1590                } break;
1591                case POST_INSTALL: {
1592                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1593
1594                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1595                    final boolean didRestore = (msg.arg2 != 0);
1596                    mRunningInstalls.delete(msg.arg1);
1597
1598                    if (data != null) {
1599                        InstallArgs args = data.args;
1600                        PackageInstalledInfo parentRes = data.res;
1601
1602                        final boolean grantPermissions = (args.installFlags
1603                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1604                        final boolean killApp = (args.installFlags
1605                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1606                        final String[] grantedPermissions = args.installGrantPermissions;
1607
1608                        // Handle the parent package
1609                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1610                                grantedPermissions, didRestore, args.installerPackageName,
1611                                args.observer);
1612
1613                        // Handle the child packages
1614                        final int childCount = (parentRes.addedChildPackages != null)
1615                                ? parentRes.addedChildPackages.size() : 0;
1616                        for (int i = 0; i < childCount; i++) {
1617                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1618                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1619                                    grantedPermissions, false, args.installerPackageName,
1620                                    args.observer);
1621                        }
1622
1623                        // Log tracing if needed
1624                        if (args.traceMethod != null) {
1625                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1626                                    args.traceCookie);
1627                        }
1628                    } else {
1629                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1630                    }
1631
1632                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1633                } break;
1634                case UPDATED_MEDIA_STATUS: {
1635                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1636                    boolean reportStatus = msg.arg1 == 1;
1637                    boolean doGc = msg.arg2 == 1;
1638                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1639                    if (doGc) {
1640                        // Force a gc to clear up stale containers.
1641                        Runtime.getRuntime().gc();
1642                    }
1643                    if (msg.obj != null) {
1644                        @SuppressWarnings("unchecked")
1645                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1646                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1647                        // Unload containers
1648                        unloadAllContainers(args);
1649                    }
1650                    if (reportStatus) {
1651                        try {
1652                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1653                            PackageHelper.getMountService().finishMediaUpdate();
1654                        } catch (RemoteException e) {
1655                            Log.e(TAG, "MountService not running?");
1656                        }
1657                    }
1658                } break;
1659                case WRITE_SETTINGS: {
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1661                    synchronized (mPackages) {
1662                        removeMessages(WRITE_SETTINGS);
1663                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1664                        mSettings.writeLPr();
1665                        mDirtyUsers.clear();
1666                    }
1667                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1668                } break;
1669                case WRITE_PACKAGE_RESTRICTIONS: {
1670                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1671                    synchronized (mPackages) {
1672                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1673                        for (int userId : mDirtyUsers) {
1674                            mSettings.writePackageRestrictionsLPr(userId);
1675                        }
1676                        mDirtyUsers.clear();
1677                    }
1678                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1679                } break;
1680                case WRITE_PACKAGE_LIST: {
1681                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1682                    synchronized (mPackages) {
1683                        removeMessages(WRITE_PACKAGE_LIST);
1684                        mSettings.writePackageListLPr(msg.arg1);
1685                    }
1686                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1687                } break;
1688                case CHECK_PENDING_VERIFICATION: {
1689                    final int verificationId = msg.arg1;
1690                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1691
1692                    if ((state != null) && !state.timeoutExtended()) {
1693                        final InstallArgs args = state.getInstallArgs();
1694                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1695
1696                        Slog.i(TAG, "Verification timed out for " + originUri);
1697                        mPendingVerification.remove(verificationId);
1698
1699                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1700
1701                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1702                            Slog.i(TAG, "Continuing with installation of " + originUri);
1703                            state.setVerifierResponse(Binder.getCallingUid(),
1704                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1705                            broadcastPackageVerified(verificationId, originUri,
1706                                    PackageManager.VERIFICATION_ALLOW,
1707                                    state.getInstallArgs().getUser());
1708                            try {
1709                                ret = args.copyApk(mContainerService, true);
1710                            } catch (RemoteException e) {
1711                                Slog.e(TAG, "Could not contact the ContainerService");
1712                            }
1713                        } else {
1714                            broadcastPackageVerified(verificationId, originUri,
1715                                    PackageManager.VERIFICATION_REJECT,
1716                                    state.getInstallArgs().getUser());
1717                        }
1718
1719                        Trace.asyncTraceEnd(
1720                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1721
1722                        processPendingInstall(args, ret);
1723                        mHandler.sendEmptyMessage(MCS_UNBIND);
1724                    }
1725                    break;
1726                }
1727                case PACKAGE_VERIFIED: {
1728                    final int verificationId = msg.arg1;
1729
1730                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1731                    if (state == null) {
1732                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1733                        break;
1734                    }
1735
1736                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1737
1738                    state.setVerifierResponse(response.callerUid, response.code);
1739
1740                    if (state.isVerificationComplete()) {
1741                        mPendingVerification.remove(verificationId);
1742
1743                        final InstallArgs args = state.getInstallArgs();
1744                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1745
1746                        int ret;
1747                        if (state.isInstallAllowed()) {
1748                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1749                            broadcastPackageVerified(verificationId, originUri,
1750                                    response.code, state.getInstallArgs().getUser());
1751                            try {
1752                                ret = args.copyApk(mContainerService, true);
1753                            } catch (RemoteException e) {
1754                                Slog.e(TAG, "Could not contact the ContainerService");
1755                            }
1756                        } else {
1757                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1758                        }
1759
1760                        Trace.asyncTraceEnd(
1761                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1762
1763                        processPendingInstall(args, ret);
1764                        mHandler.sendEmptyMessage(MCS_UNBIND);
1765                    }
1766
1767                    break;
1768                }
1769                case START_INTENT_FILTER_VERIFICATIONS: {
1770                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1771                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1772                            params.replacing, params.pkg);
1773                    break;
1774                }
1775                case INTENT_FILTER_VERIFIED: {
1776                    final int verificationId = msg.arg1;
1777
1778                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1779                            verificationId);
1780                    if (state == null) {
1781                        Slog.w(TAG, "Invalid IntentFilter verification token "
1782                                + verificationId + " received");
1783                        break;
1784                    }
1785
1786                    final int userId = state.getUserId();
1787
1788                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1789                            "Processing IntentFilter verification with token:"
1790                            + verificationId + " and userId:" + userId);
1791
1792                    final IntentFilterVerificationResponse response =
1793                            (IntentFilterVerificationResponse) msg.obj;
1794
1795                    state.setVerifierResponse(response.callerUid, response.code);
1796
1797                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1798                            "IntentFilter verification with token:" + verificationId
1799                            + " and userId:" + userId
1800                            + " is settings verifier response with response code:"
1801                            + response.code);
1802
1803                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1804                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1805                                + response.getFailedDomainsString());
1806                    }
1807
1808                    if (state.isVerificationComplete()) {
1809                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1810                    } else {
1811                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1812                                "IntentFilter verification with token:" + verificationId
1813                                + " was not said to be complete");
1814                    }
1815
1816                    break;
1817                }
1818            }
1819        }
1820    }
1821
1822    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1823            boolean killApp, String[] grantedPermissions,
1824            boolean launchedForRestore, String installerPackage,
1825            IPackageInstallObserver2 installObserver) {
1826        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1827            // Send the removed broadcasts
1828            if (res.removedInfo != null) {
1829                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1830            }
1831
1832            // Now that we successfully installed the package, grant runtime
1833            // permissions if requested before broadcasting the install.
1834            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1835                    >= Build.VERSION_CODES.M) {
1836                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1837            }
1838
1839            final boolean update = res.removedInfo != null
1840                    && res.removedInfo.removedPackage != null;
1841
1842            // If this is the first time we have child packages for a disabled privileged
1843            // app that had no children, we grant requested runtime permissions to the new
1844            // children if the parent on the system image had them already granted.
1845            if (res.pkg.parentPackage != null) {
1846                synchronized (mPackages) {
1847                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1848                }
1849            }
1850
1851            synchronized (mPackages) {
1852                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1853            }
1854
1855            final String packageName = res.pkg.applicationInfo.packageName;
1856            Bundle extras = new Bundle(1);
1857            extras.putInt(Intent.EXTRA_UID, res.uid);
1858
1859            // Determine the set of users who are adding this package for
1860            // the first time vs. those who are seeing an update.
1861            int[] firstUsers = EMPTY_INT_ARRAY;
1862            int[] updateUsers = EMPTY_INT_ARRAY;
1863            if (res.origUsers == null || res.origUsers.length == 0) {
1864                firstUsers = res.newUsers;
1865            } else {
1866                for (int newUser : res.newUsers) {
1867                    boolean isNew = true;
1868                    for (int origUser : res.origUsers) {
1869                        if (origUser == newUser) {
1870                            isNew = false;
1871                            break;
1872                        }
1873                    }
1874                    if (isNew) {
1875                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1876                    } else {
1877                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1878                    }
1879                }
1880            }
1881
1882            // Send installed broadcasts if the install/update is not ephemeral
1883            if (!isEphemeral(res.pkg)) {
1884                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1885
1886                // Send added for users that see the package for the first time
1887                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1888                        extras, 0 /*flags*/, null /*targetPackage*/,
1889                        null /*finishedReceiver*/, firstUsers);
1890
1891                // Send added for users that don't see the package for the first time
1892                if (update) {
1893                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1894                }
1895                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1896                        extras, 0 /*flags*/, null /*targetPackage*/,
1897                        null /*finishedReceiver*/, updateUsers);
1898
1899                // Send replaced for users that don't see the package for the first time
1900                if (update) {
1901                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1902                            packageName, extras, 0 /*flags*/,
1903                            null /*targetPackage*/, null /*finishedReceiver*/,
1904                            updateUsers);
1905                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1906                            null /*package*/, null /*extras*/, 0 /*flags*/,
1907                            packageName /*targetPackage*/,
1908                            null /*finishedReceiver*/, updateUsers);
1909                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1910                    // First-install and we did a restore, so we're responsible for the
1911                    // first-launch broadcast.
1912                    if (DEBUG_BACKUP) {
1913                        Slog.i(TAG, "Post-restore of " + packageName
1914                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1915                    }
1916                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1917                }
1918
1919                // Send broadcast package appeared if forward locked/external for all users
1920                // treat asec-hosted packages like removable media on upgrade
1921                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1922                    if (DEBUG_INSTALL) {
1923                        Slog.i(TAG, "upgrading pkg " + res.pkg
1924                                + " is ASEC-hosted -> AVAILABLE");
1925                    }
1926                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1927                    ArrayList<String> pkgList = new ArrayList<>(1);
1928                    pkgList.add(packageName);
1929                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1930                }
1931            }
1932
1933            // Work that needs to happen on first install within each user
1934            if (firstUsers != null && firstUsers.length > 0) {
1935                synchronized (mPackages) {
1936                    for (int userId : firstUsers) {
1937                        // If this app is a browser and it's newly-installed for some
1938                        // users, clear any default-browser state in those users. The
1939                        // app's nature doesn't depend on the user, so we can just check
1940                        // its browser nature in any user and generalize.
1941                        if (packageIsBrowser(packageName, userId)) {
1942                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1943                        }
1944
1945                        // We may also need to apply pending (restored) runtime
1946                        // permission grants within these users.
1947                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1948                    }
1949                }
1950            }
1951
1952            // Log current value of "unknown sources" setting
1953            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1954                    getUnknownSourcesSettings());
1955
1956            // Force a gc to clear up things
1957            Runtime.getRuntime().gc();
1958
1959            // Remove the replaced package's older resources safely now
1960            // We delete after a gc for applications  on sdcard.
1961            if (res.removedInfo != null && res.removedInfo.args != null) {
1962                synchronized (mInstallLock) {
1963                    res.removedInfo.args.doPostDeleteLI(true);
1964                }
1965            }
1966        }
1967
1968        // If someone is watching installs - notify them
1969        if (installObserver != null) {
1970            try {
1971                Bundle extras = extrasForInstallResult(res);
1972                installObserver.onPackageInstalled(res.name, res.returnCode,
1973                        res.returnMsg, extras);
1974            } catch (RemoteException e) {
1975                Slog.i(TAG, "Observer no longer exists.");
1976            }
1977        }
1978    }
1979
1980    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1981            PackageParser.Package pkg) {
1982        if (pkg.parentPackage == null) {
1983            return;
1984        }
1985        if (pkg.requestedPermissions == null) {
1986            return;
1987        }
1988        final PackageSetting disabledSysParentPs = mSettings
1989                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1990        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1991                || !disabledSysParentPs.isPrivileged()
1992                || (disabledSysParentPs.childPackageNames != null
1993                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1994            return;
1995        }
1996        final int[] allUserIds = sUserManager.getUserIds();
1997        final int permCount = pkg.requestedPermissions.size();
1998        for (int i = 0; i < permCount; i++) {
1999            String permission = pkg.requestedPermissions.get(i);
2000            BasePermission bp = mSettings.mPermissions.get(permission);
2001            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2002                continue;
2003            }
2004            for (int userId : allUserIds) {
2005                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2006                        permission, userId)) {
2007                    grantRuntimePermission(pkg.packageName, permission, userId);
2008                }
2009            }
2010        }
2011    }
2012
2013    private StorageEventListener mStorageListener = new StorageEventListener() {
2014        @Override
2015        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2016            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2017                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2018                    final String volumeUuid = vol.getFsUuid();
2019
2020                    // Clean up any users or apps that were removed or recreated
2021                    // while this volume was missing
2022                    reconcileUsers(volumeUuid);
2023                    reconcileApps(volumeUuid);
2024
2025                    // Clean up any install sessions that expired or were
2026                    // cancelled while this volume was missing
2027                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2028
2029                    loadPrivatePackages(vol);
2030
2031                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2032                    unloadPrivatePackages(vol);
2033                }
2034            }
2035
2036            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2037                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2038                    updateExternalMediaStatus(true, false);
2039                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2040                    updateExternalMediaStatus(false, false);
2041                }
2042            }
2043        }
2044
2045        @Override
2046        public void onVolumeForgotten(String fsUuid) {
2047            if (TextUtils.isEmpty(fsUuid)) {
2048                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2049                return;
2050            }
2051
2052            // Remove any apps installed on the forgotten volume
2053            synchronized (mPackages) {
2054                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2055                for (PackageSetting ps : packages) {
2056                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2057                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2058                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2059                }
2060
2061                mSettings.onVolumeForgotten(fsUuid);
2062                mSettings.writeLPr();
2063            }
2064        }
2065    };
2066
2067    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2068            String[] grantedPermissions) {
2069        for (int userId : userIds) {
2070            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2071        }
2072
2073        // We could have touched GID membership, so flush out packages.list
2074        synchronized (mPackages) {
2075            mSettings.writePackageListLPr();
2076        }
2077    }
2078
2079    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2080            String[] grantedPermissions) {
2081        SettingBase sb = (SettingBase) pkg.mExtras;
2082        if (sb == null) {
2083            return;
2084        }
2085
2086        PermissionsState permissionsState = sb.getPermissionsState();
2087
2088        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2089                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2090
2091        for (String permission : pkg.requestedPermissions) {
2092            final BasePermission bp;
2093            synchronized (mPackages) {
2094                bp = mSettings.mPermissions.get(permission);
2095            }
2096            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2097                    && (grantedPermissions == null
2098                           || ArrayUtils.contains(grantedPermissions, permission))) {
2099                final int flags = permissionsState.getPermissionFlags(permission, userId);
2100                // Installer cannot change immutable permissions.
2101                if ((flags & immutableFlags) == 0) {
2102                    grantRuntimePermission(pkg.packageName, permission, userId);
2103                }
2104            }
2105        }
2106    }
2107
2108    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2109        Bundle extras = null;
2110        switch (res.returnCode) {
2111            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2112                extras = new Bundle();
2113                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2114                        res.origPermission);
2115                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2116                        res.origPackage);
2117                break;
2118            }
2119            case PackageManager.INSTALL_SUCCEEDED: {
2120                extras = new Bundle();
2121                extras.putBoolean(Intent.EXTRA_REPLACING,
2122                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2123                break;
2124            }
2125        }
2126        return extras;
2127    }
2128
2129    void scheduleWriteSettingsLocked() {
2130        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2131            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2132        }
2133    }
2134
2135    void scheduleWritePackageListLocked(int userId) {
2136        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2137            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2138            msg.arg1 = userId;
2139            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2140        }
2141    }
2142
2143    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2144        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2145        scheduleWritePackageRestrictionsLocked(userId);
2146    }
2147
2148    void scheduleWritePackageRestrictionsLocked(int userId) {
2149        final int[] userIds = (userId == UserHandle.USER_ALL)
2150                ? sUserManager.getUserIds() : new int[]{userId};
2151        for (int nextUserId : userIds) {
2152            if (!sUserManager.exists(nextUserId)) return;
2153            mDirtyUsers.add(nextUserId);
2154            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2155                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2156            }
2157        }
2158    }
2159
2160    public static PackageManagerService main(Context context, Installer installer,
2161            boolean factoryTest, boolean onlyCore) {
2162        // Self-check for initial settings.
2163        PackageManagerServiceCompilerMapping.checkProperties();
2164
2165        PackageManagerService m = new PackageManagerService(context, installer,
2166                factoryTest, onlyCore);
2167        m.enableSystemUserPackages();
2168        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2169        // disabled after already being started.
2170        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2171                UserHandle.USER_SYSTEM);
2172        ServiceManager.addService("package", m);
2173        return m;
2174    }
2175
2176    private void enableSystemUserPackages() {
2177        if (!UserManager.isSplitSystemUser()) {
2178            return;
2179        }
2180        // For system user, enable apps based on the following conditions:
2181        // - app is whitelisted or belong to one of these groups:
2182        //   -- system app which has no launcher icons
2183        //   -- system app which has INTERACT_ACROSS_USERS permission
2184        //   -- system IME app
2185        // - app is not in the blacklist
2186        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2187        Set<String> enableApps = new ArraySet<>();
2188        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2189                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2190                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2191        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2192        enableApps.addAll(wlApps);
2193        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2194                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2195        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2196        enableApps.removeAll(blApps);
2197        Log.i(TAG, "Applications installed for system user: " + enableApps);
2198        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2199                UserHandle.SYSTEM);
2200        final int allAppsSize = allAps.size();
2201        synchronized (mPackages) {
2202            for (int i = 0; i < allAppsSize; i++) {
2203                String pName = allAps.get(i);
2204                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2205                // Should not happen, but we shouldn't be failing if it does
2206                if (pkgSetting == null) {
2207                    continue;
2208                }
2209                boolean install = enableApps.contains(pName);
2210                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2211                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2212                            + " for system user");
2213                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2214                }
2215            }
2216        }
2217    }
2218
2219    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2220        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2221                Context.DISPLAY_SERVICE);
2222        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2223    }
2224
2225    public PackageManagerService(Context context, Installer installer,
2226            boolean factoryTest, boolean onlyCore) {
2227        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2228                SystemClock.uptimeMillis());
2229
2230        if (mSdkVersion <= 0) {
2231            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2232        }
2233
2234        mContext = context;
2235        mFactoryTest = factoryTest;
2236        mOnlyCore = onlyCore;
2237        mMetrics = new DisplayMetrics();
2238        mSettings = new Settings(mPackages);
2239        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2250                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2251
2252        String separateProcesses = SystemProperties.get("debug.separate_processes");
2253        if (separateProcesses != null && separateProcesses.length() > 0) {
2254            if ("*".equals(separateProcesses)) {
2255                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2256                mSeparateProcesses = null;
2257                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2258            } else {
2259                mDefParseFlags = 0;
2260                mSeparateProcesses = separateProcesses.split(",");
2261                Slog.w(TAG, "Running with debug.separate_processes: "
2262                        + separateProcesses);
2263            }
2264        } else {
2265            mDefParseFlags = 0;
2266            mSeparateProcesses = null;
2267        }
2268
2269        mInstaller = installer;
2270        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2271                "*dexopt*");
2272        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2273
2274        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2275                FgThread.get().getLooper());
2276
2277        getDefaultDisplayMetrics(context, mMetrics);
2278
2279        SystemConfig systemConfig = SystemConfig.getInstance();
2280        mGlobalGids = systemConfig.getGlobalGids();
2281        mSystemPermissions = systemConfig.getSystemPermissions();
2282        mAvailableFeatures = systemConfig.getAvailableFeatures();
2283
2284        mProtectedPackages = new ProtectedPackages(mContext);
2285
2286        synchronized (mInstallLock) {
2287        // writer
2288        synchronized (mPackages) {
2289            mHandlerThread = new ServiceThread(TAG,
2290                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2291            mHandlerThread.start();
2292            mHandler = new PackageHandler(mHandlerThread.getLooper());
2293            mProcessLoggingHandler = new ProcessLoggingHandler();
2294            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2295
2296            File dataDir = Environment.getDataDirectory();
2297            mAppInstallDir = new File(dataDir, "app");
2298            mAppLib32InstallDir = new File(dataDir, "app-lib");
2299            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2300            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2301            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2302
2303            sUserManager = new UserManagerService(context, this, mPackages);
2304
2305            // Propagate permission configuration in to package manager.
2306            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2307                    = systemConfig.getPermissions();
2308            for (int i=0; i<permConfig.size(); i++) {
2309                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2310                BasePermission bp = mSettings.mPermissions.get(perm.name);
2311                if (bp == null) {
2312                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2313                    mSettings.mPermissions.put(perm.name, bp);
2314                }
2315                if (perm.gids != null) {
2316                    bp.setGids(perm.gids, perm.perUser);
2317                }
2318            }
2319
2320            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2321            for (int i=0; i<libConfig.size(); i++) {
2322                mSharedLibraries.put(libConfig.keyAt(i),
2323                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2324            }
2325
2326            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2327
2328            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2329
2330            String customResolverActivity = Resources.getSystem().getString(
2331                    R.string.config_customResolverActivity);
2332            if (TextUtils.isEmpty(customResolverActivity)) {
2333                customResolverActivity = null;
2334            } else {
2335                mCustomResolverComponentName = ComponentName.unflattenFromString(
2336                        customResolverActivity);
2337            }
2338
2339            long startTime = SystemClock.uptimeMillis();
2340
2341            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2342                    startTime);
2343
2344            // Set flag to monitor and not change apk file paths when
2345            // scanning install directories.
2346            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2347
2348            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2349            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2350
2351            if (bootClassPath == null) {
2352                Slog.w(TAG, "No BOOTCLASSPATH found!");
2353            }
2354
2355            if (systemServerClassPath == null) {
2356                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2357            }
2358
2359            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2360            final String[] dexCodeInstructionSets =
2361                    getDexCodeInstructionSets(
2362                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2363
2364            /**
2365             * Ensure all external libraries have had dexopt run on them.
2366             */
2367            if (mSharedLibraries.size() > 0) {
2368                // NOTE: For now, we're compiling these system "shared libraries"
2369                // (and framework jars) into all available architectures. It's possible
2370                // to compile them only when we come across an app that uses them (there's
2371                // already logic for that in scanPackageLI) but that adds some complexity.
2372                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2373                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2374                        final String lib = libEntry.path;
2375                        if (lib == null) {
2376                            continue;
2377                        }
2378
2379                        try {
2380                            // Shared libraries do not have profiles so we perform a full
2381                            // AOT compilation (if needed).
2382                            int dexoptNeeded = DexFile.getDexOptNeeded(
2383                                    lib, dexCodeInstructionSet,
2384                                    getCompilerFilterForReason(REASON_SHARED_APK),
2385                                    false /* newProfile */);
2386                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2387                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2388                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2389                                        getCompilerFilterForReason(REASON_SHARED_APK),
2390                                        StorageManager.UUID_PRIVATE_INTERNAL,
2391                                        SKIP_SHARED_LIBRARY_CHECK);
2392                            }
2393                        } catch (FileNotFoundException e) {
2394                            Slog.w(TAG, "Library not found: " + lib);
2395                        } catch (IOException | InstallerException e) {
2396                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2397                                    + e.getMessage());
2398                        }
2399                    }
2400                }
2401            }
2402
2403            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2404
2405            final VersionInfo ver = mSettings.getInternalVersion();
2406            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2407
2408            // when upgrading from pre-M, promote system app permissions from install to runtime
2409            mPromoteSystemApps =
2410                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2411
2412            // When upgrading from pre-N, we need to handle package extraction like first boot,
2413            // as there is no profiling data available.
2414            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2415
2416            // save off the names of pre-existing system packages prior to scanning; we don't
2417            // want to automatically grant runtime permissions for new system apps
2418            if (mPromoteSystemApps) {
2419                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2420                while (pkgSettingIter.hasNext()) {
2421                    PackageSetting ps = pkgSettingIter.next();
2422                    if (isSystemApp(ps)) {
2423                        mExistingSystemPackages.add(ps.name);
2424                    }
2425                }
2426            }
2427
2428            // Collect vendor overlay packages.
2429            // (Do this before scanning any apps.)
2430            // For security and version matching reason, only consider
2431            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2432            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2433            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2434                    | PackageParser.PARSE_IS_SYSTEM
2435                    | PackageParser.PARSE_IS_SYSTEM_DIR
2436                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2437
2438            // Find base frameworks (resource packages without code).
2439            scanDirTracedLI(frameworkDir, mDefParseFlags
2440                    | PackageParser.PARSE_IS_SYSTEM
2441                    | PackageParser.PARSE_IS_SYSTEM_DIR
2442                    | PackageParser.PARSE_IS_PRIVILEGED,
2443                    scanFlags | SCAN_NO_DEX, 0);
2444
2445            // Collected privileged system packages.
2446            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2447            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2448                    | PackageParser.PARSE_IS_SYSTEM
2449                    | PackageParser.PARSE_IS_SYSTEM_DIR
2450                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2451
2452            // Collect ordinary system packages.
2453            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2454            scanDirTracedLI(systemAppDir, mDefParseFlags
2455                    | PackageParser.PARSE_IS_SYSTEM
2456                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2457
2458            // Collect all vendor packages.
2459            File vendorAppDir = new File("/vendor/app");
2460            try {
2461                vendorAppDir = vendorAppDir.getCanonicalFile();
2462            } catch (IOException e) {
2463                // failed to look up canonical path, continue with original one
2464            }
2465            scanDirTracedLI(vendorAppDir, mDefParseFlags
2466                    | PackageParser.PARSE_IS_SYSTEM
2467                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2468
2469            // Collect all OEM packages.
2470            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2471            scanDirTracedLI(oemAppDir, mDefParseFlags
2472                    | PackageParser.PARSE_IS_SYSTEM
2473                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2474
2475            // Prune any system packages that no longer exist.
2476            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2477            if (!mOnlyCore) {
2478                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2479                while (psit.hasNext()) {
2480                    PackageSetting ps = psit.next();
2481
2482                    /*
2483                     * If this is not a system app, it can't be a
2484                     * disable system app.
2485                     */
2486                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2487                        continue;
2488                    }
2489
2490                    /*
2491                     * If the package is scanned, it's not erased.
2492                     */
2493                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2494                    if (scannedPkg != null) {
2495                        /*
2496                         * If the system app is both scanned and in the
2497                         * disabled packages list, then it must have been
2498                         * added via OTA. Remove it from the currently
2499                         * scanned package so the previously user-installed
2500                         * application can be scanned.
2501                         */
2502                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2503                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2504                                    + ps.name + "; removing system app.  Last known codePath="
2505                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2506                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2507                                    + scannedPkg.mVersionCode);
2508                            removePackageLI(scannedPkg, true);
2509                            mExpectingBetter.put(ps.name, ps.codePath);
2510                        }
2511
2512                        continue;
2513                    }
2514
2515                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2516                        psit.remove();
2517                        logCriticalInfo(Log.WARN, "System package " + ps.name
2518                                + " no longer exists; it's data will be wiped");
2519                        // Actual deletion of code and data will be handled by later
2520                        // reconciliation step
2521                    } else {
2522                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2523                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2524                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2525                        }
2526                    }
2527                }
2528            }
2529
2530            //look for any incomplete package installations
2531            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2532            for (int i = 0; i < deletePkgsList.size(); i++) {
2533                // Actual deletion of code and data will be handled by later
2534                // reconciliation step
2535                final String packageName = deletePkgsList.get(i).name;
2536                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2537                synchronized (mPackages) {
2538                    mSettings.removePackageLPw(packageName);
2539                }
2540            }
2541
2542            //delete tmp files
2543            deleteTempPackageFiles();
2544
2545            // Remove any shared userIDs that have no associated packages
2546            mSettings.pruneSharedUsersLPw();
2547
2548            if (!mOnlyCore) {
2549                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2550                        SystemClock.uptimeMillis());
2551                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2552
2553                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2554                        | PackageParser.PARSE_FORWARD_LOCK,
2555                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2556
2557                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2558                        | PackageParser.PARSE_IS_EPHEMERAL,
2559                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2560
2561                /**
2562                 * Remove disable package settings for any updated system
2563                 * apps that were removed via an OTA. If they're not a
2564                 * previously-updated app, remove them completely.
2565                 * Otherwise, just revoke their system-level permissions.
2566                 */
2567                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2568                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2569                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2570
2571                    String msg;
2572                    if (deletedPkg == null) {
2573                        msg = "Updated system package " + deletedAppName
2574                                + " no longer exists; it's data will be wiped";
2575                        // Actual deletion of code and data will be handled by later
2576                        // reconciliation step
2577                    } else {
2578                        msg = "Updated system app + " + deletedAppName
2579                                + " no longer present; removing system privileges for "
2580                                + deletedAppName;
2581
2582                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2583
2584                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2585                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2586                    }
2587                    logCriticalInfo(Log.WARN, msg);
2588                }
2589
2590                /**
2591                 * Make sure all system apps that we expected to appear on
2592                 * the userdata partition actually showed up. If they never
2593                 * appeared, crawl back and revive the system version.
2594                 */
2595                for (int i = 0; i < mExpectingBetter.size(); i++) {
2596                    final String packageName = mExpectingBetter.keyAt(i);
2597                    if (!mPackages.containsKey(packageName)) {
2598                        final File scanFile = mExpectingBetter.valueAt(i);
2599
2600                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2601                                + " but never showed up; reverting to system");
2602
2603                        int reparseFlags = mDefParseFlags;
2604                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2605                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2606                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2607                                    | PackageParser.PARSE_IS_PRIVILEGED;
2608                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2609                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2610                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2611                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2612                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2613                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2614                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2615                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2616                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2617                        } else {
2618                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2619                            continue;
2620                        }
2621
2622                        mSettings.enableSystemPackageLPw(packageName);
2623
2624                        try {
2625                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2626                        } catch (PackageManagerException e) {
2627                            Slog.e(TAG, "Failed to parse original system package: "
2628                                    + e.getMessage());
2629                        }
2630                    }
2631                }
2632            }
2633            mExpectingBetter.clear();
2634
2635            // Resolve protected action filters. Only the setup wizard is allowed to
2636            // have a high priority filter for these actions.
2637            mSetupWizardPackage = getSetupWizardPackageName();
2638            if (mProtectedFilters.size() > 0) {
2639                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2640                    Slog.i(TAG, "No setup wizard;"
2641                        + " All protected intents capped to priority 0");
2642                }
2643                for (ActivityIntentInfo filter : mProtectedFilters) {
2644                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2645                        if (DEBUG_FILTERS) {
2646                            Slog.i(TAG, "Found setup wizard;"
2647                                + " allow priority " + filter.getPriority() + ";"
2648                                + " package: " + filter.activity.info.packageName
2649                                + " activity: " + filter.activity.className
2650                                + " priority: " + filter.getPriority());
2651                        }
2652                        // skip setup wizard; allow it to keep the high priority filter
2653                        continue;
2654                    }
2655                    Slog.w(TAG, "Protected action; cap priority to 0;"
2656                            + " package: " + filter.activity.info.packageName
2657                            + " activity: " + filter.activity.className
2658                            + " origPrio: " + filter.getPriority());
2659                    filter.setPriority(0);
2660                }
2661            }
2662            mDeferProtectedFilters = false;
2663            mProtectedFilters.clear();
2664
2665            // Now that we know all of the shared libraries, update all clients to have
2666            // the correct library paths.
2667            updateAllSharedLibrariesLPw();
2668
2669            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2670                // NOTE: We ignore potential failures here during a system scan (like
2671                // the rest of the commands above) because there's precious little we
2672                // can do about it. A settings error is reported, though.
2673                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2674                        false /* boot complete */);
2675            }
2676
2677            // Now that we know all the packages we are keeping,
2678            // read and update their last usage times.
2679            mPackageUsage.readLP();
2680
2681            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2682                    SystemClock.uptimeMillis());
2683            Slog.i(TAG, "Time to scan packages: "
2684                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2685                    + " seconds");
2686
2687            // If the platform SDK has changed since the last time we booted,
2688            // we need to re-grant app permission to catch any new ones that
2689            // appear.  This is really a hack, and means that apps can in some
2690            // cases get permissions that the user didn't initially explicitly
2691            // allow...  it would be nice to have some better way to handle
2692            // this situation.
2693            int updateFlags = UPDATE_PERMISSIONS_ALL;
2694            if (ver.sdkVersion != mSdkVersion) {
2695                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2696                        + mSdkVersion + "; regranting permissions for internal storage");
2697                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2698            }
2699            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2700            ver.sdkVersion = mSdkVersion;
2701
2702            // If this is the first boot or an update from pre-M, and it is a normal
2703            // boot, then we need to initialize the default preferred apps across
2704            // all defined users.
2705            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2706                for (UserInfo user : sUserManager.getUsers(true)) {
2707                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2708                    applyFactoryDefaultBrowserLPw(user.id);
2709                    primeDomainVerificationsLPw(user.id);
2710                }
2711            }
2712
2713            // Prepare storage for system user really early during boot,
2714            // since core system apps like SettingsProvider and SystemUI
2715            // can't wait for user to start
2716            final int storageFlags;
2717            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2718                storageFlags = StorageManager.FLAG_STORAGE_DE;
2719            } else {
2720                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2721            }
2722            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2723                    storageFlags);
2724
2725            // If this is first boot after an OTA, and a normal boot, then
2726            // we need to clear code cache directories.
2727            // Note that we do *not* clear the application profiles. These remain valid
2728            // across OTAs and are used to drive profile verification (post OTA) and
2729            // profile compilation (without waiting to collect a fresh set of profiles).
2730            if (mIsUpgrade && !onlyCore) {
2731                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2732                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2733                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2734                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2735                        // No apps are running this early, so no need to freeze
2736                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2737                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2738                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2739                    }
2740                }
2741                ver.fingerprint = Build.FINGERPRINT;
2742            }
2743
2744            checkDefaultBrowser();
2745
2746            // clear only after permissions and other defaults have been updated
2747            mExistingSystemPackages.clear();
2748            mPromoteSystemApps = false;
2749
2750            // All the changes are done during package scanning.
2751            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2752
2753            // can downgrade to reader
2754            mSettings.writeLPr();
2755
2756            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2757            // early on (before the package manager declares itself as early) because other
2758            // components in the system server might ask for package contexts for these apps.
2759            //
2760            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2761            // (i.e, that the data partition is unavailable).
2762            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2763                long start = System.nanoTime();
2764                List<PackageParser.Package> coreApps = new ArrayList<>();
2765                for (PackageParser.Package pkg : mPackages.values()) {
2766                    if (pkg.coreApp) {
2767                        coreApps.add(pkg);
2768                    }
2769                }
2770
2771                int[] stats = performDexOpt(coreApps, false,
2772                        getCompilerFilterForReason(REASON_CORE_APP));
2773
2774                final int elapsedTimeSeconds =
2775                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2776                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2777
2778                if (DEBUG_DEXOPT) {
2779                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2780                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2781                }
2782
2783
2784                // TODO: Should we log these stats to tron too ?
2785                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2786                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2787                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2788                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2789            }
2790
2791            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2792                    SystemClock.uptimeMillis());
2793
2794            if (!mOnlyCore) {
2795                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2796                mRequiredInstallerPackage = getRequiredInstallerLPr();
2797                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2798                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2799                        mIntentFilterVerifierComponent);
2800                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2801                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2802                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2803                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2804            } else {
2805                mRequiredVerifierPackage = null;
2806                mRequiredInstallerPackage = null;
2807                mIntentFilterVerifierComponent = null;
2808                mIntentFilterVerifier = null;
2809                mServicesSystemSharedLibraryPackageName = null;
2810                mSharedSystemSharedLibraryPackageName = null;
2811            }
2812
2813            mInstallerService = new PackageInstallerService(context, this);
2814
2815            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2816            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2817            // both the installer and resolver must be present to enable ephemeral
2818            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2819                if (DEBUG_EPHEMERAL) {
2820                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2821                            + " installer:" + ephemeralInstallerComponent);
2822                }
2823                mEphemeralResolverComponent = ephemeralResolverComponent;
2824                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2825                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2826                mEphemeralResolverConnection =
2827                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2828            } else {
2829                if (DEBUG_EPHEMERAL) {
2830                    final String missingComponent =
2831                            (ephemeralResolverComponent == null)
2832                            ? (ephemeralInstallerComponent == null)
2833                                    ? "resolver and installer"
2834                                    : "resolver"
2835                            : "installer";
2836                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2837                }
2838                mEphemeralResolverComponent = null;
2839                mEphemeralInstallerComponent = null;
2840                mEphemeralResolverConnection = null;
2841            }
2842
2843            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2844        } // synchronized (mPackages)
2845        } // synchronized (mInstallLock)
2846
2847        // Now after opening every single application zip, make sure they
2848        // are all flushed.  Not really needed, but keeps things nice and
2849        // tidy.
2850        Runtime.getRuntime().gc();
2851
2852        // The initial scanning above does many calls into installd while
2853        // holding the mPackages lock, but we're mostly interested in yelling
2854        // once we have a booted system.
2855        mInstaller.setWarnIfHeld(mPackages);
2856
2857        // Expose private service for system components to use.
2858        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2859    }
2860
2861    @Override
2862    public boolean isFirstBoot() {
2863        return !mRestoredSettings;
2864    }
2865
2866    @Override
2867    public boolean isOnlyCoreApps() {
2868        return mOnlyCore;
2869    }
2870
2871    @Override
2872    public boolean isUpgrade() {
2873        return mIsUpgrade;
2874    }
2875
2876    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2877        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2878
2879        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2880                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2881                UserHandle.USER_SYSTEM);
2882        if (matches.size() == 1) {
2883            return matches.get(0).getComponentInfo().packageName;
2884        } else {
2885            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2886            return null;
2887        }
2888    }
2889
2890    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2891        synchronized (mPackages) {
2892            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2893            if (libraryEntry == null) {
2894                throw new IllegalStateException("Missing required shared library:" + libraryName);
2895            }
2896            return libraryEntry.apk;
2897        }
2898    }
2899
2900    private @NonNull String getRequiredInstallerLPr() {
2901        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2902        intent.addCategory(Intent.CATEGORY_DEFAULT);
2903        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2904
2905        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2906                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2907                UserHandle.USER_SYSTEM);
2908        if (matches.size() == 1) {
2909            ResolveInfo resolveInfo = matches.get(0);
2910            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2911                throw new RuntimeException("The installer must be a privileged app");
2912            }
2913            return matches.get(0).getComponentInfo().packageName;
2914        } else {
2915            throw new RuntimeException("There must be exactly one installer; found " + matches);
2916        }
2917    }
2918
2919    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2920        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2921
2922        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2923                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2924                UserHandle.USER_SYSTEM);
2925        ResolveInfo best = null;
2926        final int N = matches.size();
2927        for (int i = 0; i < N; i++) {
2928            final ResolveInfo cur = matches.get(i);
2929            final String packageName = cur.getComponentInfo().packageName;
2930            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2931                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2932                continue;
2933            }
2934
2935            if (best == null || cur.priority > best.priority) {
2936                best = cur;
2937            }
2938        }
2939
2940        if (best != null) {
2941            return best.getComponentInfo().getComponentName();
2942        } else {
2943            throw new RuntimeException("There must be at least one intent filter verifier");
2944        }
2945    }
2946
2947    private @Nullable ComponentName getEphemeralResolverLPr() {
2948        final String[] packageArray =
2949                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2950        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2951            if (DEBUG_EPHEMERAL) {
2952                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2953            }
2954            return null;
2955        }
2956
2957        final int resolveFlags =
2958                MATCH_DIRECT_BOOT_AWARE
2959                | MATCH_DIRECT_BOOT_UNAWARE
2960                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2961        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2962        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2963                resolveFlags, UserHandle.USER_SYSTEM);
2964
2965        final int N = resolvers.size();
2966        if (N == 0) {
2967            if (DEBUG_EPHEMERAL) {
2968                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2969            }
2970            return null;
2971        }
2972
2973        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2974        for (int i = 0; i < N; i++) {
2975            final ResolveInfo info = resolvers.get(i);
2976
2977            if (info.serviceInfo == null) {
2978                continue;
2979            }
2980
2981            final String packageName = info.serviceInfo.packageName;
2982            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2983                if (DEBUG_EPHEMERAL) {
2984                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2985                            + " pkg: " + packageName + ", info:" + info);
2986                }
2987                continue;
2988            }
2989
2990            if (DEBUG_EPHEMERAL) {
2991                Slog.v(TAG, "Ephemeral resolver found;"
2992                        + " pkg: " + packageName + ", info:" + info);
2993            }
2994            return new ComponentName(packageName, info.serviceInfo.name);
2995        }
2996        if (DEBUG_EPHEMERAL) {
2997            Slog.v(TAG, "Ephemeral resolver NOT found");
2998        }
2999        return null;
3000    }
3001
3002    private @Nullable ComponentName getEphemeralInstallerLPr() {
3003        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3004        intent.addCategory(Intent.CATEGORY_DEFAULT);
3005        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3006
3007        final int resolveFlags =
3008                MATCH_DIRECT_BOOT_AWARE
3009                | MATCH_DIRECT_BOOT_UNAWARE
3010                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3011        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3012                resolveFlags, UserHandle.USER_SYSTEM);
3013        if (matches.size() == 0) {
3014            return null;
3015        } else if (matches.size() == 1) {
3016            return matches.get(0).getComponentInfo().getComponentName();
3017        } else {
3018            throw new RuntimeException(
3019                    "There must be at most one ephemeral installer; found " + matches);
3020        }
3021    }
3022
3023    private void primeDomainVerificationsLPw(int userId) {
3024        if (DEBUG_DOMAIN_VERIFICATION) {
3025            Slog.d(TAG, "Priming domain verifications in user " + userId);
3026        }
3027
3028        SystemConfig systemConfig = SystemConfig.getInstance();
3029        ArraySet<String> packages = systemConfig.getLinkedApps();
3030        ArraySet<String> domains = new ArraySet<String>();
3031
3032        for (String packageName : packages) {
3033            PackageParser.Package pkg = mPackages.get(packageName);
3034            if (pkg != null) {
3035                if (!pkg.isSystemApp()) {
3036                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3037                    continue;
3038                }
3039
3040                domains.clear();
3041                for (PackageParser.Activity a : pkg.activities) {
3042                    for (ActivityIntentInfo filter : a.intents) {
3043                        if (hasValidDomains(filter)) {
3044                            domains.addAll(filter.getHostsList());
3045                        }
3046                    }
3047                }
3048
3049                if (domains.size() > 0) {
3050                    if (DEBUG_DOMAIN_VERIFICATION) {
3051                        Slog.v(TAG, "      + " + packageName);
3052                    }
3053                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3054                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3055                    // and then 'always' in the per-user state actually used for intent resolution.
3056                    final IntentFilterVerificationInfo ivi;
3057                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3058                            new ArrayList<String>(domains));
3059                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3060                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3061                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3062                } else {
3063                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3064                            + "' does not handle web links");
3065                }
3066            } else {
3067                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3068            }
3069        }
3070
3071        scheduleWritePackageRestrictionsLocked(userId);
3072        scheduleWriteSettingsLocked();
3073    }
3074
3075    private void applyFactoryDefaultBrowserLPw(int userId) {
3076        // The default browser app's package name is stored in a string resource,
3077        // with a product-specific overlay used for vendor customization.
3078        String browserPkg = mContext.getResources().getString(
3079                com.android.internal.R.string.default_browser);
3080        if (!TextUtils.isEmpty(browserPkg)) {
3081            // non-empty string => required to be a known package
3082            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3083            if (ps == null) {
3084                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3085                browserPkg = null;
3086            } else {
3087                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3088            }
3089        }
3090
3091        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3092        // default.  If there's more than one, just leave everything alone.
3093        if (browserPkg == null) {
3094            calculateDefaultBrowserLPw(userId);
3095        }
3096    }
3097
3098    private void calculateDefaultBrowserLPw(int userId) {
3099        List<String> allBrowsers = resolveAllBrowserApps(userId);
3100        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3101        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3102    }
3103
3104    private List<String> resolveAllBrowserApps(int userId) {
3105        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3106        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3107                PackageManager.MATCH_ALL, userId);
3108
3109        final int count = list.size();
3110        List<String> result = new ArrayList<String>(count);
3111        for (int i=0; i<count; i++) {
3112            ResolveInfo info = list.get(i);
3113            if (info.activityInfo == null
3114                    || !info.handleAllWebDataURI
3115                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3116                    || result.contains(info.activityInfo.packageName)) {
3117                continue;
3118            }
3119            result.add(info.activityInfo.packageName);
3120        }
3121
3122        return result;
3123    }
3124
3125    private boolean packageIsBrowser(String packageName, int userId) {
3126        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3127                PackageManager.MATCH_ALL, userId);
3128        final int N = list.size();
3129        for (int i = 0; i < N; i++) {
3130            ResolveInfo info = list.get(i);
3131            if (packageName.equals(info.activityInfo.packageName)) {
3132                return true;
3133            }
3134        }
3135        return false;
3136    }
3137
3138    private void checkDefaultBrowser() {
3139        final int myUserId = UserHandle.myUserId();
3140        final String packageName = getDefaultBrowserPackageName(myUserId);
3141        if (packageName != null) {
3142            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3143            if (info == null) {
3144                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3145                synchronized (mPackages) {
3146                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3147                }
3148            }
3149        }
3150    }
3151
3152    @Override
3153    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3154            throws RemoteException {
3155        try {
3156            return super.onTransact(code, data, reply, flags);
3157        } catch (RuntimeException e) {
3158            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3159                Slog.wtf(TAG, "Package Manager Crash", e);
3160            }
3161            throw e;
3162        }
3163    }
3164
3165    static int[] appendInts(int[] cur, int[] add) {
3166        if (add == null) return cur;
3167        if (cur == null) return add;
3168        final int N = add.length;
3169        for (int i=0; i<N; i++) {
3170            cur = appendInt(cur, add[i]);
3171        }
3172        return cur;
3173    }
3174
3175    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3176        if (!sUserManager.exists(userId)) return null;
3177        if (ps == null) {
3178            return null;
3179        }
3180        final PackageParser.Package p = ps.pkg;
3181        if (p == null) {
3182            return null;
3183        }
3184
3185        final PermissionsState permissionsState = ps.getPermissionsState();
3186
3187        final int[] gids = permissionsState.computeGids(userId);
3188        final Set<String> permissions = permissionsState.getPermissions(userId);
3189        final PackageUserState state = ps.readUserState(userId);
3190
3191        return PackageParser.generatePackageInfo(p, gids, flags,
3192                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3193    }
3194
3195    @Override
3196    public void checkPackageStartable(String packageName, int userId) {
3197        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3198
3199        synchronized (mPackages) {
3200            final PackageSetting ps = mSettings.mPackages.get(packageName);
3201            if (ps == null) {
3202                throw new SecurityException("Package " + packageName + " was not found!");
3203            }
3204
3205            if (!ps.getInstalled(userId)) {
3206                throw new SecurityException(
3207                        "Package " + packageName + " was not installed for user " + userId + "!");
3208            }
3209
3210            if (mSafeMode && !ps.isSystem()) {
3211                throw new SecurityException("Package " + packageName + " not a system app!");
3212            }
3213
3214            if (mFrozenPackages.contains(packageName)) {
3215                throw new SecurityException("Package " + packageName + " is currently frozen!");
3216            }
3217
3218            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3219                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3220                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3221            }
3222        }
3223    }
3224
3225    @Override
3226    public boolean isPackageAvailable(String packageName, int userId) {
3227        if (!sUserManager.exists(userId)) return false;
3228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3229                false /* requireFullPermission */, false /* checkShell */, "is package available");
3230        synchronized (mPackages) {
3231            PackageParser.Package p = mPackages.get(packageName);
3232            if (p != null) {
3233                final PackageSetting ps = (PackageSetting) p.mExtras;
3234                if (ps != null) {
3235                    final PackageUserState state = ps.readUserState(userId);
3236                    if (state != null) {
3237                        return PackageParser.isAvailable(state);
3238                    }
3239                }
3240            }
3241        }
3242        return false;
3243    }
3244
3245    @Override
3246    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3247        if (!sUserManager.exists(userId)) return null;
3248        flags = updateFlagsForPackage(flags, userId, packageName);
3249        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3250                false /* requireFullPermission */, false /* checkShell */, "get package info");
3251        // reader
3252        synchronized (mPackages) {
3253            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3254            PackageParser.Package p = null;
3255            if (matchFactoryOnly) {
3256                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3257                if (ps != null) {
3258                    return generatePackageInfo(ps, flags, userId);
3259                }
3260            }
3261            if (p == null) {
3262                p = mPackages.get(packageName);
3263                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3264                    return null;
3265                }
3266            }
3267            if (DEBUG_PACKAGE_INFO)
3268                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3269            if (p != null) {
3270                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3271            }
3272            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3273                final PackageSetting ps = mSettings.mPackages.get(packageName);
3274                return generatePackageInfo(ps, flags, userId);
3275            }
3276        }
3277        return null;
3278    }
3279
3280    @Override
3281    public String[] currentToCanonicalPackageNames(String[] names) {
3282        String[] out = new String[names.length];
3283        // reader
3284        synchronized (mPackages) {
3285            for (int i=names.length-1; i>=0; i--) {
3286                PackageSetting ps = mSettings.mPackages.get(names[i]);
3287                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3288            }
3289        }
3290        return out;
3291    }
3292
3293    @Override
3294    public String[] canonicalToCurrentPackageNames(String[] names) {
3295        String[] out = new String[names.length];
3296        // reader
3297        synchronized (mPackages) {
3298            for (int i=names.length-1; i>=0; i--) {
3299                String cur = mSettings.mRenamedPackages.get(names[i]);
3300                out[i] = cur != null ? cur : names[i];
3301            }
3302        }
3303        return out;
3304    }
3305
3306    @Override
3307    public int getPackageUid(String packageName, int flags, int userId) {
3308        if (!sUserManager.exists(userId)) return -1;
3309        flags = updateFlagsForPackage(flags, userId, packageName);
3310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3311                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3312
3313        // reader
3314        synchronized (mPackages) {
3315            final PackageParser.Package p = mPackages.get(packageName);
3316            if (p != null && p.isMatch(flags)) {
3317                return UserHandle.getUid(userId, p.applicationInfo.uid);
3318            }
3319            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3320                final PackageSetting ps = mSettings.mPackages.get(packageName);
3321                if (ps != null && ps.isMatch(flags)) {
3322                    return UserHandle.getUid(userId, ps.appId);
3323                }
3324            }
3325        }
3326
3327        return -1;
3328    }
3329
3330    @Override
3331    public int[] getPackageGids(String packageName, int flags, int userId) {
3332        if (!sUserManager.exists(userId)) return null;
3333        flags = updateFlagsForPackage(flags, userId, packageName);
3334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3335                false /* requireFullPermission */, false /* checkShell */,
3336                "getPackageGids");
3337
3338        // reader
3339        synchronized (mPackages) {
3340            final PackageParser.Package p = mPackages.get(packageName);
3341            if (p != null && p.isMatch(flags)) {
3342                PackageSetting ps = (PackageSetting) p.mExtras;
3343                return ps.getPermissionsState().computeGids(userId);
3344            }
3345            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3346                final PackageSetting ps = mSettings.mPackages.get(packageName);
3347                if (ps != null && ps.isMatch(flags)) {
3348                    return ps.getPermissionsState().computeGids(userId);
3349                }
3350            }
3351        }
3352
3353        return null;
3354    }
3355
3356    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3357        if (bp.perm != null) {
3358            return PackageParser.generatePermissionInfo(bp.perm, flags);
3359        }
3360        PermissionInfo pi = new PermissionInfo();
3361        pi.name = bp.name;
3362        pi.packageName = bp.sourcePackage;
3363        pi.nonLocalizedLabel = bp.name;
3364        pi.protectionLevel = bp.protectionLevel;
3365        return pi;
3366    }
3367
3368    @Override
3369    public PermissionInfo getPermissionInfo(String name, int flags) {
3370        // reader
3371        synchronized (mPackages) {
3372            final BasePermission p = mSettings.mPermissions.get(name);
3373            if (p != null) {
3374                return generatePermissionInfo(p, flags);
3375            }
3376            return null;
3377        }
3378    }
3379
3380    @Override
3381    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3382            int flags) {
3383        // reader
3384        synchronized (mPackages) {
3385            if (group != null && !mPermissionGroups.containsKey(group)) {
3386                // This is thrown as NameNotFoundException
3387                return null;
3388            }
3389
3390            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3391            for (BasePermission p : mSettings.mPermissions.values()) {
3392                if (group == null) {
3393                    if (p.perm == null || p.perm.info.group == null) {
3394                        out.add(generatePermissionInfo(p, flags));
3395                    }
3396                } else {
3397                    if (p.perm != null && group.equals(p.perm.info.group)) {
3398                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3399                    }
3400                }
3401            }
3402            return new ParceledListSlice<>(out);
3403        }
3404    }
3405
3406    @Override
3407    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3408        // reader
3409        synchronized (mPackages) {
3410            return PackageParser.generatePermissionGroupInfo(
3411                    mPermissionGroups.get(name), flags);
3412        }
3413    }
3414
3415    @Override
3416    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3417        // reader
3418        synchronized (mPackages) {
3419            final int N = mPermissionGroups.size();
3420            ArrayList<PermissionGroupInfo> out
3421                    = new ArrayList<PermissionGroupInfo>(N);
3422            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3423                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3424            }
3425            return new ParceledListSlice<>(out);
3426        }
3427    }
3428
3429    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3430            int userId) {
3431        if (!sUserManager.exists(userId)) return null;
3432        PackageSetting ps = mSettings.mPackages.get(packageName);
3433        if (ps != null) {
3434            if (ps.pkg == null) {
3435                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3436                if (pInfo != null) {
3437                    return pInfo.applicationInfo;
3438                }
3439                return null;
3440            }
3441            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3442                    ps.readUserState(userId), userId);
3443        }
3444        return null;
3445    }
3446
3447    @Override
3448    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3449        if (!sUserManager.exists(userId)) return null;
3450        flags = updateFlagsForApplication(flags, userId, packageName);
3451        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3452                false /* requireFullPermission */, false /* checkShell */, "get application info");
3453        // writer
3454        synchronized (mPackages) {
3455            PackageParser.Package p = mPackages.get(packageName);
3456            if (DEBUG_PACKAGE_INFO) Log.v(
3457                    TAG, "getApplicationInfo " + packageName
3458                    + ": " + p);
3459            if (p != null) {
3460                PackageSetting ps = mSettings.mPackages.get(packageName);
3461                if (ps == null) return null;
3462                // Note: isEnabledLP() does not apply here - always return info
3463                return PackageParser.generateApplicationInfo(
3464                        p, flags, ps.readUserState(userId), userId);
3465            }
3466            if ("android".equals(packageName)||"system".equals(packageName)) {
3467                return mAndroidApplication;
3468            }
3469            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3470                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3471            }
3472        }
3473        return null;
3474    }
3475
3476    @Override
3477    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3478            final IPackageDataObserver observer) {
3479        mContext.enforceCallingOrSelfPermission(
3480                android.Manifest.permission.CLEAR_APP_CACHE, null);
3481        // Queue up an async operation since clearing cache may take a little while.
3482        mHandler.post(new Runnable() {
3483            public void run() {
3484                mHandler.removeCallbacks(this);
3485                boolean success = true;
3486                synchronized (mInstallLock) {
3487                    try {
3488                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3489                    } catch (InstallerException e) {
3490                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3491                        success = false;
3492                    }
3493                }
3494                if (observer != null) {
3495                    try {
3496                        observer.onRemoveCompleted(null, success);
3497                    } catch (RemoteException e) {
3498                        Slog.w(TAG, "RemoveException when invoking call back");
3499                    }
3500                }
3501            }
3502        });
3503    }
3504
3505    @Override
3506    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3507            final IntentSender pi) {
3508        mContext.enforceCallingOrSelfPermission(
3509                android.Manifest.permission.CLEAR_APP_CACHE, null);
3510        // Queue up an async operation since clearing cache may take a little while.
3511        mHandler.post(new Runnable() {
3512            public void run() {
3513                mHandler.removeCallbacks(this);
3514                boolean success = true;
3515                synchronized (mInstallLock) {
3516                    try {
3517                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3518                    } catch (InstallerException e) {
3519                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3520                        success = false;
3521                    }
3522                }
3523                if(pi != null) {
3524                    try {
3525                        // Callback via pending intent
3526                        int code = success ? 1 : 0;
3527                        pi.sendIntent(null, code, null,
3528                                null, null);
3529                    } catch (SendIntentException e1) {
3530                        Slog.i(TAG, "Failed to send pending intent");
3531                    }
3532                }
3533            }
3534        });
3535    }
3536
3537    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3538        synchronized (mInstallLock) {
3539            try {
3540                mInstaller.freeCache(volumeUuid, freeStorageSize);
3541            } catch (InstallerException e) {
3542                throw new IOException("Failed to free enough space", e);
3543            }
3544        }
3545    }
3546
3547    /**
3548     * Update given flags based on encryption status of current user.
3549     */
3550    private int updateFlags(int flags, int userId) {
3551        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3552                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3553            // Caller expressed an explicit opinion about what encryption
3554            // aware/unaware components they want to see, so fall through and
3555            // give them what they want
3556        } else {
3557            // Caller expressed no opinion, so match based on user state
3558            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3559                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3560            } else {
3561                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3562            }
3563        }
3564        return flags;
3565    }
3566
3567    private UserManagerInternal getUserManagerInternal() {
3568        if (mUserManagerInternal == null) {
3569            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3570        }
3571        return mUserManagerInternal;
3572    }
3573
3574    /**
3575     * Update given flags when being used to request {@link PackageInfo}.
3576     */
3577    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3578        boolean triaged = true;
3579        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3580                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3581            // Caller is asking for component details, so they'd better be
3582            // asking for specific encryption matching behavior, or be triaged
3583            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3584                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3585                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3586                triaged = false;
3587            }
3588        }
3589        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3590                | PackageManager.MATCH_SYSTEM_ONLY
3591                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3592            triaged = false;
3593        }
3594        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3595            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3596                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3597        }
3598        return updateFlags(flags, userId);
3599    }
3600
3601    /**
3602     * Update given flags when being used to request {@link ApplicationInfo}.
3603     */
3604    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3605        return updateFlagsForPackage(flags, userId, cookie);
3606    }
3607
3608    /**
3609     * Update given flags when being used to request {@link ComponentInfo}.
3610     */
3611    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3612        if (cookie instanceof Intent) {
3613            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3614                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3615            }
3616        }
3617
3618        boolean triaged = true;
3619        // Caller is asking for component details, so they'd better be
3620        // asking for specific encryption matching behavior, or be triaged
3621        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3622                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3623                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3624            triaged = false;
3625        }
3626        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3627            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3628                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3629        }
3630
3631        return updateFlags(flags, userId);
3632    }
3633
3634    /**
3635     * Update given flags when being used to request {@link ResolveInfo}.
3636     */
3637    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3638        // Safe mode means we shouldn't match any third-party components
3639        if (mSafeMode) {
3640            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3641        }
3642
3643        return updateFlagsForComponent(flags, userId, cookie);
3644    }
3645
3646    @Override
3647    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3648        if (!sUserManager.exists(userId)) return null;
3649        flags = updateFlagsForComponent(flags, userId, component);
3650        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3651                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3652        synchronized (mPackages) {
3653            PackageParser.Activity a = mActivities.mActivities.get(component);
3654
3655            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3656            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3657                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3658                if (ps == null) return null;
3659                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3660                        userId);
3661            }
3662            if (mResolveComponentName.equals(component)) {
3663                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3664                        new PackageUserState(), userId);
3665            }
3666        }
3667        return null;
3668    }
3669
3670    @Override
3671    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3672            String resolvedType) {
3673        synchronized (mPackages) {
3674            if (component.equals(mResolveComponentName)) {
3675                // The resolver supports EVERYTHING!
3676                return true;
3677            }
3678            PackageParser.Activity a = mActivities.mActivities.get(component);
3679            if (a == null) {
3680                return false;
3681            }
3682            for (int i=0; i<a.intents.size(); i++) {
3683                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3684                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3685                    return true;
3686                }
3687            }
3688            return false;
3689        }
3690    }
3691
3692    @Override
3693    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3694        if (!sUserManager.exists(userId)) return null;
3695        flags = updateFlagsForComponent(flags, userId, component);
3696        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3697                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3698        synchronized (mPackages) {
3699            PackageParser.Activity a = mReceivers.mActivities.get(component);
3700            if (DEBUG_PACKAGE_INFO) Log.v(
3701                TAG, "getReceiverInfo " + component + ": " + a);
3702            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3703                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3704                if (ps == null) return null;
3705                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3706                        userId);
3707            }
3708        }
3709        return null;
3710    }
3711
3712    @Override
3713    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3714        if (!sUserManager.exists(userId)) return null;
3715        flags = updateFlagsForComponent(flags, userId, component);
3716        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3717                false /* requireFullPermission */, false /* checkShell */, "get service info");
3718        synchronized (mPackages) {
3719            PackageParser.Service s = mServices.mServices.get(component);
3720            if (DEBUG_PACKAGE_INFO) Log.v(
3721                TAG, "getServiceInfo " + component + ": " + s);
3722            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3723                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3724                if (ps == null) return null;
3725                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3726                        userId);
3727            }
3728        }
3729        return null;
3730    }
3731
3732    @Override
3733    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3734        if (!sUserManager.exists(userId)) return null;
3735        flags = updateFlagsForComponent(flags, userId, component);
3736        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3737                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3738        synchronized (mPackages) {
3739            PackageParser.Provider p = mProviders.mProviders.get(component);
3740            if (DEBUG_PACKAGE_INFO) Log.v(
3741                TAG, "getProviderInfo " + component + ": " + p);
3742            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3743                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3744                if (ps == null) return null;
3745                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3746                        userId);
3747            }
3748        }
3749        return null;
3750    }
3751
3752    @Override
3753    public String[] getSystemSharedLibraryNames() {
3754        Set<String> libSet;
3755        synchronized (mPackages) {
3756            libSet = mSharedLibraries.keySet();
3757            int size = libSet.size();
3758            if (size > 0) {
3759                String[] libs = new String[size];
3760                libSet.toArray(libs);
3761                return libs;
3762            }
3763        }
3764        return null;
3765    }
3766
3767    @Override
3768    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3769        synchronized (mPackages) {
3770            return mServicesSystemSharedLibraryPackageName;
3771        }
3772    }
3773
3774    @Override
3775    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3776        synchronized (mPackages) {
3777            return mSharedSystemSharedLibraryPackageName;
3778        }
3779    }
3780
3781    @Override
3782    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3783        synchronized (mPackages) {
3784            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3785
3786            final FeatureInfo fi = new FeatureInfo();
3787            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3788                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3789            res.add(fi);
3790
3791            return new ParceledListSlice<>(res);
3792        }
3793    }
3794
3795    @Override
3796    public boolean hasSystemFeature(String name, int version) {
3797        synchronized (mPackages) {
3798            final FeatureInfo feat = mAvailableFeatures.get(name);
3799            if (feat == null) {
3800                return false;
3801            } else {
3802                return feat.version >= version;
3803            }
3804        }
3805    }
3806
3807    @Override
3808    public int checkPermission(String permName, String pkgName, int userId) {
3809        if (!sUserManager.exists(userId)) {
3810            return PackageManager.PERMISSION_DENIED;
3811        }
3812
3813        synchronized (mPackages) {
3814            final PackageParser.Package p = mPackages.get(pkgName);
3815            if (p != null && p.mExtras != null) {
3816                final PackageSetting ps = (PackageSetting) p.mExtras;
3817                final PermissionsState permissionsState = ps.getPermissionsState();
3818                if (permissionsState.hasPermission(permName, userId)) {
3819                    return PackageManager.PERMISSION_GRANTED;
3820                }
3821                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3822                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3823                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3824                    return PackageManager.PERMISSION_GRANTED;
3825                }
3826            }
3827        }
3828
3829        return PackageManager.PERMISSION_DENIED;
3830    }
3831
3832    @Override
3833    public int checkUidPermission(String permName, int uid) {
3834        final int userId = UserHandle.getUserId(uid);
3835
3836        if (!sUserManager.exists(userId)) {
3837            return PackageManager.PERMISSION_DENIED;
3838        }
3839
3840        synchronized (mPackages) {
3841            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3842            if (obj != null) {
3843                final SettingBase ps = (SettingBase) obj;
3844                final PermissionsState permissionsState = ps.getPermissionsState();
3845                if (permissionsState.hasPermission(permName, userId)) {
3846                    return PackageManager.PERMISSION_GRANTED;
3847                }
3848                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3849                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3850                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3851                    return PackageManager.PERMISSION_GRANTED;
3852                }
3853            } else {
3854                ArraySet<String> perms = mSystemPermissions.get(uid);
3855                if (perms != null) {
3856                    if (perms.contains(permName)) {
3857                        return PackageManager.PERMISSION_GRANTED;
3858                    }
3859                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3860                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3861                        return PackageManager.PERMISSION_GRANTED;
3862                    }
3863                }
3864            }
3865        }
3866
3867        return PackageManager.PERMISSION_DENIED;
3868    }
3869
3870    @Override
3871    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3872        if (UserHandle.getCallingUserId() != userId) {
3873            mContext.enforceCallingPermission(
3874                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3875                    "isPermissionRevokedByPolicy for user " + userId);
3876        }
3877
3878        if (checkPermission(permission, packageName, userId)
3879                == PackageManager.PERMISSION_GRANTED) {
3880            return false;
3881        }
3882
3883        final long identity = Binder.clearCallingIdentity();
3884        try {
3885            final int flags = getPermissionFlags(permission, packageName, userId);
3886            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3887        } finally {
3888            Binder.restoreCallingIdentity(identity);
3889        }
3890    }
3891
3892    @Override
3893    public String getPermissionControllerPackageName() {
3894        synchronized (mPackages) {
3895            return mRequiredInstallerPackage;
3896        }
3897    }
3898
3899    /**
3900     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3901     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3902     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3903     * @param message the message to log on security exception
3904     */
3905    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3906            boolean checkShell, String message) {
3907        if (userId < 0) {
3908            throw new IllegalArgumentException("Invalid userId " + userId);
3909        }
3910        if (checkShell) {
3911            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3912        }
3913        if (userId == UserHandle.getUserId(callingUid)) return;
3914        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3915            if (requireFullPermission) {
3916                mContext.enforceCallingOrSelfPermission(
3917                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3918            } else {
3919                try {
3920                    mContext.enforceCallingOrSelfPermission(
3921                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3922                } catch (SecurityException se) {
3923                    mContext.enforceCallingOrSelfPermission(
3924                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3925                }
3926            }
3927        }
3928    }
3929
3930    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3931        if (callingUid == Process.SHELL_UID) {
3932            if (userHandle >= 0
3933                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3934                throw new SecurityException("Shell does not have permission to access user "
3935                        + userHandle);
3936            } else if (userHandle < 0) {
3937                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3938                        + Debug.getCallers(3));
3939            }
3940        }
3941    }
3942
3943    private BasePermission findPermissionTreeLP(String permName) {
3944        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3945            if (permName.startsWith(bp.name) &&
3946                    permName.length() > bp.name.length() &&
3947                    permName.charAt(bp.name.length()) == '.') {
3948                return bp;
3949            }
3950        }
3951        return null;
3952    }
3953
3954    private BasePermission checkPermissionTreeLP(String permName) {
3955        if (permName != null) {
3956            BasePermission bp = findPermissionTreeLP(permName);
3957            if (bp != null) {
3958                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3959                    return bp;
3960                }
3961                throw new SecurityException("Calling uid "
3962                        + Binder.getCallingUid()
3963                        + " is not allowed to add to permission tree "
3964                        + bp.name + " owned by uid " + bp.uid);
3965            }
3966        }
3967        throw new SecurityException("No permission tree found for " + permName);
3968    }
3969
3970    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3971        if (s1 == null) {
3972            return s2 == null;
3973        }
3974        if (s2 == null) {
3975            return false;
3976        }
3977        if (s1.getClass() != s2.getClass()) {
3978            return false;
3979        }
3980        return s1.equals(s2);
3981    }
3982
3983    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3984        if (pi1.icon != pi2.icon) return false;
3985        if (pi1.logo != pi2.logo) return false;
3986        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3987        if (!compareStrings(pi1.name, pi2.name)) return false;
3988        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3989        // We'll take care of setting this one.
3990        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3991        // These are not currently stored in settings.
3992        //if (!compareStrings(pi1.group, pi2.group)) return false;
3993        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3994        //if (pi1.labelRes != pi2.labelRes) return false;
3995        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3996        return true;
3997    }
3998
3999    int permissionInfoFootprint(PermissionInfo info) {
4000        int size = info.name.length();
4001        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4002        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4003        return size;
4004    }
4005
4006    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4007        int size = 0;
4008        for (BasePermission perm : mSettings.mPermissions.values()) {
4009            if (perm.uid == tree.uid) {
4010                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4011            }
4012        }
4013        return size;
4014    }
4015
4016    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4017        // We calculate the max size of permissions defined by this uid and throw
4018        // if that plus the size of 'info' would exceed our stated maximum.
4019        if (tree.uid != Process.SYSTEM_UID) {
4020            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4021            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4022                throw new SecurityException("Permission tree size cap exceeded");
4023            }
4024        }
4025    }
4026
4027    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4028        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4029            throw new SecurityException("Label must be specified in permission");
4030        }
4031        BasePermission tree = checkPermissionTreeLP(info.name);
4032        BasePermission bp = mSettings.mPermissions.get(info.name);
4033        boolean added = bp == null;
4034        boolean changed = true;
4035        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4036        if (added) {
4037            enforcePermissionCapLocked(info, tree);
4038            bp = new BasePermission(info.name, tree.sourcePackage,
4039                    BasePermission.TYPE_DYNAMIC);
4040        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4041            throw new SecurityException(
4042                    "Not allowed to modify non-dynamic permission "
4043                    + info.name);
4044        } else {
4045            if (bp.protectionLevel == fixedLevel
4046                    && bp.perm.owner.equals(tree.perm.owner)
4047                    && bp.uid == tree.uid
4048                    && comparePermissionInfos(bp.perm.info, info)) {
4049                changed = false;
4050            }
4051        }
4052        bp.protectionLevel = fixedLevel;
4053        info = new PermissionInfo(info);
4054        info.protectionLevel = fixedLevel;
4055        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4056        bp.perm.info.packageName = tree.perm.info.packageName;
4057        bp.uid = tree.uid;
4058        if (added) {
4059            mSettings.mPermissions.put(info.name, bp);
4060        }
4061        if (changed) {
4062            if (!async) {
4063                mSettings.writeLPr();
4064            } else {
4065                scheduleWriteSettingsLocked();
4066            }
4067        }
4068        return added;
4069    }
4070
4071    @Override
4072    public boolean addPermission(PermissionInfo info) {
4073        synchronized (mPackages) {
4074            return addPermissionLocked(info, false);
4075        }
4076    }
4077
4078    @Override
4079    public boolean addPermissionAsync(PermissionInfo info) {
4080        synchronized (mPackages) {
4081            return addPermissionLocked(info, true);
4082        }
4083    }
4084
4085    @Override
4086    public void removePermission(String name) {
4087        synchronized (mPackages) {
4088            checkPermissionTreeLP(name);
4089            BasePermission bp = mSettings.mPermissions.get(name);
4090            if (bp != null) {
4091                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4092                    throw new SecurityException(
4093                            "Not allowed to modify non-dynamic permission "
4094                            + name);
4095                }
4096                mSettings.mPermissions.remove(name);
4097                mSettings.writeLPr();
4098            }
4099        }
4100    }
4101
4102    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4103            BasePermission bp) {
4104        int index = pkg.requestedPermissions.indexOf(bp.name);
4105        if (index == -1) {
4106            throw new SecurityException("Package " + pkg.packageName
4107                    + " has not requested permission " + bp.name);
4108        }
4109        if (!bp.isRuntime() && !bp.isDevelopment()) {
4110            throw new SecurityException("Permission " + bp.name
4111                    + " is not a changeable permission type");
4112        }
4113    }
4114
4115    @Override
4116    public void grantRuntimePermission(String packageName, String name, final int userId) {
4117        if (!sUserManager.exists(userId)) {
4118            Log.e(TAG, "No such user:" + userId);
4119            return;
4120        }
4121
4122        mContext.enforceCallingOrSelfPermission(
4123                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4124                "grantRuntimePermission");
4125
4126        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4127                true /* requireFullPermission */, true /* checkShell */,
4128                "grantRuntimePermission");
4129
4130        final int uid;
4131        final SettingBase sb;
4132
4133        synchronized (mPackages) {
4134            final PackageParser.Package pkg = mPackages.get(packageName);
4135            if (pkg == null) {
4136                throw new IllegalArgumentException("Unknown package: " + packageName);
4137            }
4138
4139            final BasePermission bp = mSettings.mPermissions.get(name);
4140            if (bp == null) {
4141                throw new IllegalArgumentException("Unknown permission: " + name);
4142            }
4143
4144            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4145
4146            // If a permission review is required for legacy apps we represent
4147            // their permissions as always granted runtime ones since we need
4148            // to keep the review required permission flag per user while an
4149            // install permission's state is shared across all users.
4150            if (Build.PERMISSIONS_REVIEW_REQUIRED
4151                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4152                    && bp.isRuntime()) {
4153                return;
4154            }
4155
4156            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4157            sb = (SettingBase) pkg.mExtras;
4158            if (sb == null) {
4159                throw new IllegalArgumentException("Unknown package: " + packageName);
4160            }
4161
4162            final PermissionsState permissionsState = sb.getPermissionsState();
4163
4164            final int flags = permissionsState.getPermissionFlags(name, userId);
4165            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4166                throw new SecurityException("Cannot grant system fixed permission "
4167                        + name + " for package " + packageName);
4168            }
4169
4170            if (bp.isDevelopment()) {
4171                // Development permissions must be handled specially, since they are not
4172                // normal runtime permissions.  For now they apply to all users.
4173                if (permissionsState.grantInstallPermission(bp) !=
4174                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4175                    scheduleWriteSettingsLocked();
4176                }
4177                return;
4178            }
4179
4180            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4181                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4182                return;
4183            }
4184
4185            final int result = permissionsState.grantRuntimePermission(bp, userId);
4186            switch (result) {
4187                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4188                    return;
4189                }
4190
4191                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4192                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4193                    mHandler.post(new Runnable() {
4194                        @Override
4195                        public void run() {
4196                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4197                        }
4198                    });
4199                }
4200                break;
4201            }
4202
4203            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4204
4205            // Not critical if that is lost - app has to request again.
4206            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4207        }
4208
4209        // Only need to do this if user is initialized. Otherwise it's a new user
4210        // and there are no processes running as the user yet and there's no need
4211        // to make an expensive call to remount processes for the changed permissions.
4212        if (READ_EXTERNAL_STORAGE.equals(name)
4213                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4214            final long token = Binder.clearCallingIdentity();
4215            try {
4216                if (sUserManager.isInitialized(userId)) {
4217                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4218                            MountServiceInternal.class);
4219                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4220                }
4221            } finally {
4222                Binder.restoreCallingIdentity(token);
4223            }
4224        }
4225    }
4226
4227    @Override
4228    public void revokeRuntimePermission(String packageName, String name, int userId) {
4229        if (!sUserManager.exists(userId)) {
4230            Log.e(TAG, "No such user:" + userId);
4231            return;
4232        }
4233
4234        mContext.enforceCallingOrSelfPermission(
4235                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4236                "revokeRuntimePermission");
4237
4238        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4239                true /* requireFullPermission */, true /* checkShell */,
4240                "revokeRuntimePermission");
4241
4242        final int appId;
4243
4244        synchronized (mPackages) {
4245            final PackageParser.Package pkg = mPackages.get(packageName);
4246            if (pkg == null) {
4247                throw new IllegalArgumentException("Unknown package: " + packageName);
4248            }
4249
4250            final BasePermission bp = mSettings.mPermissions.get(name);
4251            if (bp == null) {
4252                throw new IllegalArgumentException("Unknown permission: " + name);
4253            }
4254
4255            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4256
4257            // If a permission review is required for legacy apps we represent
4258            // their permissions as always granted runtime ones since we need
4259            // to keep the review required permission flag per user while an
4260            // install permission's state is shared across all users.
4261            if (Build.PERMISSIONS_REVIEW_REQUIRED
4262                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4263                    && bp.isRuntime()) {
4264                return;
4265            }
4266
4267            SettingBase sb = (SettingBase) pkg.mExtras;
4268            if (sb == null) {
4269                throw new IllegalArgumentException("Unknown package: " + packageName);
4270            }
4271
4272            final PermissionsState permissionsState = sb.getPermissionsState();
4273
4274            final int flags = permissionsState.getPermissionFlags(name, userId);
4275            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4276                throw new SecurityException("Cannot revoke system fixed permission "
4277                        + name + " for package " + packageName);
4278            }
4279
4280            if (bp.isDevelopment()) {
4281                // Development permissions must be handled specially, since they are not
4282                // normal runtime permissions.  For now they apply to all users.
4283                if (permissionsState.revokeInstallPermission(bp) !=
4284                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4285                    scheduleWriteSettingsLocked();
4286                }
4287                return;
4288            }
4289
4290            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4291                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4292                return;
4293            }
4294
4295            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4296
4297            // Critical, after this call app should never have the permission.
4298            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4299
4300            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4301        }
4302
4303        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4304    }
4305
4306    @Override
4307    public void resetRuntimePermissions() {
4308        mContext.enforceCallingOrSelfPermission(
4309                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4310                "revokeRuntimePermission");
4311
4312        int callingUid = Binder.getCallingUid();
4313        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4314            mContext.enforceCallingOrSelfPermission(
4315                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4316                    "resetRuntimePermissions");
4317        }
4318
4319        synchronized (mPackages) {
4320            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4321            for (int userId : UserManagerService.getInstance().getUserIds()) {
4322                final int packageCount = mPackages.size();
4323                for (int i = 0; i < packageCount; i++) {
4324                    PackageParser.Package pkg = mPackages.valueAt(i);
4325                    if (!(pkg.mExtras instanceof PackageSetting)) {
4326                        continue;
4327                    }
4328                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4329                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4330                }
4331            }
4332        }
4333    }
4334
4335    @Override
4336    public int getPermissionFlags(String name, String packageName, int userId) {
4337        if (!sUserManager.exists(userId)) {
4338            return 0;
4339        }
4340
4341        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4342
4343        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4344                true /* requireFullPermission */, false /* checkShell */,
4345                "getPermissionFlags");
4346
4347        synchronized (mPackages) {
4348            final PackageParser.Package pkg = mPackages.get(packageName);
4349            if (pkg == null) {
4350                return 0;
4351            }
4352
4353            final BasePermission bp = mSettings.mPermissions.get(name);
4354            if (bp == null) {
4355                return 0;
4356            }
4357
4358            SettingBase sb = (SettingBase) pkg.mExtras;
4359            if (sb == null) {
4360                return 0;
4361            }
4362
4363            PermissionsState permissionsState = sb.getPermissionsState();
4364            return permissionsState.getPermissionFlags(name, userId);
4365        }
4366    }
4367
4368    @Override
4369    public void updatePermissionFlags(String name, String packageName, int flagMask,
4370            int flagValues, int userId) {
4371        if (!sUserManager.exists(userId)) {
4372            return;
4373        }
4374
4375        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4376
4377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4378                true /* requireFullPermission */, true /* checkShell */,
4379                "updatePermissionFlags");
4380
4381        // Only the system can change these flags and nothing else.
4382        if (getCallingUid() != Process.SYSTEM_UID) {
4383            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4384            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4385            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4386            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4387            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4388        }
4389
4390        synchronized (mPackages) {
4391            final PackageParser.Package pkg = mPackages.get(packageName);
4392            if (pkg == null) {
4393                throw new IllegalArgumentException("Unknown package: " + packageName);
4394            }
4395
4396            final BasePermission bp = mSettings.mPermissions.get(name);
4397            if (bp == null) {
4398                throw new IllegalArgumentException("Unknown permission: " + name);
4399            }
4400
4401            SettingBase sb = (SettingBase) pkg.mExtras;
4402            if (sb == null) {
4403                throw new IllegalArgumentException("Unknown package: " + packageName);
4404            }
4405
4406            PermissionsState permissionsState = sb.getPermissionsState();
4407
4408            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4409
4410            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4411                // Install and runtime permissions are stored in different places,
4412                // so figure out what permission changed and persist the change.
4413                if (permissionsState.getInstallPermissionState(name) != null) {
4414                    scheduleWriteSettingsLocked();
4415                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4416                        || hadState) {
4417                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4418                }
4419            }
4420        }
4421    }
4422
4423    /**
4424     * Update the permission flags for all packages and runtime permissions of a user in order
4425     * to allow device or profile owner to remove POLICY_FIXED.
4426     */
4427    @Override
4428    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4429        if (!sUserManager.exists(userId)) {
4430            return;
4431        }
4432
4433        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4434
4435        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4436                true /* requireFullPermission */, true /* checkShell */,
4437                "updatePermissionFlagsForAllApps");
4438
4439        // Only the system can change system fixed flags.
4440        if (getCallingUid() != Process.SYSTEM_UID) {
4441            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4442            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4443        }
4444
4445        synchronized (mPackages) {
4446            boolean changed = false;
4447            final int packageCount = mPackages.size();
4448            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4449                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4450                SettingBase sb = (SettingBase) pkg.mExtras;
4451                if (sb == null) {
4452                    continue;
4453                }
4454                PermissionsState permissionsState = sb.getPermissionsState();
4455                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4456                        userId, flagMask, flagValues);
4457            }
4458            if (changed) {
4459                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4460            }
4461        }
4462    }
4463
4464    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4465        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4466                != PackageManager.PERMISSION_GRANTED
4467            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4468                != PackageManager.PERMISSION_GRANTED) {
4469            throw new SecurityException(message + " requires "
4470                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4471                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4472        }
4473    }
4474
4475    @Override
4476    public boolean shouldShowRequestPermissionRationale(String permissionName,
4477            String packageName, int userId) {
4478        if (UserHandle.getCallingUserId() != userId) {
4479            mContext.enforceCallingPermission(
4480                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4481                    "canShowRequestPermissionRationale for user " + userId);
4482        }
4483
4484        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4485        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4486            return false;
4487        }
4488
4489        if (checkPermission(permissionName, packageName, userId)
4490                == PackageManager.PERMISSION_GRANTED) {
4491            return false;
4492        }
4493
4494        final int flags;
4495
4496        final long identity = Binder.clearCallingIdentity();
4497        try {
4498            flags = getPermissionFlags(permissionName,
4499                    packageName, userId);
4500        } finally {
4501            Binder.restoreCallingIdentity(identity);
4502        }
4503
4504        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4505                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4506                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4507
4508        if ((flags & fixedFlags) != 0) {
4509            return false;
4510        }
4511
4512        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4513    }
4514
4515    @Override
4516    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4517        mContext.enforceCallingOrSelfPermission(
4518                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4519                "addOnPermissionsChangeListener");
4520
4521        synchronized (mPackages) {
4522            mOnPermissionChangeListeners.addListenerLocked(listener);
4523        }
4524    }
4525
4526    @Override
4527    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4528        synchronized (mPackages) {
4529            mOnPermissionChangeListeners.removeListenerLocked(listener);
4530        }
4531    }
4532
4533    @Override
4534    public boolean isProtectedBroadcast(String actionName) {
4535        synchronized (mPackages) {
4536            if (mProtectedBroadcasts.contains(actionName)) {
4537                return true;
4538            } else if (actionName != null) {
4539                // TODO: remove these terrible hacks
4540                if (actionName.startsWith("android.net.netmon.lingerExpired")
4541                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4542                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4543                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4544                    return true;
4545                }
4546            }
4547        }
4548        return false;
4549    }
4550
4551    @Override
4552    public int checkSignatures(String pkg1, String pkg2) {
4553        synchronized (mPackages) {
4554            final PackageParser.Package p1 = mPackages.get(pkg1);
4555            final PackageParser.Package p2 = mPackages.get(pkg2);
4556            if (p1 == null || p1.mExtras == null
4557                    || p2 == null || p2.mExtras == null) {
4558                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4559            }
4560            return compareSignatures(p1.mSignatures, p2.mSignatures);
4561        }
4562    }
4563
4564    @Override
4565    public int checkUidSignatures(int uid1, int uid2) {
4566        // Map to base uids.
4567        uid1 = UserHandle.getAppId(uid1);
4568        uid2 = UserHandle.getAppId(uid2);
4569        // reader
4570        synchronized (mPackages) {
4571            Signature[] s1;
4572            Signature[] s2;
4573            Object obj = mSettings.getUserIdLPr(uid1);
4574            if (obj != null) {
4575                if (obj instanceof SharedUserSetting) {
4576                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4577                } else if (obj instanceof PackageSetting) {
4578                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4579                } else {
4580                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4581                }
4582            } else {
4583                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4584            }
4585            obj = mSettings.getUserIdLPr(uid2);
4586            if (obj != null) {
4587                if (obj instanceof SharedUserSetting) {
4588                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4589                } else if (obj instanceof PackageSetting) {
4590                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4591                } else {
4592                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4593                }
4594            } else {
4595                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4596            }
4597            return compareSignatures(s1, s2);
4598        }
4599    }
4600
4601    /**
4602     * This method should typically only be used when granting or revoking
4603     * permissions, since the app may immediately restart after this call.
4604     * <p>
4605     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4606     * guard your work against the app being relaunched.
4607     */
4608    private void killUid(int appId, int userId, String reason) {
4609        final long identity = Binder.clearCallingIdentity();
4610        try {
4611            IActivityManager am = ActivityManagerNative.getDefault();
4612            if (am != null) {
4613                try {
4614                    am.killUid(appId, userId, reason);
4615                } catch (RemoteException e) {
4616                    /* ignore - same process */
4617                }
4618            }
4619        } finally {
4620            Binder.restoreCallingIdentity(identity);
4621        }
4622    }
4623
4624    /**
4625     * Compares two sets of signatures. Returns:
4626     * <br />
4627     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4628     * <br />
4629     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4630     * <br />
4631     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4632     * <br />
4633     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4634     * <br />
4635     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4636     */
4637    static int compareSignatures(Signature[] s1, Signature[] s2) {
4638        if (s1 == null) {
4639            return s2 == null
4640                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4641                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4642        }
4643
4644        if (s2 == null) {
4645            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4646        }
4647
4648        if (s1.length != s2.length) {
4649            return PackageManager.SIGNATURE_NO_MATCH;
4650        }
4651
4652        // Since both signature sets are of size 1, we can compare without HashSets.
4653        if (s1.length == 1) {
4654            return s1[0].equals(s2[0]) ?
4655                    PackageManager.SIGNATURE_MATCH :
4656                    PackageManager.SIGNATURE_NO_MATCH;
4657        }
4658
4659        ArraySet<Signature> set1 = new ArraySet<Signature>();
4660        for (Signature sig : s1) {
4661            set1.add(sig);
4662        }
4663        ArraySet<Signature> set2 = new ArraySet<Signature>();
4664        for (Signature sig : s2) {
4665            set2.add(sig);
4666        }
4667        // Make sure s2 contains all signatures in s1.
4668        if (set1.equals(set2)) {
4669            return PackageManager.SIGNATURE_MATCH;
4670        }
4671        return PackageManager.SIGNATURE_NO_MATCH;
4672    }
4673
4674    /**
4675     * If the database version for this type of package (internal storage or
4676     * external storage) is less than the version where package signatures
4677     * were updated, return true.
4678     */
4679    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4680        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4681        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4682    }
4683
4684    /**
4685     * Used for backward compatibility to make sure any packages with
4686     * certificate chains get upgraded to the new style. {@code existingSigs}
4687     * will be in the old format (since they were stored on disk from before the
4688     * system upgrade) and {@code scannedSigs} will be in the newer format.
4689     */
4690    private int compareSignaturesCompat(PackageSignatures existingSigs,
4691            PackageParser.Package scannedPkg) {
4692        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4693            return PackageManager.SIGNATURE_NO_MATCH;
4694        }
4695
4696        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4697        for (Signature sig : existingSigs.mSignatures) {
4698            existingSet.add(sig);
4699        }
4700        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4701        for (Signature sig : scannedPkg.mSignatures) {
4702            try {
4703                Signature[] chainSignatures = sig.getChainSignatures();
4704                for (Signature chainSig : chainSignatures) {
4705                    scannedCompatSet.add(chainSig);
4706                }
4707            } catch (CertificateEncodingException e) {
4708                scannedCompatSet.add(sig);
4709            }
4710        }
4711        /*
4712         * Make sure the expanded scanned set contains all signatures in the
4713         * existing one.
4714         */
4715        if (scannedCompatSet.equals(existingSet)) {
4716            // Migrate the old signatures to the new scheme.
4717            existingSigs.assignSignatures(scannedPkg.mSignatures);
4718            // The new KeySets will be re-added later in the scanning process.
4719            synchronized (mPackages) {
4720                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4721            }
4722            return PackageManager.SIGNATURE_MATCH;
4723        }
4724        return PackageManager.SIGNATURE_NO_MATCH;
4725    }
4726
4727    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4728        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4729        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4730    }
4731
4732    private int compareSignaturesRecover(PackageSignatures existingSigs,
4733            PackageParser.Package scannedPkg) {
4734        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4735            return PackageManager.SIGNATURE_NO_MATCH;
4736        }
4737
4738        String msg = null;
4739        try {
4740            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4741                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4742                        + scannedPkg.packageName);
4743                return PackageManager.SIGNATURE_MATCH;
4744            }
4745        } catch (CertificateException e) {
4746            msg = e.getMessage();
4747        }
4748
4749        logCriticalInfo(Log.INFO,
4750                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4751        return PackageManager.SIGNATURE_NO_MATCH;
4752    }
4753
4754    @Override
4755    public List<String> getAllPackages() {
4756        synchronized (mPackages) {
4757            return new ArrayList<String>(mPackages.keySet());
4758        }
4759    }
4760
4761    @Override
4762    public String[] getPackagesForUid(int uid) {
4763        uid = UserHandle.getAppId(uid);
4764        // reader
4765        synchronized (mPackages) {
4766            Object obj = mSettings.getUserIdLPr(uid);
4767            if (obj instanceof SharedUserSetting) {
4768                final SharedUserSetting sus = (SharedUserSetting) obj;
4769                final int N = sus.packages.size();
4770                final String[] res = new String[N];
4771                for (int i = 0; i < N; i++) {
4772                    res[i] = sus.packages.valueAt(i).name;
4773                }
4774                return res;
4775            } else if (obj instanceof PackageSetting) {
4776                final PackageSetting ps = (PackageSetting) obj;
4777                return new String[] { ps.name };
4778            }
4779        }
4780        return null;
4781    }
4782
4783    @Override
4784    public String getNameForUid(int uid) {
4785        // reader
4786        synchronized (mPackages) {
4787            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4788            if (obj instanceof SharedUserSetting) {
4789                final SharedUserSetting sus = (SharedUserSetting) obj;
4790                return sus.name + ":" + sus.userId;
4791            } else if (obj instanceof PackageSetting) {
4792                final PackageSetting ps = (PackageSetting) obj;
4793                return ps.name;
4794            }
4795        }
4796        return null;
4797    }
4798
4799    @Override
4800    public int getUidForSharedUser(String sharedUserName) {
4801        if(sharedUserName == null) {
4802            return -1;
4803        }
4804        // reader
4805        synchronized (mPackages) {
4806            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4807            if (suid == null) {
4808                return -1;
4809            }
4810            return suid.userId;
4811        }
4812    }
4813
4814    @Override
4815    public int getFlagsForUid(int uid) {
4816        synchronized (mPackages) {
4817            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4818            if (obj instanceof SharedUserSetting) {
4819                final SharedUserSetting sus = (SharedUserSetting) obj;
4820                return sus.pkgFlags;
4821            } else if (obj instanceof PackageSetting) {
4822                final PackageSetting ps = (PackageSetting) obj;
4823                return ps.pkgFlags;
4824            }
4825        }
4826        return 0;
4827    }
4828
4829    @Override
4830    public int getPrivateFlagsForUid(int uid) {
4831        synchronized (mPackages) {
4832            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4833            if (obj instanceof SharedUserSetting) {
4834                final SharedUserSetting sus = (SharedUserSetting) obj;
4835                return sus.pkgPrivateFlags;
4836            } else if (obj instanceof PackageSetting) {
4837                final PackageSetting ps = (PackageSetting) obj;
4838                return ps.pkgPrivateFlags;
4839            }
4840        }
4841        return 0;
4842    }
4843
4844    @Override
4845    public boolean isUidPrivileged(int uid) {
4846        uid = UserHandle.getAppId(uid);
4847        // reader
4848        synchronized (mPackages) {
4849            Object obj = mSettings.getUserIdLPr(uid);
4850            if (obj instanceof SharedUserSetting) {
4851                final SharedUserSetting sus = (SharedUserSetting) obj;
4852                final Iterator<PackageSetting> it = sus.packages.iterator();
4853                while (it.hasNext()) {
4854                    if (it.next().isPrivileged()) {
4855                        return true;
4856                    }
4857                }
4858            } else if (obj instanceof PackageSetting) {
4859                final PackageSetting ps = (PackageSetting) obj;
4860                return ps.isPrivileged();
4861            }
4862        }
4863        return false;
4864    }
4865
4866    @Override
4867    public String[] getAppOpPermissionPackages(String permissionName) {
4868        synchronized (mPackages) {
4869            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4870            if (pkgs == null) {
4871                return null;
4872            }
4873            return pkgs.toArray(new String[pkgs.size()]);
4874        }
4875    }
4876
4877    @Override
4878    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4879            int flags, int userId) {
4880        try {
4881            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4882
4883            if (!sUserManager.exists(userId)) return null;
4884            flags = updateFlagsForResolve(flags, userId, intent);
4885            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4886                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4887
4888            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4889            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4890                    flags, userId);
4891            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4892
4893            final ResolveInfo bestChoice =
4894                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4895
4896            if (isEphemeralAllowed(intent, query, userId)) {
4897                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4898                final EphemeralResolveInfo ai =
4899                        getEphemeralResolveInfo(intent, resolvedType, userId);
4900                if (ai != null) {
4901                    if (DEBUG_EPHEMERAL) {
4902                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4903                    }
4904                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4905                    bestChoice.ephemeralResolveInfo = ai;
4906                }
4907                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4908            }
4909            return bestChoice;
4910        } finally {
4911            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4912        }
4913    }
4914
4915    @Override
4916    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4917            IntentFilter filter, int match, ComponentName activity) {
4918        final int userId = UserHandle.getCallingUserId();
4919        if (DEBUG_PREFERRED) {
4920            Log.v(TAG, "setLastChosenActivity intent=" + intent
4921                + " resolvedType=" + resolvedType
4922                + " flags=" + flags
4923                + " filter=" + filter
4924                + " match=" + match
4925                + " activity=" + activity);
4926            filter.dump(new PrintStreamPrinter(System.out), "    ");
4927        }
4928        intent.setComponent(null);
4929        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4930                userId);
4931        // Find any earlier preferred or last chosen entries and nuke them
4932        findPreferredActivity(intent, resolvedType,
4933                flags, query, 0, false, true, false, userId);
4934        // Add the new activity as the last chosen for this filter
4935        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4936                "Setting last chosen");
4937    }
4938
4939    @Override
4940    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4941        final int userId = UserHandle.getCallingUserId();
4942        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4943        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4944                userId);
4945        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4946                false, false, false, userId);
4947    }
4948
4949
4950    private boolean isEphemeralAllowed(
4951            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4952        // Short circuit and return early if possible.
4953        if (DISABLE_EPHEMERAL_APPS) {
4954            return false;
4955        }
4956        final int callingUser = UserHandle.getCallingUserId();
4957        if (callingUser != UserHandle.USER_SYSTEM) {
4958            return false;
4959        }
4960        if (mEphemeralResolverConnection == null) {
4961            return false;
4962        }
4963        if (intent.getComponent() != null) {
4964            return false;
4965        }
4966        if (intent.getPackage() != null) {
4967            return false;
4968        }
4969        final boolean isWebUri = hasWebURI(intent);
4970        if (!isWebUri) {
4971            return false;
4972        }
4973        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4974        synchronized (mPackages) {
4975            final int count = resolvedActivites.size();
4976            for (int n = 0; n < count; n++) {
4977                ResolveInfo info = resolvedActivites.get(n);
4978                String packageName = info.activityInfo.packageName;
4979                PackageSetting ps = mSettings.mPackages.get(packageName);
4980                if (ps != null) {
4981                    // Try to get the status from User settings first
4982                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4983                    int status = (int) (packedStatus >> 32);
4984                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4985                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4986                        if (DEBUG_EPHEMERAL) {
4987                            Slog.v(TAG, "DENY ephemeral apps;"
4988                                + " pkg: " + packageName + ", status: " + status);
4989                        }
4990                        return false;
4991                    }
4992                }
4993            }
4994        }
4995        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4996        return true;
4997    }
4998
4999    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
5000            int userId) {
5001        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
5002                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
5003        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
5004                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
5005        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
5006                ephemeralPrefixCount);
5007        final int[] shaPrefix = digest.getDigestPrefix();
5008        final byte[][] digestBytes = digest.getDigestBytes();
5009        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5010                mEphemeralResolverConnection.getEphemeralResolveInfoList(
5011                        shaPrefix, ephemeralPrefixMask);
5012        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5013            // No hash prefix match; there are no ephemeral apps for this domain.
5014            return null;
5015        }
5016
5017        // Go in reverse order so we match the narrowest scope first.
5018        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5019            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5020                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5021                    continue;
5022                }
5023                final List<IntentFilter> filters = ephemeralApplication.getFilters();
5024                // No filters; this should never happen.
5025                if (filters.isEmpty()) {
5026                    continue;
5027                }
5028                // We have a domain match; resolve the filters to see if anything matches.
5029                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5030                for (int j = filters.size() - 1; j >= 0; --j) {
5031                    final EphemeralResolveIntentInfo intentInfo =
5032                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5033                    ephemeralResolver.addFilter(intentInfo);
5034                }
5035                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5036                        intent, resolvedType, false /*defaultOnly*/, userId);
5037                if (!matchedResolveInfoList.isEmpty()) {
5038                    return matchedResolveInfoList.get(0);
5039                }
5040            }
5041        }
5042        // Hash or filter mis-match; no ephemeral apps for this domain.
5043        return null;
5044    }
5045
5046    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5047            int flags, List<ResolveInfo> query, int userId) {
5048        if (query != null) {
5049            final int N = query.size();
5050            if (N == 1) {
5051                return query.get(0);
5052            } else if (N > 1) {
5053                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5054                // If there is more than one activity with the same priority,
5055                // then let the user decide between them.
5056                ResolveInfo r0 = query.get(0);
5057                ResolveInfo r1 = query.get(1);
5058                if (DEBUG_INTENT_MATCHING || debug) {
5059                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5060                            + r1.activityInfo.name + "=" + r1.priority);
5061                }
5062                // If the first activity has a higher priority, or a different
5063                // default, then it is always desirable to pick it.
5064                if (r0.priority != r1.priority
5065                        || r0.preferredOrder != r1.preferredOrder
5066                        || r0.isDefault != r1.isDefault) {
5067                    return query.get(0);
5068                }
5069                // If we have saved a preference for a preferred activity for
5070                // this Intent, use that.
5071                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5072                        flags, query, r0.priority, true, false, debug, userId);
5073                if (ri != null) {
5074                    return ri;
5075                }
5076                ri = new ResolveInfo(mResolveInfo);
5077                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5078                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5079                // If all of the options come from the same package, show the application's
5080                // label and icon instead of the generic resolver's.
5081                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5082                // and then throw away the ResolveInfo itself, meaning that the caller loses
5083                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5084                // a fallback for this case; we only set the target package's resources on
5085                // the ResolveInfo, not the ActivityInfo.
5086                final String intentPackage = intent.getPackage();
5087                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5088                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5089                    ri.resolvePackageName = intentPackage;
5090                    if (userNeedsBadging(userId)) {
5091                        ri.noResourceId = true;
5092                    } else {
5093                        ri.icon = appi.icon;
5094                    }
5095                    ri.iconResourceId = appi.icon;
5096                    ri.labelRes = appi.labelRes;
5097                }
5098                ri.activityInfo.applicationInfo = new ApplicationInfo(
5099                        ri.activityInfo.applicationInfo);
5100                if (userId != 0) {
5101                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5102                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5103                }
5104                // Make sure that the resolver is displayable in car mode
5105                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5106                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5107                return ri;
5108            }
5109        }
5110        return null;
5111    }
5112
5113    /**
5114     * Return true if the given list is not empty and all of its contents have
5115     * an activityInfo with the given package name.
5116     */
5117    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5118        if (ArrayUtils.isEmpty(list)) {
5119            return false;
5120        }
5121        for (int i = 0, N = list.size(); i < N; i++) {
5122            final ResolveInfo ri = list.get(i);
5123            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5124            if (ai == null || !packageName.equals(ai.packageName)) {
5125                return false;
5126            }
5127        }
5128        return true;
5129    }
5130
5131    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5132            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5133        final int N = query.size();
5134        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5135                .get(userId);
5136        // Get the list of persistent preferred activities that handle the intent
5137        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5138        List<PersistentPreferredActivity> pprefs = ppir != null
5139                ? ppir.queryIntent(intent, resolvedType,
5140                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5141                : null;
5142        if (pprefs != null && pprefs.size() > 0) {
5143            final int M = pprefs.size();
5144            for (int i=0; i<M; i++) {
5145                final PersistentPreferredActivity ppa = pprefs.get(i);
5146                if (DEBUG_PREFERRED || debug) {
5147                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5148                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5149                            + "\n  component=" + ppa.mComponent);
5150                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5151                }
5152                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5153                        flags | MATCH_DISABLED_COMPONENTS, userId);
5154                if (DEBUG_PREFERRED || debug) {
5155                    Slog.v(TAG, "Found persistent preferred activity:");
5156                    if (ai != null) {
5157                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5158                    } else {
5159                        Slog.v(TAG, "  null");
5160                    }
5161                }
5162                if (ai == null) {
5163                    // This previously registered persistent preferred activity
5164                    // component is no longer known. Ignore it and do NOT remove it.
5165                    continue;
5166                }
5167                for (int j=0; j<N; j++) {
5168                    final ResolveInfo ri = query.get(j);
5169                    if (!ri.activityInfo.applicationInfo.packageName
5170                            .equals(ai.applicationInfo.packageName)) {
5171                        continue;
5172                    }
5173                    if (!ri.activityInfo.name.equals(ai.name)) {
5174                        continue;
5175                    }
5176                    //  Found a persistent preference that can handle the intent.
5177                    if (DEBUG_PREFERRED || debug) {
5178                        Slog.v(TAG, "Returning persistent preferred activity: " +
5179                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5180                    }
5181                    return ri;
5182                }
5183            }
5184        }
5185        return null;
5186    }
5187
5188    // TODO: handle preferred activities missing while user has amnesia
5189    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5190            List<ResolveInfo> query, int priority, boolean always,
5191            boolean removeMatches, boolean debug, int userId) {
5192        if (!sUserManager.exists(userId)) return null;
5193        flags = updateFlagsForResolve(flags, userId, intent);
5194        // writer
5195        synchronized (mPackages) {
5196            if (intent.getSelector() != null) {
5197                intent = intent.getSelector();
5198            }
5199            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5200
5201            // Try to find a matching persistent preferred activity.
5202            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5203                    debug, userId);
5204
5205            // If a persistent preferred activity matched, use it.
5206            if (pri != null) {
5207                return pri;
5208            }
5209
5210            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5211            // Get the list of preferred activities that handle the intent
5212            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5213            List<PreferredActivity> prefs = pir != null
5214                    ? pir.queryIntent(intent, resolvedType,
5215                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5216                    : null;
5217            if (prefs != null && prefs.size() > 0) {
5218                boolean changed = false;
5219                try {
5220                    // First figure out how good the original match set is.
5221                    // We will only allow preferred activities that came
5222                    // from the same match quality.
5223                    int match = 0;
5224
5225                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5226
5227                    final int N = query.size();
5228                    for (int j=0; j<N; j++) {
5229                        final ResolveInfo ri = query.get(j);
5230                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5231                                + ": 0x" + Integer.toHexString(match));
5232                        if (ri.match > match) {
5233                            match = ri.match;
5234                        }
5235                    }
5236
5237                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5238                            + Integer.toHexString(match));
5239
5240                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5241                    final int M = prefs.size();
5242                    for (int i=0; i<M; i++) {
5243                        final PreferredActivity pa = prefs.get(i);
5244                        if (DEBUG_PREFERRED || debug) {
5245                            Slog.v(TAG, "Checking PreferredActivity ds="
5246                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5247                                    + "\n  component=" + pa.mPref.mComponent);
5248                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5249                        }
5250                        if (pa.mPref.mMatch != match) {
5251                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5252                                    + Integer.toHexString(pa.mPref.mMatch));
5253                            continue;
5254                        }
5255                        // If it's not an "always" type preferred activity and that's what we're
5256                        // looking for, skip it.
5257                        if (always && !pa.mPref.mAlways) {
5258                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5259                            continue;
5260                        }
5261                        final ActivityInfo ai = getActivityInfo(
5262                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5263                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5264                                userId);
5265                        if (DEBUG_PREFERRED || debug) {
5266                            Slog.v(TAG, "Found preferred activity:");
5267                            if (ai != null) {
5268                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5269                            } else {
5270                                Slog.v(TAG, "  null");
5271                            }
5272                        }
5273                        if (ai == null) {
5274                            // This previously registered preferred activity
5275                            // component is no longer known.  Most likely an update
5276                            // to the app was installed and in the new version this
5277                            // component no longer exists.  Clean it up by removing
5278                            // it from the preferred activities list, and skip it.
5279                            Slog.w(TAG, "Removing dangling preferred activity: "
5280                                    + pa.mPref.mComponent);
5281                            pir.removeFilter(pa);
5282                            changed = true;
5283                            continue;
5284                        }
5285                        for (int j=0; j<N; j++) {
5286                            final ResolveInfo ri = query.get(j);
5287                            if (!ri.activityInfo.applicationInfo.packageName
5288                                    .equals(ai.applicationInfo.packageName)) {
5289                                continue;
5290                            }
5291                            if (!ri.activityInfo.name.equals(ai.name)) {
5292                                continue;
5293                            }
5294
5295                            if (removeMatches) {
5296                                pir.removeFilter(pa);
5297                                changed = true;
5298                                if (DEBUG_PREFERRED) {
5299                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5300                                }
5301                                break;
5302                            }
5303
5304                            // Okay we found a previously set preferred or last chosen app.
5305                            // If the result set is different from when this
5306                            // was created, we need to clear it and re-ask the
5307                            // user their preference, if we're looking for an "always" type entry.
5308                            if (always && !pa.mPref.sameSet(query)) {
5309                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5310                                        + intent + " type " + resolvedType);
5311                                if (DEBUG_PREFERRED) {
5312                                    Slog.v(TAG, "Removing preferred activity since set changed "
5313                                            + pa.mPref.mComponent);
5314                                }
5315                                pir.removeFilter(pa);
5316                                // Re-add the filter as a "last chosen" entry (!always)
5317                                PreferredActivity lastChosen = new PreferredActivity(
5318                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5319                                pir.addFilter(lastChosen);
5320                                changed = true;
5321                                return null;
5322                            }
5323
5324                            // Yay! Either the set matched or we're looking for the last chosen
5325                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5326                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5327                            return ri;
5328                        }
5329                    }
5330                } finally {
5331                    if (changed) {
5332                        if (DEBUG_PREFERRED) {
5333                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5334                        }
5335                        scheduleWritePackageRestrictionsLocked(userId);
5336                    }
5337                }
5338            }
5339        }
5340        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5341        return null;
5342    }
5343
5344    /*
5345     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5346     */
5347    @Override
5348    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5349            int targetUserId) {
5350        mContext.enforceCallingOrSelfPermission(
5351                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5352        List<CrossProfileIntentFilter> matches =
5353                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5354        if (matches != null) {
5355            int size = matches.size();
5356            for (int i = 0; i < size; i++) {
5357                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5358            }
5359        }
5360        if (hasWebURI(intent)) {
5361            // cross-profile app linking works only towards the parent.
5362            final UserInfo parent = getProfileParent(sourceUserId);
5363            synchronized(mPackages) {
5364                int flags = updateFlagsForResolve(0, parent.id, intent);
5365                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5366                        intent, resolvedType, flags, sourceUserId, parent.id);
5367                return xpDomainInfo != null;
5368            }
5369        }
5370        return false;
5371    }
5372
5373    private UserInfo getProfileParent(int userId) {
5374        final long identity = Binder.clearCallingIdentity();
5375        try {
5376            return sUserManager.getProfileParent(userId);
5377        } finally {
5378            Binder.restoreCallingIdentity(identity);
5379        }
5380    }
5381
5382    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5383            String resolvedType, int userId) {
5384        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5385        if (resolver != null) {
5386            return resolver.queryIntent(intent, resolvedType, false, userId);
5387        }
5388        return null;
5389    }
5390
5391    @Override
5392    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5393            String resolvedType, int flags, int userId) {
5394        try {
5395            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5396
5397            return new ParceledListSlice<>(
5398                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5399        } finally {
5400            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5401        }
5402    }
5403
5404    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5405            String resolvedType, int flags, int userId) {
5406        if (!sUserManager.exists(userId)) return Collections.emptyList();
5407        flags = updateFlagsForResolve(flags, userId, intent);
5408        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5409                false /* requireFullPermission */, false /* checkShell */,
5410                "query intent activities");
5411        ComponentName comp = intent.getComponent();
5412        if (comp == null) {
5413            if (intent.getSelector() != null) {
5414                intent = intent.getSelector();
5415                comp = intent.getComponent();
5416            }
5417        }
5418
5419        if (comp != null) {
5420            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5421            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5422            if (ai != null) {
5423                final ResolveInfo ri = new ResolveInfo();
5424                ri.activityInfo = ai;
5425                list.add(ri);
5426            }
5427            return list;
5428        }
5429
5430        // reader
5431        synchronized (mPackages) {
5432            final String pkgName = intent.getPackage();
5433            if (pkgName == null) {
5434                List<CrossProfileIntentFilter> matchingFilters =
5435                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5436                // Check for results that need to skip the current profile.
5437                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5438                        resolvedType, flags, userId);
5439                if (xpResolveInfo != null) {
5440                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5441                    result.add(xpResolveInfo);
5442                    return filterIfNotSystemUser(result, userId);
5443                }
5444
5445                // Check for results in the current profile.
5446                List<ResolveInfo> result = mActivities.queryIntent(
5447                        intent, resolvedType, flags, userId);
5448                result = filterIfNotSystemUser(result, userId);
5449
5450                // Check for cross profile results.
5451                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5452                xpResolveInfo = queryCrossProfileIntents(
5453                        matchingFilters, intent, resolvedType, flags, userId,
5454                        hasNonNegativePriorityResult);
5455                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5456                    boolean isVisibleToUser = filterIfNotSystemUser(
5457                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5458                    if (isVisibleToUser) {
5459                        result.add(xpResolveInfo);
5460                        Collections.sort(result, mResolvePrioritySorter);
5461                    }
5462                }
5463                if (hasWebURI(intent)) {
5464                    CrossProfileDomainInfo xpDomainInfo = null;
5465                    final UserInfo parent = getProfileParent(userId);
5466                    if (parent != null) {
5467                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5468                                flags, userId, parent.id);
5469                    }
5470                    if (xpDomainInfo != null) {
5471                        if (xpResolveInfo != null) {
5472                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5473                            // in the result.
5474                            result.remove(xpResolveInfo);
5475                        }
5476                        if (result.size() == 0) {
5477                            result.add(xpDomainInfo.resolveInfo);
5478                            return result;
5479                        }
5480                    } else if (result.size() <= 1) {
5481                        return result;
5482                    }
5483                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5484                            xpDomainInfo, userId);
5485                    Collections.sort(result, mResolvePrioritySorter);
5486                }
5487                return result;
5488            }
5489            final PackageParser.Package pkg = mPackages.get(pkgName);
5490            if (pkg != null) {
5491                return filterIfNotSystemUser(
5492                        mActivities.queryIntentForPackage(
5493                                intent, resolvedType, flags, pkg.activities, userId),
5494                        userId);
5495            }
5496            return new ArrayList<ResolveInfo>();
5497        }
5498    }
5499
5500    private static class CrossProfileDomainInfo {
5501        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5502        ResolveInfo resolveInfo;
5503        /* Best domain verification status of the activities found in the other profile */
5504        int bestDomainVerificationStatus;
5505    }
5506
5507    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5508            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5509        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5510                sourceUserId)) {
5511            return null;
5512        }
5513        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5514                resolvedType, flags, parentUserId);
5515
5516        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5517            return null;
5518        }
5519        CrossProfileDomainInfo result = null;
5520        int size = resultTargetUser.size();
5521        for (int i = 0; i < size; i++) {
5522            ResolveInfo riTargetUser = resultTargetUser.get(i);
5523            // Intent filter verification is only for filters that specify a host. So don't return
5524            // those that handle all web uris.
5525            if (riTargetUser.handleAllWebDataURI) {
5526                continue;
5527            }
5528            String packageName = riTargetUser.activityInfo.packageName;
5529            PackageSetting ps = mSettings.mPackages.get(packageName);
5530            if (ps == null) {
5531                continue;
5532            }
5533            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5534            int status = (int)(verificationState >> 32);
5535            if (result == null) {
5536                result = new CrossProfileDomainInfo();
5537                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5538                        sourceUserId, parentUserId);
5539                result.bestDomainVerificationStatus = status;
5540            } else {
5541                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5542                        result.bestDomainVerificationStatus);
5543            }
5544        }
5545        // Don't consider matches with status NEVER across profiles.
5546        if (result != null && result.bestDomainVerificationStatus
5547                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5548            return null;
5549        }
5550        return result;
5551    }
5552
5553    /**
5554     * Verification statuses are ordered from the worse to the best, except for
5555     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5556     */
5557    private int bestDomainVerificationStatus(int status1, int status2) {
5558        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5559            return status2;
5560        }
5561        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5562            return status1;
5563        }
5564        return (int) MathUtils.max(status1, status2);
5565    }
5566
5567    private boolean isUserEnabled(int userId) {
5568        long callingId = Binder.clearCallingIdentity();
5569        try {
5570            UserInfo userInfo = sUserManager.getUserInfo(userId);
5571            return userInfo != null && userInfo.isEnabled();
5572        } finally {
5573            Binder.restoreCallingIdentity(callingId);
5574        }
5575    }
5576
5577    /**
5578     * Filter out activities with systemUserOnly flag set, when current user is not System.
5579     *
5580     * @return filtered list
5581     */
5582    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5583        if (userId == UserHandle.USER_SYSTEM) {
5584            return resolveInfos;
5585        }
5586        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5587            ResolveInfo info = resolveInfos.get(i);
5588            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5589                resolveInfos.remove(i);
5590            }
5591        }
5592        return resolveInfos;
5593    }
5594
5595    /**
5596     * @param resolveInfos list of resolve infos in descending priority order
5597     * @return if the list contains a resolve info with non-negative priority
5598     */
5599    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5600        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5601    }
5602
5603    private static boolean hasWebURI(Intent intent) {
5604        if (intent.getData() == null) {
5605            return false;
5606        }
5607        final String scheme = intent.getScheme();
5608        if (TextUtils.isEmpty(scheme)) {
5609            return false;
5610        }
5611        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5612    }
5613
5614    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5615            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5616            int userId) {
5617        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5618
5619        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5620            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5621                    candidates.size());
5622        }
5623
5624        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5625        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5626        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5627        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5628        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5629        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5630
5631        synchronized (mPackages) {
5632            final int count = candidates.size();
5633            // First, try to use linked apps. Partition the candidates into four lists:
5634            // one for the final results, one for the "do not use ever", one for "undefined status"
5635            // and finally one for "browser app type".
5636            for (int n=0; n<count; n++) {
5637                ResolveInfo info = candidates.get(n);
5638                String packageName = info.activityInfo.packageName;
5639                PackageSetting ps = mSettings.mPackages.get(packageName);
5640                if (ps != null) {
5641                    // Add to the special match all list (Browser use case)
5642                    if (info.handleAllWebDataURI) {
5643                        matchAllList.add(info);
5644                        continue;
5645                    }
5646                    // Try to get the status from User settings first
5647                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5648                    int status = (int)(packedStatus >> 32);
5649                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5650                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5651                        if (DEBUG_DOMAIN_VERIFICATION) {
5652                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5653                                    + " : linkgen=" + linkGeneration);
5654                        }
5655                        // Use link-enabled generation as preferredOrder, i.e.
5656                        // prefer newly-enabled over earlier-enabled.
5657                        info.preferredOrder = linkGeneration;
5658                        alwaysList.add(info);
5659                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5660                        if (DEBUG_DOMAIN_VERIFICATION) {
5661                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5662                        }
5663                        neverList.add(info);
5664                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5665                        if (DEBUG_DOMAIN_VERIFICATION) {
5666                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5667                        }
5668                        alwaysAskList.add(info);
5669                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5670                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5671                        if (DEBUG_DOMAIN_VERIFICATION) {
5672                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5673                        }
5674                        undefinedList.add(info);
5675                    }
5676                }
5677            }
5678
5679            // We'll want to include browser possibilities in a few cases
5680            boolean includeBrowser = false;
5681
5682            // First try to add the "always" resolution(s) for the current user, if any
5683            if (alwaysList.size() > 0) {
5684                result.addAll(alwaysList);
5685            } else {
5686                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5687                result.addAll(undefinedList);
5688                // Maybe add one for the other profile.
5689                if (xpDomainInfo != null && (
5690                        xpDomainInfo.bestDomainVerificationStatus
5691                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5692                    result.add(xpDomainInfo.resolveInfo);
5693                }
5694                includeBrowser = true;
5695            }
5696
5697            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5698            // If there were 'always' entries their preferred order has been set, so we also
5699            // back that off to make the alternatives equivalent
5700            if (alwaysAskList.size() > 0) {
5701                for (ResolveInfo i : result) {
5702                    i.preferredOrder = 0;
5703                }
5704                result.addAll(alwaysAskList);
5705                includeBrowser = true;
5706            }
5707
5708            if (includeBrowser) {
5709                // Also add browsers (all of them or only the default one)
5710                if (DEBUG_DOMAIN_VERIFICATION) {
5711                    Slog.v(TAG, "   ...including browsers in candidate set");
5712                }
5713                if ((matchFlags & MATCH_ALL) != 0) {
5714                    result.addAll(matchAllList);
5715                } else {
5716                    // Browser/generic handling case.  If there's a default browser, go straight
5717                    // to that (but only if there is no other higher-priority match).
5718                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5719                    int maxMatchPrio = 0;
5720                    ResolveInfo defaultBrowserMatch = null;
5721                    final int numCandidates = matchAllList.size();
5722                    for (int n = 0; n < numCandidates; n++) {
5723                        ResolveInfo info = matchAllList.get(n);
5724                        // track the highest overall match priority...
5725                        if (info.priority > maxMatchPrio) {
5726                            maxMatchPrio = info.priority;
5727                        }
5728                        // ...and the highest-priority default browser match
5729                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5730                            if (defaultBrowserMatch == null
5731                                    || (defaultBrowserMatch.priority < info.priority)) {
5732                                if (debug) {
5733                                    Slog.v(TAG, "Considering default browser match " + info);
5734                                }
5735                                defaultBrowserMatch = info;
5736                            }
5737                        }
5738                    }
5739                    if (defaultBrowserMatch != null
5740                            && defaultBrowserMatch.priority >= maxMatchPrio
5741                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5742                    {
5743                        if (debug) {
5744                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5745                        }
5746                        result.add(defaultBrowserMatch);
5747                    } else {
5748                        result.addAll(matchAllList);
5749                    }
5750                }
5751
5752                // If there is nothing selected, add all candidates and remove the ones that the user
5753                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5754                if (result.size() == 0) {
5755                    result.addAll(candidates);
5756                    result.removeAll(neverList);
5757                }
5758            }
5759        }
5760        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5761            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5762                    result.size());
5763            for (ResolveInfo info : result) {
5764                Slog.v(TAG, "  + " + info.activityInfo);
5765            }
5766        }
5767        return result;
5768    }
5769
5770    // Returns a packed value as a long:
5771    //
5772    // high 'int'-sized word: link status: undefined/ask/never/always.
5773    // low 'int'-sized word: relative priority among 'always' results.
5774    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5775        long result = ps.getDomainVerificationStatusForUser(userId);
5776        // if none available, get the master status
5777        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5778            if (ps.getIntentFilterVerificationInfo() != null) {
5779                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5780            }
5781        }
5782        return result;
5783    }
5784
5785    private ResolveInfo querySkipCurrentProfileIntents(
5786            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5787            int flags, int sourceUserId) {
5788        if (matchingFilters != null) {
5789            int size = matchingFilters.size();
5790            for (int i = 0; i < size; i ++) {
5791                CrossProfileIntentFilter filter = matchingFilters.get(i);
5792                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5793                    // Checking if there are activities in the target user that can handle the
5794                    // intent.
5795                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5796                            resolvedType, flags, sourceUserId);
5797                    if (resolveInfo != null) {
5798                        return resolveInfo;
5799                    }
5800                }
5801            }
5802        }
5803        return null;
5804    }
5805
5806    // Return matching ResolveInfo in target user if any.
5807    private ResolveInfo queryCrossProfileIntents(
5808            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5809            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5810        if (matchingFilters != null) {
5811            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5812            // match the same intent. For performance reasons, it is better not to
5813            // run queryIntent twice for the same userId
5814            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5815            int size = matchingFilters.size();
5816            for (int i = 0; i < size; i++) {
5817                CrossProfileIntentFilter filter = matchingFilters.get(i);
5818                int targetUserId = filter.getTargetUserId();
5819                boolean skipCurrentProfile =
5820                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5821                boolean skipCurrentProfileIfNoMatchFound =
5822                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5823                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5824                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5825                    // Checking if there are activities in the target user that can handle the
5826                    // intent.
5827                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5828                            resolvedType, flags, sourceUserId);
5829                    if (resolveInfo != null) return resolveInfo;
5830                    alreadyTriedUserIds.put(targetUserId, true);
5831                }
5832            }
5833        }
5834        return null;
5835    }
5836
5837    /**
5838     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5839     * will forward the intent to the filter's target user.
5840     * Otherwise, returns null.
5841     */
5842    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5843            String resolvedType, int flags, int sourceUserId) {
5844        int targetUserId = filter.getTargetUserId();
5845        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5846                resolvedType, flags, targetUserId);
5847        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5848            // If all the matches in the target profile are suspended, return null.
5849            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5850                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5851                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5852                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5853                            targetUserId);
5854                }
5855            }
5856        }
5857        return null;
5858    }
5859
5860    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5861            int sourceUserId, int targetUserId) {
5862        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5863        long ident = Binder.clearCallingIdentity();
5864        boolean targetIsProfile;
5865        try {
5866            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5867        } finally {
5868            Binder.restoreCallingIdentity(ident);
5869        }
5870        String className;
5871        if (targetIsProfile) {
5872            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5873        } else {
5874            className = FORWARD_INTENT_TO_PARENT;
5875        }
5876        ComponentName forwardingActivityComponentName = new ComponentName(
5877                mAndroidApplication.packageName, className);
5878        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5879                sourceUserId);
5880        if (!targetIsProfile) {
5881            forwardingActivityInfo.showUserIcon = targetUserId;
5882            forwardingResolveInfo.noResourceId = true;
5883        }
5884        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5885        forwardingResolveInfo.priority = 0;
5886        forwardingResolveInfo.preferredOrder = 0;
5887        forwardingResolveInfo.match = 0;
5888        forwardingResolveInfo.isDefault = true;
5889        forwardingResolveInfo.filter = filter;
5890        forwardingResolveInfo.targetUserId = targetUserId;
5891        return forwardingResolveInfo;
5892    }
5893
5894    @Override
5895    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5896            Intent[] specifics, String[] specificTypes, Intent intent,
5897            String resolvedType, int flags, int userId) {
5898        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5899                specificTypes, intent, resolvedType, flags, userId));
5900    }
5901
5902    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5903            Intent[] specifics, String[] specificTypes, Intent intent,
5904            String resolvedType, int flags, int userId) {
5905        if (!sUserManager.exists(userId)) return Collections.emptyList();
5906        flags = updateFlagsForResolve(flags, userId, intent);
5907        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5908                false /* requireFullPermission */, false /* checkShell */,
5909                "query intent activity options");
5910        final String resultsAction = intent.getAction();
5911
5912        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5913                | PackageManager.GET_RESOLVED_FILTER, userId);
5914
5915        if (DEBUG_INTENT_MATCHING) {
5916            Log.v(TAG, "Query " + intent + ": " + results);
5917        }
5918
5919        int specificsPos = 0;
5920        int N;
5921
5922        // todo: note that the algorithm used here is O(N^2).  This
5923        // isn't a problem in our current environment, but if we start running
5924        // into situations where we have more than 5 or 10 matches then this
5925        // should probably be changed to something smarter...
5926
5927        // First we go through and resolve each of the specific items
5928        // that were supplied, taking care of removing any corresponding
5929        // duplicate items in the generic resolve list.
5930        if (specifics != null) {
5931            for (int i=0; i<specifics.length; i++) {
5932                final Intent sintent = specifics[i];
5933                if (sintent == null) {
5934                    continue;
5935                }
5936
5937                if (DEBUG_INTENT_MATCHING) {
5938                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5939                }
5940
5941                String action = sintent.getAction();
5942                if (resultsAction != null && resultsAction.equals(action)) {
5943                    // If this action was explicitly requested, then don't
5944                    // remove things that have it.
5945                    action = null;
5946                }
5947
5948                ResolveInfo ri = null;
5949                ActivityInfo ai = null;
5950
5951                ComponentName comp = sintent.getComponent();
5952                if (comp == null) {
5953                    ri = resolveIntent(
5954                        sintent,
5955                        specificTypes != null ? specificTypes[i] : null,
5956                            flags, userId);
5957                    if (ri == null) {
5958                        continue;
5959                    }
5960                    if (ri == mResolveInfo) {
5961                        // ACK!  Must do something better with this.
5962                    }
5963                    ai = ri.activityInfo;
5964                    comp = new ComponentName(ai.applicationInfo.packageName,
5965                            ai.name);
5966                } else {
5967                    ai = getActivityInfo(comp, flags, userId);
5968                    if (ai == null) {
5969                        continue;
5970                    }
5971                }
5972
5973                // Look for any generic query activities that are duplicates
5974                // of this specific one, and remove them from the results.
5975                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5976                N = results.size();
5977                int j;
5978                for (j=specificsPos; j<N; j++) {
5979                    ResolveInfo sri = results.get(j);
5980                    if ((sri.activityInfo.name.equals(comp.getClassName())
5981                            && sri.activityInfo.applicationInfo.packageName.equals(
5982                                    comp.getPackageName()))
5983                        || (action != null && sri.filter.matchAction(action))) {
5984                        results.remove(j);
5985                        if (DEBUG_INTENT_MATCHING) Log.v(
5986                            TAG, "Removing duplicate item from " + j
5987                            + " due to specific " + specificsPos);
5988                        if (ri == null) {
5989                            ri = sri;
5990                        }
5991                        j--;
5992                        N--;
5993                    }
5994                }
5995
5996                // Add this specific item to its proper place.
5997                if (ri == null) {
5998                    ri = new ResolveInfo();
5999                    ri.activityInfo = ai;
6000                }
6001                results.add(specificsPos, ri);
6002                ri.specificIndex = i;
6003                specificsPos++;
6004            }
6005        }
6006
6007        // Now we go through the remaining generic results and remove any
6008        // duplicate actions that are found here.
6009        N = results.size();
6010        for (int i=specificsPos; i<N-1; i++) {
6011            final ResolveInfo rii = results.get(i);
6012            if (rii.filter == null) {
6013                continue;
6014            }
6015
6016            // Iterate over all of the actions of this result's intent
6017            // filter...  typically this should be just one.
6018            final Iterator<String> it = rii.filter.actionsIterator();
6019            if (it == null) {
6020                continue;
6021            }
6022            while (it.hasNext()) {
6023                final String action = it.next();
6024                if (resultsAction != null && resultsAction.equals(action)) {
6025                    // If this action was explicitly requested, then don't
6026                    // remove things that have it.
6027                    continue;
6028                }
6029                for (int j=i+1; j<N; j++) {
6030                    final ResolveInfo rij = results.get(j);
6031                    if (rij.filter != null && rij.filter.hasAction(action)) {
6032                        results.remove(j);
6033                        if (DEBUG_INTENT_MATCHING) Log.v(
6034                            TAG, "Removing duplicate item from " + j
6035                            + " due to action " + action + " at " + i);
6036                        j--;
6037                        N--;
6038                    }
6039                }
6040            }
6041
6042            // If the caller didn't request filter information, drop it now
6043            // so we don't have to marshall/unmarshall it.
6044            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6045                rii.filter = null;
6046            }
6047        }
6048
6049        // Filter out the caller activity if so requested.
6050        if (caller != null) {
6051            N = results.size();
6052            for (int i=0; i<N; i++) {
6053                ActivityInfo ainfo = results.get(i).activityInfo;
6054                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6055                        && caller.getClassName().equals(ainfo.name)) {
6056                    results.remove(i);
6057                    break;
6058                }
6059            }
6060        }
6061
6062        // If the caller didn't request filter information,
6063        // drop them now so we don't have to
6064        // marshall/unmarshall it.
6065        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6066            N = results.size();
6067            for (int i=0; i<N; i++) {
6068                results.get(i).filter = null;
6069            }
6070        }
6071
6072        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6073        return results;
6074    }
6075
6076    @Override
6077    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6078            String resolvedType, int flags, int userId) {
6079        return new ParceledListSlice<>(
6080                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6081    }
6082
6083    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6084            String resolvedType, int flags, int userId) {
6085        if (!sUserManager.exists(userId)) return Collections.emptyList();
6086        flags = updateFlagsForResolve(flags, userId, intent);
6087        ComponentName comp = intent.getComponent();
6088        if (comp == null) {
6089            if (intent.getSelector() != null) {
6090                intent = intent.getSelector();
6091                comp = intent.getComponent();
6092            }
6093        }
6094        if (comp != null) {
6095            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6096            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6097            if (ai != null) {
6098                ResolveInfo ri = new ResolveInfo();
6099                ri.activityInfo = ai;
6100                list.add(ri);
6101            }
6102            return list;
6103        }
6104
6105        // reader
6106        synchronized (mPackages) {
6107            String pkgName = intent.getPackage();
6108            if (pkgName == null) {
6109                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6110            }
6111            final PackageParser.Package pkg = mPackages.get(pkgName);
6112            if (pkg != null) {
6113                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6114                        userId);
6115            }
6116            return Collections.emptyList();
6117        }
6118    }
6119
6120    @Override
6121    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6122        if (!sUserManager.exists(userId)) return null;
6123        flags = updateFlagsForResolve(flags, userId, intent);
6124        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6125        if (query != null) {
6126            if (query.size() >= 1) {
6127                // If there is more than one service with the same priority,
6128                // just arbitrarily pick the first one.
6129                return query.get(0);
6130            }
6131        }
6132        return null;
6133    }
6134
6135    @Override
6136    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6137            String resolvedType, int flags, int userId) {
6138        return new ParceledListSlice<>(
6139                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6140    }
6141
6142    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6143            String resolvedType, int flags, int userId) {
6144        if (!sUserManager.exists(userId)) return Collections.emptyList();
6145        flags = updateFlagsForResolve(flags, userId, intent);
6146        ComponentName comp = intent.getComponent();
6147        if (comp == null) {
6148            if (intent.getSelector() != null) {
6149                intent = intent.getSelector();
6150                comp = intent.getComponent();
6151            }
6152        }
6153        if (comp != null) {
6154            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6155            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6156            if (si != null) {
6157                final ResolveInfo ri = new ResolveInfo();
6158                ri.serviceInfo = si;
6159                list.add(ri);
6160            }
6161            return list;
6162        }
6163
6164        // reader
6165        synchronized (mPackages) {
6166            String pkgName = intent.getPackage();
6167            if (pkgName == null) {
6168                return mServices.queryIntent(intent, resolvedType, flags, userId);
6169            }
6170            final PackageParser.Package pkg = mPackages.get(pkgName);
6171            if (pkg != null) {
6172                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6173                        userId);
6174            }
6175            return Collections.emptyList();
6176        }
6177    }
6178
6179    @Override
6180    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6181            String resolvedType, int flags, int userId) {
6182        return new ParceledListSlice<>(
6183                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6184    }
6185
6186    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6187            Intent intent, String resolvedType, int flags, int userId) {
6188        if (!sUserManager.exists(userId)) return Collections.emptyList();
6189        flags = updateFlagsForResolve(flags, userId, intent);
6190        ComponentName comp = intent.getComponent();
6191        if (comp == null) {
6192            if (intent.getSelector() != null) {
6193                intent = intent.getSelector();
6194                comp = intent.getComponent();
6195            }
6196        }
6197        if (comp != null) {
6198            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6199            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6200            if (pi != null) {
6201                final ResolveInfo ri = new ResolveInfo();
6202                ri.providerInfo = pi;
6203                list.add(ri);
6204            }
6205            return list;
6206        }
6207
6208        // reader
6209        synchronized (mPackages) {
6210            String pkgName = intent.getPackage();
6211            if (pkgName == null) {
6212                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6213            }
6214            final PackageParser.Package pkg = mPackages.get(pkgName);
6215            if (pkg != null) {
6216                return mProviders.queryIntentForPackage(
6217                        intent, resolvedType, flags, pkg.providers, userId);
6218            }
6219            return Collections.emptyList();
6220        }
6221    }
6222
6223    @Override
6224    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6225        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6226        flags = updateFlagsForPackage(flags, userId, null);
6227        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6229                true /* requireFullPermission */, false /* checkShell */,
6230                "get installed packages");
6231
6232        // writer
6233        synchronized (mPackages) {
6234            ArrayList<PackageInfo> list;
6235            if (listUninstalled) {
6236                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6237                for (PackageSetting ps : mSettings.mPackages.values()) {
6238                    final PackageInfo pi;
6239                    if (ps.pkg != null) {
6240                        pi = generatePackageInfo(ps, flags, userId);
6241                    } else {
6242                        pi = generatePackageInfo(ps, flags, userId);
6243                    }
6244                    if (pi != null) {
6245                        list.add(pi);
6246                    }
6247                }
6248            } else {
6249                list = new ArrayList<PackageInfo>(mPackages.size());
6250                for (PackageParser.Package p : mPackages.values()) {
6251                    final PackageInfo pi =
6252                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6253                    if (pi != null) {
6254                        list.add(pi);
6255                    }
6256                }
6257            }
6258
6259            return new ParceledListSlice<PackageInfo>(list);
6260        }
6261    }
6262
6263    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6264            String[] permissions, boolean[] tmp, int flags, int userId) {
6265        int numMatch = 0;
6266        final PermissionsState permissionsState = ps.getPermissionsState();
6267        for (int i=0; i<permissions.length; i++) {
6268            final String permission = permissions[i];
6269            if (permissionsState.hasPermission(permission, userId)) {
6270                tmp[i] = true;
6271                numMatch++;
6272            } else {
6273                tmp[i] = false;
6274            }
6275        }
6276        if (numMatch == 0) {
6277            return;
6278        }
6279        final PackageInfo pi;
6280        if (ps.pkg != null) {
6281            pi = generatePackageInfo(ps, flags, userId);
6282        } else {
6283            pi = generatePackageInfo(ps, flags, userId);
6284        }
6285        // The above might return null in cases of uninstalled apps or install-state
6286        // skew across users/profiles.
6287        if (pi != null) {
6288            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6289                if (numMatch == permissions.length) {
6290                    pi.requestedPermissions = permissions;
6291                } else {
6292                    pi.requestedPermissions = new String[numMatch];
6293                    numMatch = 0;
6294                    for (int i=0; i<permissions.length; i++) {
6295                        if (tmp[i]) {
6296                            pi.requestedPermissions[numMatch] = permissions[i];
6297                            numMatch++;
6298                        }
6299                    }
6300                }
6301            }
6302            list.add(pi);
6303        }
6304    }
6305
6306    @Override
6307    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6308            String[] permissions, int flags, int userId) {
6309        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6310        flags = updateFlagsForPackage(flags, userId, permissions);
6311        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6312
6313        // writer
6314        synchronized (mPackages) {
6315            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6316            boolean[] tmpBools = new boolean[permissions.length];
6317            if (listUninstalled) {
6318                for (PackageSetting ps : mSettings.mPackages.values()) {
6319                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6320                }
6321            } else {
6322                for (PackageParser.Package pkg : mPackages.values()) {
6323                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6324                    if (ps != null) {
6325                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6326                                userId);
6327                    }
6328                }
6329            }
6330
6331            return new ParceledListSlice<PackageInfo>(list);
6332        }
6333    }
6334
6335    @Override
6336    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6337        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6338        flags = updateFlagsForApplication(flags, userId, null);
6339        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6340
6341        // writer
6342        synchronized (mPackages) {
6343            ArrayList<ApplicationInfo> list;
6344            if (listUninstalled) {
6345                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6346                for (PackageSetting ps : mSettings.mPackages.values()) {
6347                    ApplicationInfo ai;
6348                    if (ps.pkg != null) {
6349                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6350                                ps.readUserState(userId), userId);
6351                    } else {
6352                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6353                    }
6354                    if (ai != null) {
6355                        list.add(ai);
6356                    }
6357                }
6358            } else {
6359                list = new ArrayList<ApplicationInfo>(mPackages.size());
6360                for (PackageParser.Package p : mPackages.values()) {
6361                    if (p.mExtras != null) {
6362                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6363                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6364                        if (ai != null) {
6365                            list.add(ai);
6366                        }
6367                    }
6368                }
6369            }
6370
6371            return new ParceledListSlice<ApplicationInfo>(list);
6372        }
6373    }
6374
6375    @Override
6376    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6377        if (DISABLE_EPHEMERAL_APPS) {
6378            return null;
6379        }
6380
6381        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6382                "getEphemeralApplications");
6383        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6384                true /* requireFullPermission */, false /* checkShell */,
6385                "getEphemeralApplications");
6386        synchronized (mPackages) {
6387            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6388                    .getEphemeralApplicationsLPw(userId);
6389            if (ephemeralApps != null) {
6390                return new ParceledListSlice<>(ephemeralApps);
6391            }
6392        }
6393        return null;
6394    }
6395
6396    @Override
6397    public boolean isEphemeralApplication(String packageName, int userId) {
6398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6399                true /* requireFullPermission */, false /* checkShell */,
6400                "isEphemeral");
6401        if (DISABLE_EPHEMERAL_APPS) {
6402            return false;
6403        }
6404
6405        if (!isCallerSameApp(packageName)) {
6406            return false;
6407        }
6408        synchronized (mPackages) {
6409            PackageParser.Package pkg = mPackages.get(packageName);
6410            if (pkg != null) {
6411                return pkg.applicationInfo.isEphemeralApp();
6412            }
6413        }
6414        return false;
6415    }
6416
6417    @Override
6418    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6419        if (DISABLE_EPHEMERAL_APPS) {
6420            return null;
6421        }
6422
6423        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6424                true /* requireFullPermission */, false /* checkShell */,
6425                "getCookie");
6426        if (!isCallerSameApp(packageName)) {
6427            return null;
6428        }
6429        synchronized (mPackages) {
6430            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6431                    packageName, userId);
6432        }
6433    }
6434
6435    @Override
6436    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6437        if (DISABLE_EPHEMERAL_APPS) {
6438            return true;
6439        }
6440
6441        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6442                true /* requireFullPermission */, true /* checkShell */,
6443                "setCookie");
6444        if (!isCallerSameApp(packageName)) {
6445            return false;
6446        }
6447        synchronized (mPackages) {
6448            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6449                    packageName, cookie, userId);
6450        }
6451    }
6452
6453    @Override
6454    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6455        if (DISABLE_EPHEMERAL_APPS) {
6456            return null;
6457        }
6458
6459        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6460                "getEphemeralApplicationIcon");
6461        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6462                true /* requireFullPermission */, false /* checkShell */,
6463                "getEphemeralApplicationIcon");
6464        synchronized (mPackages) {
6465            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6466                    packageName, userId);
6467        }
6468    }
6469
6470    private boolean isCallerSameApp(String packageName) {
6471        PackageParser.Package pkg = mPackages.get(packageName);
6472        return pkg != null
6473                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6474    }
6475
6476    @Override
6477    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6478        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6479    }
6480
6481    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6482        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6483
6484        // reader
6485        synchronized (mPackages) {
6486            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6487            final int userId = UserHandle.getCallingUserId();
6488            while (i.hasNext()) {
6489                final PackageParser.Package p = i.next();
6490                if (p.applicationInfo == null) continue;
6491
6492                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6493                        && !p.applicationInfo.isDirectBootAware();
6494                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6495                        && p.applicationInfo.isDirectBootAware();
6496
6497                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6498                        && (!mSafeMode || isSystemApp(p))
6499                        && (matchesUnaware || matchesAware)) {
6500                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6501                    if (ps != null) {
6502                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6503                                ps.readUserState(userId), userId);
6504                        if (ai != null) {
6505                            finalList.add(ai);
6506                        }
6507                    }
6508                }
6509            }
6510        }
6511
6512        return finalList;
6513    }
6514
6515    @Override
6516    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6517        if (!sUserManager.exists(userId)) return null;
6518        flags = updateFlagsForComponent(flags, userId, name);
6519        // reader
6520        synchronized (mPackages) {
6521            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6522            PackageSetting ps = provider != null
6523                    ? mSettings.mPackages.get(provider.owner.packageName)
6524                    : null;
6525            return ps != null
6526                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6527                    ? PackageParser.generateProviderInfo(provider, flags,
6528                            ps.readUserState(userId), userId)
6529                    : null;
6530        }
6531    }
6532
6533    /**
6534     * @deprecated
6535     */
6536    @Deprecated
6537    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6538        // reader
6539        synchronized (mPackages) {
6540            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6541                    .entrySet().iterator();
6542            final int userId = UserHandle.getCallingUserId();
6543            while (i.hasNext()) {
6544                Map.Entry<String, PackageParser.Provider> entry = i.next();
6545                PackageParser.Provider p = entry.getValue();
6546                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6547
6548                if (ps != null && p.syncable
6549                        && (!mSafeMode || (p.info.applicationInfo.flags
6550                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6551                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6552                            ps.readUserState(userId), userId);
6553                    if (info != null) {
6554                        outNames.add(entry.getKey());
6555                        outInfo.add(info);
6556                    }
6557                }
6558            }
6559        }
6560    }
6561
6562    @Override
6563    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6564            int uid, int flags) {
6565        final int userId = processName != null ? UserHandle.getUserId(uid)
6566                : UserHandle.getCallingUserId();
6567        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6568        flags = updateFlagsForComponent(flags, userId, processName);
6569
6570        ArrayList<ProviderInfo> finalList = null;
6571        // reader
6572        synchronized (mPackages) {
6573            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6574            while (i.hasNext()) {
6575                final PackageParser.Provider p = i.next();
6576                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6577                if (ps != null && p.info.authority != null
6578                        && (processName == null
6579                                || (p.info.processName.equals(processName)
6580                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6581                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6582                    if (finalList == null) {
6583                        finalList = new ArrayList<ProviderInfo>(3);
6584                    }
6585                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6586                            ps.readUserState(userId), userId);
6587                    if (info != null) {
6588                        finalList.add(info);
6589                    }
6590                }
6591            }
6592        }
6593
6594        if (finalList != null) {
6595            Collections.sort(finalList, mProviderInitOrderSorter);
6596            return new ParceledListSlice<ProviderInfo>(finalList);
6597        }
6598
6599        return ParceledListSlice.emptyList();
6600    }
6601
6602    @Override
6603    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6604        // reader
6605        synchronized (mPackages) {
6606            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6607            return PackageParser.generateInstrumentationInfo(i, flags);
6608        }
6609    }
6610
6611    @Override
6612    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6613            String targetPackage, int flags) {
6614        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6615    }
6616
6617    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6618            int flags) {
6619        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6620
6621        // reader
6622        synchronized (mPackages) {
6623            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6624            while (i.hasNext()) {
6625                final PackageParser.Instrumentation p = i.next();
6626                if (targetPackage == null
6627                        || targetPackage.equals(p.info.targetPackage)) {
6628                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6629                            flags);
6630                    if (ii != null) {
6631                        finalList.add(ii);
6632                    }
6633                }
6634            }
6635        }
6636
6637        return finalList;
6638    }
6639
6640    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6641        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6642        if (overlays == null) {
6643            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6644            return;
6645        }
6646        for (PackageParser.Package opkg : overlays.values()) {
6647            // Not much to do if idmap fails: we already logged the error
6648            // and we certainly don't want to abort installation of pkg simply
6649            // because an overlay didn't fit properly. For these reasons,
6650            // ignore the return value of createIdmapForPackagePairLI.
6651            createIdmapForPackagePairLI(pkg, opkg);
6652        }
6653    }
6654
6655    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6656            PackageParser.Package opkg) {
6657        if (!opkg.mTrustedOverlay) {
6658            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6659                    opkg.baseCodePath + ": overlay not trusted");
6660            return false;
6661        }
6662        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6663        if (overlaySet == null) {
6664            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6665                    opkg.baseCodePath + " but target package has no known overlays");
6666            return false;
6667        }
6668        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6669        // TODO: generate idmap for split APKs
6670        try {
6671            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6672        } catch (InstallerException e) {
6673            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6674                    + opkg.baseCodePath);
6675            return false;
6676        }
6677        PackageParser.Package[] overlayArray =
6678            overlaySet.values().toArray(new PackageParser.Package[0]);
6679        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6680            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6681                return p1.mOverlayPriority - p2.mOverlayPriority;
6682            }
6683        };
6684        Arrays.sort(overlayArray, cmp);
6685
6686        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6687        int i = 0;
6688        for (PackageParser.Package p : overlayArray) {
6689            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6690        }
6691        return true;
6692    }
6693
6694    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6695        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6696        try {
6697            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6698        } finally {
6699            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6700        }
6701    }
6702
6703    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6704        final File[] files = dir.listFiles();
6705        if (ArrayUtils.isEmpty(files)) {
6706            Log.d(TAG, "No files in app dir " + dir);
6707            return;
6708        }
6709
6710        if (DEBUG_PACKAGE_SCANNING) {
6711            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6712                    + " flags=0x" + Integer.toHexString(parseFlags));
6713        }
6714
6715        for (File file : files) {
6716            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6717                    && !PackageInstallerService.isStageName(file.getName());
6718            if (!isPackage) {
6719                // Ignore entries which are not packages
6720                continue;
6721            }
6722            try {
6723                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6724                        scanFlags, currentTime, null);
6725            } catch (PackageManagerException e) {
6726                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6727
6728                // Delete invalid userdata apps
6729                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6730                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6731                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6732                    removeCodePathLI(file);
6733                }
6734            }
6735        }
6736    }
6737
6738    private static File getSettingsProblemFile() {
6739        File dataDir = Environment.getDataDirectory();
6740        File systemDir = new File(dataDir, "system");
6741        File fname = new File(systemDir, "uiderrors.txt");
6742        return fname;
6743    }
6744
6745    static void reportSettingsProblem(int priority, String msg) {
6746        logCriticalInfo(priority, msg);
6747    }
6748
6749    static void logCriticalInfo(int priority, String msg) {
6750        Slog.println(priority, TAG, msg);
6751        EventLogTags.writePmCriticalInfo(msg);
6752        try {
6753            File fname = getSettingsProblemFile();
6754            FileOutputStream out = new FileOutputStream(fname, true);
6755            PrintWriter pw = new FastPrintWriter(out);
6756            SimpleDateFormat formatter = new SimpleDateFormat();
6757            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6758            pw.println(dateString + ": " + msg);
6759            pw.close();
6760            FileUtils.setPermissions(
6761                    fname.toString(),
6762                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6763                    -1, -1);
6764        } catch (java.io.IOException e) {
6765        }
6766    }
6767
6768    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6769        if (srcFile.isDirectory()) {
6770            final File baseFile = new File(pkg.baseCodePath);
6771            long maxModifiedTime = baseFile.lastModified();
6772            if (pkg.splitCodePaths != null) {
6773                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6774                    final File splitFile = new File(pkg.splitCodePaths[i]);
6775                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6776                }
6777            }
6778            return maxModifiedTime;
6779        }
6780        return srcFile.lastModified();
6781    }
6782
6783    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6784            final int policyFlags) throws PackageManagerException {
6785        if (ps != null
6786                && ps.codePath.equals(srcFile)
6787                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6788                && !isCompatSignatureUpdateNeeded(pkg)
6789                && !isRecoverSignatureUpdateNeeded(pkg)) {
6790            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6791            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6792            ArraySet<PublicKey> signingKs;
6793            synchronized (mPackages) {
6794                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6795            }
6796            if (ps.signatures.mSignatures != null
6797                    && ps.signatures.mSignatures.length != 0
6798                    && signingKs != null) {
6799                // Optimization: reuse the existing cached certificates
6800                // if the package appears to be unchanged.
6801                pkg.mSignatures = ps.signatures.mSignatures;
6802                pkg.mSigningKeys = signingKs;
6803                return;
6804            }
6805
6806            Slog.w(TAG, "PackageSetting for " + ps.name
6807                    + " is missing signatures.  Collecting certs again to recover them.");
6808        } else {
6809            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6810        }
6811
6812        try {
6813            PackageParser.collectCertificates(pkg, policyFlags);
6814        } catch (PackageParserException e) {
6815            throw PackageManagerException.from(e);
6816        }
6817    }
6818
6819    /**
6820     *  Traces a package scan.
6821     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6822     */
6823    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6824            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6825        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6826        try {
6827            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6828        } finally {
6829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6830        }
6831    }
6832
6833    /**
6834     *  Scans a package and returns the newly parsed package.
6835     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6836     */
6837    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6838            long currentTime, UserHandle user) throws PackageManagerException {
6839        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6840        PackageParser pp = new PackageParser();
6841        pp.setSeparateProcesses(mSeparateProcesses);
6842        pp.setOnlyCoreApps(mOnlyCore);
6843        pp.setDisplayMetrics(mMetrics);
6844
6845        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6846            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6847        }
6848
6849        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6850        final PackageParser.Package pkg;
6851        try {
6852            pkg = pp.parsePackage(scanFile, parseFlags);
6853        } catch (PackageParserException e) {
6854            throw PackageManagerException.from(e);
6855        } finally {
6856            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6857        }
6858
6859        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6860    }
6861
6862    /**
6863     *  Scans a package and returns the newly parsed package.
6864     *  @throws PackageManagerException on a parse error.
6865     */
6866    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6867            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6868            throws PackageManagerException {
6869        // If the package has children and this is the first dive in the function
6870        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6871        // packages (parent and children) would be successfully scanned before the
6872        // actual scan since scanning mutates internal state and we want to atomically
6873        // install the package and its children.
6874        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6875            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6876                scanFlags |= SCAN_CHECK_ONLY;
6877            }
6878        } else {
6879            scanFlags &= ~SCAN_CHECK_ONLY;
6880        }
6881
6882        // Scan the parent
6883        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6884                scanFlags, currentTime, user);
6885
6886        // Scan the children
6887        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6888        for (int i = 0; i < childCount; i++) {
6889            PackageParser.Package childPackage = pkg.childPackages.get(i);
6890            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6891                    currentTime, user);
6892        }
6893
6894
6895        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6896            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6897        }
6898
6899        return scannedPkg;
6900    }
6901
6902    /**
6903     *  Scans a package and returns the newly parsed package.
6904     *  @throws PackageManagerException on a parse error.
6905     */
6906    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6907            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6908            throws PackageManagerException {
6909        PackageSetting ps = null;
6910        PackageSetting updatedPkg;
6911        // reader
6912        synchronized (mPackages) {
6913            // Look to see if we already know about this package.
6914            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6915            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6916                // This package has been renamed to its original name.  Let's
6917                // use that.
6918                ps = mSettings.peekPackageLPr(oldName);
6919            }
6920            // If there was no original package, see one for the real package name.
6921            if (ps == null) {
6922                ps = mSettings.peekPackageLPr(pkg.packageName);
6923            }
6924            // Check to see if this package could be hiding/updating a system
6925            // package.  Must look for it either under the original or real
6926            // package name depending on our state.
6927            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6928            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6929
6930            // If this is a package we don't know about on the system partition, we
6931            // may need to remove disabled child packages on the system partition
6932            // or may need to not add child packages if the parent apk is updated
6933            // on the data partition and no longer defines this child package.
6934            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6935                // If this is a parent package for an updated system app and this system
6936                // app got an OTA update which no longer defines some of the child packages
6937                // we have to prune them from the disabled system packages.
6938                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6939                if (disabledPs != null) {
6940                    final int scannedChildCount = (pkg.childPackages != null)
6941                            ? pkg.childPackages.size() : 0;
6942                    final int disabledChildCount = disabledPs.childPackageNames != null
6943                            ? disabledPs.childPackageNames.size() : 0;
6944                    for (int i = 0; i < disabledChildCount; i++) {
6945                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6946                        boolean disabledPackageAvailable = false;
6947                        for (int j = 0; j < scannedChildCount; j++) {
6948                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6949                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6950                                disabledPackageAvailable = true;
6951                                break;
6952                            }
6953                         }
6954                         if (!disabledPackageAvailable) {
6955                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6956                         }
6957                    }
6958                }
6959            }
6960        }
6961
6962        boolean updatedPkgBetter = false;
6963        // First check if this is a system package that may involve an update
6964        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6965            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6966            // it needs to drop FLAG_PRIVILEGED.
6967            if (locationIsPrivileged(scanFile)) {
6968                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6969            } else {
6970                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6971            }
6972
6973            if (ps != null && !ps.codePath.equals(scanFile)) {
6974                // The path has changed from what was last scanned...  check the
6975                // version of the new path against what we have stored to determine
6976                // what to do.
6977                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6978                if (pkg.mVersionCode <= ps.versionCode) {
6979                    // The system package has been updated and the code path does not match
6980                    // Ignore entry. Skip it.
6981                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6982                            + " ignored: updated version " + ps.versionCode
6983                            + " better than this " + pkg.mVersionCode);
6984                    if (!updatedPkg.codePath.equals(scanFile)) {
6985                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6986                                + ps.name + " changing from " + updatedPkg.codePathString
6987                                + " to " + scanFile);
6988                        updatedPkg.codePath = scanFile;
6989                        updatedPkg.codePathString = scanFile.toString();
6990                        updatedPkg.resourcePath = scanFile;
6991                        updatedPkg.resourcePathString = scanFile.toString();
6992                    }
6993                    updatedPkg.pkg = pkg;
6994                    updatedPkg.versionCode = pkg.mVersionCode;
6995
6996                    // Update the disabled system child packages to point to the package too.
6997                    final int childCount = updatedPkg.childPackageNames != null
6998                            ? updatedPkg.childPackageNames.size() : 0;
6999                    for (int i = 0; i < childCount; i++) {
7000                        String childPackageName = updatedPkg.childPackageNames.get(i);
7001                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7002                                childPackageName);
7003                        if (updatedChildPkg != null) {
7004                            updatedChildPkg.pkg = pkg;
7005                            updatedChildPkg.versionCode = pkg.mVersionCode;
7006                        }
7007                    }
7008
7009                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7010                            + scanFile + " ignored: updated version " + ps.versionCode
7011                            + " better than this " + pkg.mVersionCode);
7012                } else {
7013                    // The current app on the system partition is better than
7014                    // what we have updated to on the data partition; switch
7015                    // back to the system partition version.
7016                    // At this point, its safely assumed that package installation for
7017                    // apps in system partition will go through. If not there won't be a working
7018                    // version of the app
7019                    // writer
7020                    synchronized (mPackages) {
7021                        // Just remove the loaded entries from package lists.
7022                        mPackages.remove(ps.name);
7023                    }
7024
7025                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7026                            + " reverting from " + ps.codePathString
7027                            + ": new version " + pkg.mVersionCode
7028                            + " better than installed " + ps.versionCode);
7029
7030                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7031                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7032                    synchronized (mInstallLock) {
7033                        args.cleanUpResourcesLI();
7034                    }
7035                    synchronized (mPackages) {
7036                        mSettings.enableSystemPackageLPw(ps.name);
7037                    }
7038                    updatedPkgBetter = true;
7039                }
7040            }
7041        }
7042
7043        if (updatedPkg != null) {
7044            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7045            // initially
7046            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7047
7048            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7049            // flag set initially
7050            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7051                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7052            }
7053        }
7054
7055        // Verify certificates against what was last scanned
7056        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7057
7058        /*
7059         * A new system app appeared, but we already had a non-system one of the
7060         * same name installed earlier.
7061         */
7062        boolean shouldHideSystemApp = false;
7063        if (updatedPkg == null && ps != null
7064                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7065            /*
7066             * Check to make sure the signatures match first. If they don't,
7067             * wipe the installed application and its data.
7068             */
7069            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7070                    != PackageManager.SIGNATURE_MATCH) {
7071                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7072                        + " signatures don't match existing userdata copy; removing");
7073                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7074                        "scanPackageInternalLI")) {
7075                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7076                }
7077                ps = null;
7078            } else {
7079                /*
7080                 * If the newly-added system app is an older version than the
7081                 * already installed version, hide it. It will be scanned later
7082                 * and re-added like an update.
7083                 */
7084                if (pkg.mVersionCode <= ps.versionCode) {
7085                    shouldHideSystemApp = true;
7086                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7087                            + " but new version " + pkg.mVersionCode + " better than installed "
7088                            + ps.versionCode + "; hiding system");
7089                } else {
7090                    /*
7091                     * The newly found system app is a newer version that the
7092                     * one previously installed. Simply remove the
7093                     * already-installed application and replace it with our own
7094                     * while keeping the application data.
7095                     */
7096                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7097                            + " reverting from " + ps.codePathString + ": new version "
7098                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7099                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7100                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7101                    synchronized (mInstallLock) {
7102                        args.cleanUpResourcesLI();
7103                    }
7104                }
7105            }
7106        }
7107
7108        // The apk is forward locked (not public) if its code and resources
7109        // are kept in different files. (except for app in either system or
7110        // vendor path).
7111        // TODO grab this value from PackageSettings
7112        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7113            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7114                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7115            }
7116        }
7117
7118        // TODO: extend to support forward-locked splits
7119        String resourcePath = null;
7120        String baseResourcePath = null;
7121        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7122            if (ps != null && ps.resourcePathString != null) {
7123                resourcePath = ps.resourcePathString;
7124                baseResourcePath = ps.resourcePathString;
7125            } else {
7126                // Should not happen at all. Just log an error.
7127                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7128            }
7129        } else {
7130            resourcePath = pkg.codePath;
7131            baseResourcePath = pkg.baseCodePath;
7132        }
7133
7134        // Set application objects path explicitly.
7135        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7136        pkg.setApplicationInfoCodePath(pkg.codePath);
7137        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7138        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7139        pkg.setApplicationInfoResourcePath(resourcePath);
7140        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7141        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7142
7143        // Note that we invoke the following method only if we are about to unpack an application
7144        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7145                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7146
7147        /*
7148         * If the system app should be overridden by a previously installed
7149         * data, hide the system app now and let the /data/app scan pick it up
7150         * again.
7151         */
7152        if (shouldHideSystemApp) {
7153            synchronized (mPackages) {
7154                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7155            }
7156        }
7157
7158        return scannedPkg;
7159    }
7160
7161    private static String fixProcessName(String defProcessName,
7162            String processName, int uid) {
7163        if (processName == null) {
7164            return defProcessName;
7165        }
7166        return processName;
7167    }
7168
7169    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7170            throws PackageManagerException {
7171        if (pkgSetting.signatures.mSignatures != null) {
7172            // Already existing package. Make sure signatures match
7173            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7174                    == PackageManager.SIGNATURE_MATCH;
7175            if (!match) {
7176                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7177                        == PackageManager.SIGNATURE_MATCH;
7178            }
7179            if (!match) {
7180                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7181                        == PackageManager.SIGNATURE_MATCH;
7182            }
7183            if (!match) {
7184                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7185                        + pkg.packageName + " signatures do not match the "
7186                        + "previously installed version; ignoring!");
7187            }
7188        }
7189
7190        // Check for shared user signatures
7191        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7192            // Already existing package. Make sure signatures match
7193            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7194                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7195            if (!match) {
7196                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7197                        == PackageManager.SIGNATURE_MATCH;
7198            }
7199            if (!match) {
7200                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7201                        == PackageManager.SIGNATURE_MATCH;
7202            }
7203            if (!match) {
7204                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7205                        "Package " + pkg.packageName
7206                        + " has no signatures that match those in shared user "
7207                        + pkgSetting.sharedUser.name + "; ignoring!");
7208            }
7209        }
7210    }
7211
7212    /**
7213     * Enforces that only the system UID or root's UID can call a method exposed
7214     * via Binder.
7215     *
7216     * @param message used as message if SecurityException is thrown
7217     * @throws SecurityException if the caller is not system or root
7218     */
7219    private static final void enforceSystemOrRoot(String message) {
7220        final int uid = Binder.getCallingUid();
7221        if (uid != Process.SYSTEM_UID && uid != 0) {
7222            throw new SecurityException(message);
7223        }
7224    }
7225
7226    @Override
7227    public void performFstrimIfNeeded() {
7228        enforceSystemOrRoot("Only the system can request fstrim");
7229
7230        // Before everything else, see whether we need to fstrim.
7231        try {
7232            IMountService ms = PackageHelper.getMountService();
7233            if (ms != null) {
7234                final boolean isUpgrade = isUpgrade();
7235                boolean doTrim = isUpgrade;
7236                if (doTrim) {
7237                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7238                } else {
7239                    final long interval = android.provider.Settings.Global.getLong(
7240                            mContext.getContentResolver(),
7241                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7242                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7243                    if (interval > 0) {
7244                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7245                        if (timeSinceLast > interval) {
7246                            doTrim = true;
7247                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7248                                    + "; running immediately");
7249                        }
7250                    }
7251                }
7252                if (doTrim) {
7253                    if (!isFirstBoot()) {
7254                        try {
7255                            ActivityManagerNative.getDefault().showBootMessage(
7256                                    mContext.getResources().getString(
7257                                            R.string.android_upgrading_fstrim), true);
7258                        } catch (RemoteException e) {
7259                        }
7260                    }
7261                    ms.runMaintenance();
7262                }
7263            } else {
7264                Slog.e(TAG, "Mount service unavailable!");
7265            }
7266        } catch (RemoteException e) {
7267            // Can't happen; MountService is local
7268        }
7269    }
7270
7271    @Override
7272    public void updatePackagesIfNeeded() {
7273        enforceSystemOrRoot("Only the system can request package update");
7274
7275        // We need to re-extract after an OTA.
7276        boolean causeUpgrade = isUpgrade();
7277
7278        // First boot or factory reset.
7279        // Note: we also handle devices that are upgrading to N right now as if it is their
7280        //       first boot, as they do not have profile data.
7281        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7282
7283        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7284        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7285
7286        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7287            return;
7288        }
7289
7290        List<PackageParser.Package> pkgs;
7291        synchronized (mPackages) {
7292            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7293        }
7294
7295        final long startTime = System.nanoTime();
7296        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7297                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7298
7299        final int elapsedTimeSeconds =
7300                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7301
7302        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7303        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7304        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7305        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7306        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7307    }
7308
7309    /**
7310     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7311     * containing statistics about the invocation. The array consists of three elements,
7312     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7313     * and {@code numberOfPackagesFailed}.
7314     */
7315    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7316            String compilerFilter) {
7317
7318        int numberOfPackagesVisited = 0;
7319        int numberOfPackagesOptimized = 0;
7320        int numberOfPackagesSkipped = 0;
7321        int numberOfPackagesFailed = 0;
7322        final int numberOfPackagesToDexopt = pkgs.size();
7323
7324        for (PackageParser.Package pkg : pkgs) {
7325            numberOfPackagesVisited++;
7326
7327            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7328                if (DEBUG_DEXOPT) {
7329                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7330                }
7331                numberOfPackagesSkipped++;
7332                continue;
7333            }
7334
7335            if (DEBUG_DEXOPT) {
7336                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7337                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7338            }
7339
7340            if (showDialog) {
7341                try {
7342                    ActivityManagerNative.getDefault().showBootMessage(
7343                            mContext.getResources().getString(R.string.android_upgrading_apk,
7344                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7345                } catch (RemoteException e) {
7346                }
7347            }
7348
7349            // checkProfiles is false to avoid merging profiles during boot which
7350            // might interfere with background compilation (b/28612421).
7351            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7352            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7353            // trade-off worth doing to save boot time work.
7354            int dexOptStatus = performDexOptTraced(pkg.packageName,
7355                    false /* checkProfiles */,
7356                    compilerFilter,
7357                    false /* force */);
7358            switch (dexOptStatus) {
7359                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7360                    numberOfPackagesOptimized++;
7361                    break;
7362                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7363                    numberOfPackagesSkipped++;
7364                    break;
7365                case PackageDexOptimizer.DEX_OPT_FAILED:
7366                    numberOfPackagesFailed++;
7367                    break;
7368                default:
7369                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7370                    break;
7371            }
7372        }
7373
7374        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7375                numberOfPackagesFailed };
7376    }
7377
7378    @Override
7379    public void notifyPackageUse(String packageName, int reason) {
7380        synchronized (mPackages) {
7381            PackageParser.Package p = mPackages.get(packageName);
7382            if (p == null) {
7383                return;
7384            }
7385            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7386        }
7387    }
7388
7389    // TODO: this is not used nor needed. Delete it.
7390    @Override
7391    public boolean performDexOptIfNeeded(String packageName) {
7392        int dexOptStatus = performDexOptTraced(packageName,
7393                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7394        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7395    }
7396
7397    @Override
7398    public boolean performDexOpt(String packageName,
7399            boolean checkProfiles, int compileReason, boolean force) {
7400        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7401                getCompilerFilterForReason(compileReason), force);
7402        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7403    }
7404
7405    @Override
7406    public boolean performDexOptMode(String packageName,
7407            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7408        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7409                targetCompilerFilter, force);
7410        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7411    }
7412
7413    private int performDexOptTraced(String packageName,
7414                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7416        try {
7417            return performDexOptInternal(packageName, checkProfiles,
7418                    targetCompilerFilter, force);
7419        } finally {
7420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7421        }
7422    }
7423
7424    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7425    // if the package can now be considered up to date for the given filter.
7426    private int performDexOptInternal(String packageName,
7427                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7428        PackageParser.Package p;
7429        synchronized (mPackages) {
7430            p = mPackages.get(packageName);
7431            if (p == null) {
7432                // Package could not be found. Report failure.
7433                return PackageDexOptimizer.DEX_OPT_FAILED;
7434            }
7435            mPackageUsage.write(false);
7436        }
7437        long callingId = Binder.clearCallingIdentity();
7438        try {
7439            synchronized (mInstallLock) {
7440                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7441                        targetCompilerFilter, force);
7442            }
7443        } finally {
7444            Binder.restoreCallingIdentity(callingId);
7445        }
7446    }
7447
7448    public ArraySet<String> getOptimizablePackages() {
7449        ArraySet<String> pkgs = new ArraySet<String>();
7450        synchronized (mPackages) {
7451            for (PackageParser.Package p : mPackages.values()) {
7452                if (PackageDexOptimizer.canOptimizePackage(p)) {
7453                    pkgs.add(p.packageName);
7454                }
7455            }
7456        }
7457        return pkgs;
7458    }
7459
7460    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7461            boolean checkProfiles, String targetCompilerFilter,
7462            boolean force) {
7463        // Select the dex optimizer based on the force parameter.
7464        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7465        //       allocate an object here.
7466        PackageDexOptimizer pdo = force
7467                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7468                : mPackageDexOptimizer;
7469
7470        // Optimize all dependencies first. Note: we ignore the return value and march on
7471        // on errors.
7472        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7473        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7474        if (!deps.isEmpty()) {
7475            for (PackageParser.Package depPackage : deps) {
7476                // TODO: Analyze and investigate if we (should) profile libraries.
7477                // Currently this will do a full compilation of the library by default.
7478                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7479                        false /* checkProfiles */,
7480                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7481            }
7482        }
7483        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7484                targetCompilerFilter);
7485    }
7486
7487    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7488        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7489            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7490            Set<String> collectedNames = new HashSet<>();
7491            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7492
7493            retValue.remove(p);
7494
7495            return retValue;
7496        } else {
7497            return Collections.emptyList();
7498        }
7499    }
7500
7501    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7502            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7503        if (!collectedNames.contains(p.packageName)) {
7504            collectedNames.add(p.packageName);
7505            collected.add(p);
7506
7507            if (p.usesLibraries != null) {
7508                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7509            }
7510            if (p.usesOptionalLibraries != null) {
7511                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7512                        collectedNames);
7513            }
7514        }
7515    }
7516
7517    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7518            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7519        for (String libName : libs) {
7520            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7521            if (libPkg != null) {
7522                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7523            }
7524        }
7525    }
7526
7527    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7528        synchronized (mPackages) {
7529            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7530            if (lib != null && lib.apk != null) {
7531                return mPackages.get(lib.apk);
7532            }
7533        }
7534        return null;
7535    }
7536
7537    public void shutdown() {
7538        mPackageUsage.write(true);
7539    }
7540
7541    @Override
7542    public void dumpProfiles(String packageName) {
7543        PackageParser.Package pkg;
7544        synchronized (mPackages) {
7545            pkg = mPackages.get(packageName);
7546            if (pkg == null) {
7547                throw new IllegalArgumentException("Unknown package: " + packageName);
7548            }
7549        }
7550        /* Only the shell, root, or the app user should be able to dump profiles. */
7551        int callingUid = Binder.getCallingUid();
7552        if (callingUid != Process.SHELL_UID &&
7553            callingUid != Process.ROOT_UID &&
7554            callingUid != pkg.applicationInfo.uid) {
7555            throw new SecurityException("dumpProfiles");
7556        }
7557
7558        synchronized (mInstallLock) {
7559            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7560            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7561            try {
7562                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7563                String gid = Integer.toString(sharedGid);
7564                String codePaths = TextUtils.join(";", allCodePaths);
7565                mInstaller.dumpProfiles(gid, packageName, codePaths);
7566            } catch (InstallerException e) {
7567                Slog.w(TAG, "Failed to dump profiles", e);
7568            }
7569            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7570        }
7571    }
7572
7573    @Override
7574    public void forceDexOpt(String packageName) {
7575        enforceSystemOrRoot("forceDexOpt");
7576
7577        PackageParser.Package pkg;
7578        synchronized (mPackages) {
7579            pkg = mPackages.get(packageName);
7580            if (pkg == null) {
7581                throw new IllegalArgumentException("Unknown package: " + packageName);
7582            }
7583        }
7584
7585        synchronized (mInstallLock) {
7586            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7587
7588            // Whoever is calling forceDexOpt wants a fully compiled package.
7589            // Don't use profiles since that may cause compilation to be skipped.
7590            final int res = performDexOptInternalWithDependenciesLI(pkg,
7591                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7592                    true /* force */);
7593
7594            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7595            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7596                throw new IllegalStateException("Failed to dexopt: " + res);
7597            }
7598        }
7599    }
7600
7601    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7602        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7603            Slog.w(TAG, "Unable to update from " + oldPkg.name
7604                    + " to " + newPkg.packageName
7605                    + ": old package not in system partition");
7606            return false;
7607        } else if (mPackages.get(oldPkg.name) != null) {
7608            Slog.w(TAG, "Unable to update from " + oldPkg.name
7609                    + " to " + newPkg.packageName
7610                    + ": old package still exists");
7611            return false;
7612        }
7613        return true;
7614    }
7615
7616    void removeCodePathLI(File codePath) {
7617        if (codePath.isDirectory()) {
7618            try {
7619                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7620            } catch (InstallerException e) {
7621                Slog.w(TAG, "Failed to remove code path", e);
7622            }
7623        } else {
7624            codePath.delete();
7625        }
7626    }
7627
7628    private int[] resolveUserIds(int userId) {
7629        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7630    }
7631
7632    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7633        if (pkg == null) {
7634            Slog.wtf(TAG, "Package was null!", new Throwable());
7635            return;
7636        }
7637        clearAppDataLeafLIF(pkg, userId, flags);
7638        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7639        for (int i = 0; i < childCount; i++) {
7640            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7641        }
7642    }
7643
7644    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7645        final PackageSetting ps;
7646        synchronized (mPackages) {
7647            ps = mSettings.mPackages.get(pkg.packageName);
7648        }
7649        for (int realUserId : resolveUserIds(userId)) {
7650            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7651            try {
7652                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7653                        ceDataInode);
7654            } catch (InstallerException e) {
7655                Slog.w(TAG, String.valueOf(e));
7656            }
7657        }
7658    }
7659
7660    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7661        if (pkg == null) {
7662            Slog.wtf(TAG, "Package was null!", new Throwable());
7663            return;
7664        }
7665        destroyAppDataLeafLIF(pkg, userId, flags);
7666        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7667        for (int i = 0; i < childCount; i++) {
7668            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7669        }
7670    }
7671
7672    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7673        final PackageSetting ps;
7674        synchronized (mPackages) {
7675            ps = mSettings.mPackages.get(pkg.packageName);
7676        }
7677        for (int realUserId : resolveUserIds(userId)) {
7678            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7679            try {
7680                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7681                        ceDataInode);
7682            } catch (InstallerException e) {
7683                Slog.w(TAG, String.valueOf(e));
7684            }
7685        }
7686    }
7687
7688    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7689        if (pkg == null) {
7690            Slog.wtf(TAG, "Package was null!", new Throwable());
7691            return;
7692        }
7693        destroyAppProfilesLeafLIF(pkg);
7694        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7695        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7696        for (int i = 0; i < childCount; i++) {
7697            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7698            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7699                    true /* removeBaseMarker */);
7700        }
7701    }
7702
7703    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7704            boolean removeBaseMarker) {
7705        if (pkg.isForwardLocked()) {
7706            return;
7707        }
7708
7709        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7710            try {
7711                path = PackageManagerServiceUtils.realpath(new File(path));
7712            } catch (IOException e) {
7713                // TODO: Should we return early here ?
7714                Slog.w(TAG, "Failed to get canonical path", e);
7715                continue;
7716            }
7717
7718            final String useMarker = path.replace('/', '@');
7719            for (int realUserId : resolveUserIds(userId)) {
7720                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7721                if (removeBaseMarker) {
7722                    File foreignUseMark = new File(profileDir, useMarker);
7723                    if (foreignUseMark.exists()) {
7724                        if (!foreignUseMark.delete()) {
7725                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7726                                    + pkg.packageName);
7727                        }
7728                    }
7729                }
7730
7731                File[] markers = profileDir.listFiles();
7732                if (markers != null) {
7733                    final String searchString = "@" + pkg.packageName + "@";
7734                    // We also delete all markers that contain the package name we're
7735                    // uninstalling. These are associated with secondary dex-files belonging
7736                    // to the package. Reconstructing the path of these dex files is messy
7737                    // in general.
7738                    for (File marker : markers) {
7739                        if (marker.getName().indexOf(searchString) > 0) {
7740                            if (!marker.delete()) {
7741                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7742                                    + pkg.packageName);
7743                            }
7744                        }
7745                    }
7746                }
7747            }
7748        }
7749    }
7750
7751    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7752        try {
7753            mInstaller.destroyAppProfiles(pkg.packageName);
7754        } catch (InstallerException e) {
7755            Slog.w(TAG, String.valueOf(e));
7756        }
7757    }
7758
7759    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7760        if (pkg == null) {
7761            Slog.wtf(TAG, "Package was null!", new Throwable());
7762            return;
7763        }
7764        clearAppProfilesLeafLIF(pkg);
7765        // We don't remove the base foreign use marker when clearing profiles because
7766        // we will rename it when the app is updated. Unlike the actual profile contents,
7767        // the foreign use marker is good across installs.
7768        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7769        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7770        for (int i = 0; i < childCount; i++) {
7771            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7772        }
7773    }
7774
7775    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7776        try {
7777            mInstaller.clearAppProfiles(pkg.packageName);
7778        } catch (InstallerException e) {
7779            Slog.w(TAG, String.valueOf(e));
7780        }
7781    }
7782
7783    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7784            long lastUpdateTime) {
7785        // Set parent install/update time
7786        PackageSetting ps = (PackageSetting) pkg.mExtras;
7787        if (ps != null) {
7788            ps.firstInstallTime = firstInstallTime;
7789            ps.lastUpdateTime = lastUpdateTime;
7790        }
7791        // Set children install/update time
7792        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7793        for (int i = 0; i < childCount; i++) {
7794            PackageParser.Package childPkg = pkg.childPackages.get(i);
7795            ps = (PackageSetting) childPkg.mExtras;
7796            if (ps != null) {
7797                ps.firstInstallTime = firstInstallTime;
7798                ps.lastUpdateTime = lastUpdateTime;
7799            }
7800        }
7801    }
7802
7803    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7804            PackageParser.Package changingLib) {
7805        if (file.path != null) {
7806            usesLibraryFiles.add(file.path);
7807            return;
7808        }
7809        PackageParser.Package p = mPackages.get(file.apk);
7810        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7811            // If we are doing this while in the middle of updating a library apk,
7812            // then we need to make sure to use that new apk for determining the
7813            // dependencies here.  (We haven't yet finished committing the new apk
7814            // to the package manager state.)
7815            if (p == null || p.packageName.equals(changingLib.packageName)) {
7816                p = changingLib;
7817            }
7818        }
7819        if (p != null) {
7820            usesLibraryFiles.addAll(p.getAllCodePaths());
7821        }
7822    }
7823
7824    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7825            PackageParser.Package changingLib) throws PackageManagerException {
7826        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7827            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7828            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7829            for (int i=0; i<N; i++) {
7830                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7831                if (file == null) {
7832                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7833                            "Package " + pkg.packageName + " requires unavailable shared library "
7834                            + pkg.usesLibraries.get(i) + "; failing!");
7835                }
7836                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7837            }
7838            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7839            for (int i=0; i<N; i++) {
7840                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7841                if (file == null) {
7842                    Slog.w(TAG, "Package " + pkg.packageName
7843                            + " desires unavailable shared library "
7844                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7845                } else {
7846                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7847                }
7848            }
7849            N = usesLibraryFiles.size();
7850            if (N > 0) {
7851                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7852            } else {
7853                pkg.usesLibraryFiles = null;
7854            }
7855        }
7856    }
7857
7858    private static boolean hasString(List<String> list, List<String> which) {
7859        if (list == null) {
7860            return false;
7861        }
7862        for (int i=list.size()-1; i>=0; i--) {
7863            for (int j=which.size()-1; j>=0; j--) {
7864                if (which.get(j).equals(list.get(i))) {
7865                    return true;
7866                }
7867            }
7868        }
7869        return false;
7870    }
7871
7872    private void updateAllSharedLibrariesLPw() {
7873        for (PackageParser.Package pkg : mPackages.values()) {
7874            try {
7875                updateSharedLibrariesLPw(pkg, null);
7876            } catch (PackageManagerException e) {
7877                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7878            }
7879        }
7880    }
7881
7882    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7883            PackageParser.Package changingPkg) {
7884        ArrayList<PackageParser.Package> res = null;
7885        for (PackageParser.Package pkg : mPackages.values()) {
7886            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7887                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7888                if (res == null) {
7889                    res = new ArrayList<PackageParser.Package>();
7890                }
7891                res.add(pkg);
7892                try {
7893                    updateSharedLibrariesLPw(pkg, changingPkg);
7894                } catch (PackageManagerException e) {
7895                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7896                }
7897            }
7898        }
7899        return res;
7900    }
7901
7902    /**
7903     * Derive the value of the {@code cpuAbiOverride} based on the provided
7904     * value and an optional stored value from the package settings.
7905     */
7906    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7907        String cpuAbiOverride = null;
7908
7909        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7910            cpuAbiOverride = null;
7911        } else if (abiOverride != null) {
7912            cpuAbiOverride = abiOverride;
7913        } else if (settings != null) {
7914            cpuAbiOverride = settings.cpuAbiOverrideString;
7915        }
7916
7917        return cpuAbiOverride;
7918    }
7919
7920    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7921            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7922                    throws PackageManagerException {
7923        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7924        // If the package has children and this is the first dive in the function
7925        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7926        // whether all packages (parent and children) would be successfully scanned
7927        // before the actual scan since scanning mutates internal state and we want
7928        // to atomically install the package and its children.
7929        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7930            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7931                scanFlags |= SCAN_CHECK_ONLY;
7932            }
7933        } else {
7934            scanFlags &= ~SCAN_CHECK_ONLY;
7935        }
7936
7937        final PackageParser.Package scannedPkg;
7938        try {
7939            // Scan the parent
7940            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7941            // Scan the children
7942            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7943            for (int i = 0; i < childCount; i++) {
7944                PackageParser.Package childPkg = pkg.childPackages.get(i);
7945                scanPackageLI(childPkg, policyFlags,
7946                        scanFlags, currentTime, user);
7947            }
7948        } finally {
7949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7950        }
7951
7952        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7953            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7954        }
7955
7956        return scannedPkg;
7957    }
7958
7959    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7960            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7961        boolean success = false;
7962        try {
7963            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7964                    currentTime, user);
7965            success = true;
7966            return res;
7967        } finally {
7968            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7969                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7970                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7971                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7972                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7973            }
7974        }
7975    }
7976
7977    /**
7978     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7979     */
7980    private static boolean apkHasCode(String fileName) {
7981        StrictJarFile jarFile = null;
7982        try {
7983            jarFile = new StrictJarFile(fileName,
7984                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7985            return jarFile.findEntry("classes.dex") != null;
7986        } catch (IOException ignore) {
7987        } finally {
7988            try {
7989                jarFile.close();
7990            } catch (IOException ignore) {}
7991        }
7992        return false;
7993    }
7994
7995    /**
7996     * Enforces code policy for the package. This ensures that if an APK has
7997     * declared hasCode="true" in its manifest that the APK actually contains
7998     * code.
7999     *
8000     * @throws PackageManagerException If bytecode could not be found when it should exist
8001     */
8002    private static void enforceCodePolicy(PackageParser.Package pkg)
8003            throws PackageManagerException {
8004        final boolean shouldHaveCode =
8005                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8006        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8007            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8008                    "Package " + pkg.baseCodePath + " code is missing");
8009        }
8010
8011        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8012            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8013                final boolean splitShouldHaveCode =
8014                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8015                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8016                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8017                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8018                }
8019            }
8020        }
8021    }
8022
8023    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8024            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8025            throws PackageManagerException {
8026        final File scanFile = new File(pkg.codePath);
8027        if (pkg.applicationInfo.getCodePath() == null ||
8028                pkg.applicationInfo.getResourcePath() == null) {
8029            // Bail out. The resource and code paths haven't been set.
8030            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8031                    "Code and resource paths haven't been set correctly");
8032        }
8033
8034        // Apply policy
8035        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8036            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8037            if (pkg.applicationInfo.isDirectBootAware()) {
8038                // we're direct boot aware; set for all components
8039                for (PackageParser.Service s : pkg.services) {
8040                    s.info.encryptionAware = s.info.directBootAware = true;
8041                }
8042                for (PackageParser.Provider p : pkg.providers) {
8043                    p.info.encryptionAware = p.info.directBootAware = true;
8044                }
8045                for (PackageParser.Activity a : pkg.activities) {
8046                    a.info.encryptionAware = a.info.directBootAware = true;
8047                }
8048                for (PackageParser.Activity r : pkg.receivers) {
8049                    r.info.encryptionAware = r.info.directBootAware = true;
8050                }
8051            }
8052        } else {
8053            // Only allow system apps to be flagged as core apps.
8054            pkg.coreApp = false;
8055            // clear flags not applicable to regular apps
8056            pkg.applicationInfo.privateFlags &=
8057                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8058            pkg.applicationInfo.privateFlags &=
8059                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8060        }
8061        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8062
8063        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8064            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8065        }
8066
8067        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8068            enforceCodePolicy(pkg);
8069        }
8070
8071        if (mCustomResolverComponentName != null &&
8072                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8073            setUpCustomResolverActivity(pkg);
8074        }
8075
8076        if (pkg.packageName.equals("android")) {
8077            synchronized (mPackages) {
8078                if (mAndroidApplication != null) {
8079                    Slog.w(TAG, "*************************************************");
8080                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8081                    Slog.w(TAG, " file=" + scanFile);
8082                    Slog.w(TAG, "*************************************************");
8083                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8084                            "Core android package being redefined.  Skipping.");
8085                }
8086
8087                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8088                    // Set up information for our fall-back user intent resolution activity.
8089                    mPlatformPackage = pkg;
8090                    pkg.mVersionCode = mSdkVersion;
8091                    mAndroidApplication = pkg.applicationInfo;
8092
8093                    if (!mResolverReplaced) {
8094                        mResolveActivity.applicationInfo = mAndroidApplication;
8095                        mResolveActivity.name = ResolverActivity.class.getName();
8096                        mResolveActivity.packageName = mAndroidApplication.packageName;
8097                        mResolveActivity.processName = "system:ui";
8098                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8099                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8100                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8101                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8102                        mResolveActivity.exported = true;
8103                        mResolveActivity.enabled = true;
8104                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8105                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8106                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8107                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8108                                | ActivityInfo.CONFIG_ORIENTATION
8109                                | ActivityInfo.CONFIG_KEYBOARD
8110                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8111                        mResolveInfo.activityInfo = mResolveActivity;
8112                        mResolveInfo.priority = 0;
8113                        mResolveInfo.preferredOrder = 0;
8114                        mResolveInfo.match = 0;
8115                        mResolveComponentName = new ComponentName(
8116                                mAndroidApplication.packageName, mResolveActivity.name);
8117                    }
8118                }
8119            }
8120        }
8121
8122        if (DEBUG_PACKAGE_SCANNING) {
8123            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8124                Log.d(TAG, "Scanning package " + pkg.packageName);
8125        }
8126
8127        synchronized (mPackages) {
8128            if (mPackages.containsKey(pkg.packageName)
8129                    || mSharedLibraries.containsKey(pkg.packageName)) {
8130                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8131                        "Application package " + pkg.packageName
8132                                + " already installed.  Skipping duplicate.");
8133            }
8134
8135            // If we're only installing presumed-existing packages, require that the
8136            // scanned APK is both already known and at the path previously established
8137            // for it.  Previously unknown packages we pick up normally, but if we have an
8138            // a priori expectation about this package's install presence, enforce it.
8139            // With a singular exception for new system packages. When an OTA contains
8140            // a new system package, we allow the codepath to change from a system location
8141            // to the user-installed location. If we don't allow this change, any newer,
8142            // user-installed version of the application will be ignored.
8143            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8144                if (mExpectingBetter.containsKey(pkg.packageName)) {
8145                    logCriticalInfo(Log.WARN,
8146                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8147                } else {
8148                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8149                    if (known != null) {
8150                        if (DEBUG_PACKAGE_SCANNING) {
8151                            Log.d(TAG, "Examining " + pkg.codePath
8152                                    + " and requiring known paths " + known.codePathString
8153                                    + " & " + known.resourcePathString);
8154                        }
8155                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8156                                || !pkg.applicationInfo.getResourcePath().equals(
8157                                known.resourcePathString)) {
8158                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8159                                    "Application package " + pkg.packageName
8160                                            + " found at " + pkg.applicationInfo.getCodePath()
8161                                            + " but expected at " + known.codePathString
8162                                            + "; ignoring.");
8163                        }
8164                    }
8165                }
8166            }
8167        }
8168
8169        // Initialize package source and resource directories
8170        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8171        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8172
8173        SharedUserSetting suid = null;
8174        PackageSetting pkgSetting = null;
8175
8176        if (!isSystemApp(pkg)) {
8177            // Only system apps can use these features.
8178            pkg.mOriginalPackages = null;
8179            pkg.mRealPackage = null;
8180            pkg.mAdoptPermissions = null;
8181        }
8182
8183        // Getting the package setting may have a side-effect, so if we
8184        // are only checking if scan would succeed, stash a copy of the
8185        // old setting to restore at the end.
8186        PackageSetting nonMutatedPs = null;
8187
8188        // writer
8189        synchronized (mPackages) {
8190            if (pkg.mSharedUserId != null) {
8191                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8192                if (suid == null) {
8193                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8194                            "Creating application package " + pkg.packageName
8195                            + " for shared user failed");
8196                }
8197                if (DEBUG_PACKAGE_SCANNING) {
8198                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8199                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8200                                + "): packages=" + suid.packages);
8201                }
8202            }
8203
8204            // Check if we are renaming from an original package name.
8205            PackageSetting origPackage = null;
8206            String realName = null;
8207            if (pkg.mOriginalPackages != null) {
8208                // This package may need to be renamed to a previously
8209                // installed name.  Let's check on that...
8210                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8211                if (pkg.mOriginalPackages.contains(renamed)) {
8212                    // This package had originally been installed as the
8213                    // original name, and we have already taken care of
8214                    // transitioning to the new one.  Just update the new
8215                    // one to continue using the old name.
8216                    realName = pkg.mRealPackage;
8217                    if (!pkg.packageName.equals(renamed)) {
8218                        // Callers into this function may have already taken
8219                        // care of renaming the package; only do it here if
8220                        // it is not already done.
8221                        pkg.setPackageName(renamed);
8222                    }
8223
8224                } else {
8225                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8226                        if ((origPackage = mSettings.peekPackageLPr(
8227                                pkg.mOriginalPackages.get(i))) != null) {
8228                            // We do have the package already installed under its
8229                            // original name...  should we use it?
8230                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8231                                // New package is not compatible with original.
8232                                origPackage = null;
8233                                continue;
8234                            } else if (origPackage.sharedUser != null) {
8235                                // Make sure uid is compatible between packages.
8236                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8237                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8238                                            + " to " + pkg.packageName + ": old uid "
8239                                            + origPackage.sharedUser.name
8240                                            + " differs from " + pkg.mSharedUserId);
8241                                    origPackage = null;
8242                                    continue;
8243                                }
8244                                // TODO: Add case when shared user id is added [b/28144775]
8245                            } else {
8246                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8247                                        + pkg.packageName + " to old name " + origPackage.name);
8248                            }
8249                            break;
8250                        }
8251                    }
8252                }
8253            }
8254
8255            if (mTransferedPackages.contains(pkg.packageName)) {
8256                Slog.w(TAG, "Package " + pkg.packageName
8257                        + " was transferred to another, but its .apk remains");
8258            }
8259
8260            // See comments in nonMutatedPs declaration
8261            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8262                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8263                if (foundPs != null) {
8264                    nonMutatedPs = new PackageSetting(foundPs);
8265                }
8266            }
8267
8268            // Just create the setting, don't add it yet. For already existing packages
8269            // the PkgSetting exists already and doesn't have to be created.
8270            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8271                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8272                    pkg.applicationInfo.primaryCpuAbi,
8273                    pkg.applicationInfo.secondaryCpuAbi,
8274                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8275                    user, false);
8276            if (pkgSetting == null) {
8277                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8278                        "Creating application package " + pkg.packageName + " failed");
8279            }
8280
8281            if (pkgSetting.origPackage != null) {
8282                // If we are first transitioning from an original package,
8283                // fix up the new package's name now.  We need to do this after
8284                // looking up the package under its new name, so getPackageLP
8285                // can take care of fiddling things correctly.
8286                pkg.setPackageName(origPackage.name);
8287
8288                // File a report about this.
8289                String msg = "New package " + pkgSetting.realName
8290                        + " renamed to replace old package " + pkgSetting.name;
8291                reportSettingsProblem(Log.WARN, msg);
8292
8293                // Make a note of it.
8294                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8295                    mTransferedPackages.add(origPackage.name);
8296                }
8297
8298                // No longer need to retain this.
8299                pkgSetting.origPackage = null;
8300            }
8301
8302            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8303                // Make a note of it.
8304                mTransferedPackages.add(pkg.packageName);
8305            }
8306
8307            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8308                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8309            }
8310
8311            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8312                // Check all shared libraries and map to their actual file path.
8313                // We only do this here for apps not on a system dir, because those
8314                // are the only ones that can fail an install due to this.  We
8315                // will take care of the system apps by updating all of their
8316                // library paths after the scan is done.
8317                updateSharedLibrariesLPw(pkg, null);
8318            }
8319
8320            if (mFoundPolicyFile) {
8321                SELinuxMMAC.assignSeinfoValue(pkg);
8322            }
8323
8324            pkg.applicationInfo.uid = pkgSetting.appId;
8325            pkg.mExtras = pkgSetting;
8326            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8327                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8328                    // We just determined the app is signed correctly, so bring
8329                    // over the latest parsed certs.
8330                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8331                } else {
8332                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8333                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8334                                "Package " + pkg.packageName + " upgrade keys do not match the "
8335                                + "previously installed version");
8336                    } else {
8337                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8338                        String msg = "System package " + pkg.packageName
8339                            + " signature changed; retaining data.";
8340                        reportSettingsProblem(Log.WARN, msg);
8341                    }
8342                }
8343            } else {
8344                try {
8345                    verifySignaturesLP(pkgSetting, pkg);
8346                    // We just determined the app is signed correctly, so bring
8347                    // over the latest parsed certs.
8348                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8349                } catch (PackageManagerException e) {
8350                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8351                        throw e;
8352                    }
8353                    // The signature has changed, but this package is in the system
8354                    // image...  let's recover!
8355                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8356                    // However...  if this package is part of a shared user, but it
8357                    // doesn't match the signature of the shared user, let's fail.
8358                    // What this means is that you can't change the signatures
8359                    // associated with an overall shared user, which doesn't seem all
8360                    // that unreasonable.
8361                    if (pkgSetting.sharedUser != null) {
8362                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8363                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8364                            throw new PackageManagerException(
8365                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8366                                            "Signature mismatch for shared user: "
8367                                            + pkgSetting.sharedUser);
8368                        }
8369                    }
8370                    // File a report about this.
8371                    String msg = "System package " + pkg.packageName
8372                        + " signature changed; retaining data.";
8373                    reportSettingsProblem(Log.WARN, msg);
8374                }
8375            }
8376            // Verify that this new package doesn't have any content providers
8377            // that conflict with existing packages.  Only do this if the
8378            // package isn't already installed, since we don't want to break
8379            // things that are installed.
8380            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8381                final int N = pkg.providers.size();
8382                int i;
8383                for (i=0; i<N; i++) {
8384                    PackageParser.Provider p = pkg.providers.get(i);
8385                    if (p.info.authority != null) {
8386                        String names[] = p.info.authority.split(";");
8387                        for (int j = 0; j < names.length; j++) {
8388                            if (mProvidersByAuthority.containsKey(names[j])) {
8389                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8390                                final String otherPackageName =
8391                                        ((other != null && other.getComponentName() != null) ?
8392                                                other.getComponentName().getPackageName() : "?");
8393                                throw new PackageManagerException(
8394                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8395                                                "Can't install because provider name " + names[j]
8396                                                + " (in package " + pkg.applicationInfo.packageName
8397                                                + ") is already used by " + otherPackageName);
8398                            }
8399                        }
8400                    }
8401                }
8402            }
8403
8404            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8405                // This package wants to adopt ownership of permissions from
8406                // another package.
8407                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8408                    final String origName = pkg.mAdoptPermissions.get(i);
8409                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8410                    if (orig != null) {
8411                        if (verifyPackageUpdateLPr(orig, pkg)) {
8412                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8413                                    + pkg.packageName);
8414                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8415                        }
8416                    }
8417                }
8418            }
8419        }
8420
8421        final String pkgName = pkg.packageName;
8422
8423        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8424        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8425        pkg.applicationInfo.processName = fixProcessName(
8426                pkg.applicationInfo.packageName,
8427                pkg.applicationInfo.processName,
8428                pkg.applicationInfo.uid);
8429
8430        if (pkg != mPlatformPackage) {
8431            // Get all of our default paths setup
8432            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8433        }
8434
8435        final String path = scanFile.getPath();
8436        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8437
8438        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8439            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8440
8441            // Some system apps still use directory structure for native libraries
8442            // in which case we might end up not detecting abi solely based on apk
8443            // structure. Try to detect abi based on directory structure.
8444            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8445                    pkg.applicationInfo.primaryCpuAbi == null) {
8446                setBundledAppAbisAndRoots(pkg, pkgSetting);
8447                setNativeLibraryPaths(pkg);
8448            }
8449
8450        } else {
8451            if ((scanFlags & SCAN_MOVE) != 0) {
8452                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8453                // but we already have this packages package info in the PackageSetting. We just
8454                // use that and derive the native library path based on the new codepath.
8455                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8456                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8457            }
8458
8459            // Set native library paths again. For moves, the path will be updated based on the
8460            // ABIs we've determined above. For non-moves, the path will be updated based on the
8461            // ABIs we determined during compilation, but the path will depend on the final
8462            // package path (after the rename away from the stage path).
8463            setNativeLibraryPaths(pkg);
8464        }
8465
8466        // This is a special case for the "system" package, where the ABI is
8467        // dictated by the zygote configuration (and init.rc). We should keep track
8468        // of this ABI so that we can deal with "normal" applications that run under
8469        // the same UID correctly.
8470        if (mPlatformPackage == pkg) {
8471            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8472                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8473        }
8474
8475        // If there's a mismatch between the abi-override in the package setting
8476        // and the abiOverride specified for the install. Warn about this because we
8477        // would've already compiled the app without taking the package setting into
8478        // account.
8479        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8480            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8481                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8482                        " for package " + pkg.packageName);
8483            }
8484        }
8485
8486        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8487        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8488        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8489
8490        // Copy the derived override back to the parsed package, so that we can
8491        // update the package settings accordingly.
8492        pkg.cpuAbiOverride = cpuAbiOverride;
8493
8494        if (DEBUG_ABI_SELECTION) {
8495            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8496                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8497                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8498        }
8499
8500        // Push the derived path down into PackageSettings so we know what to
8501        // clean up at uninstall time.
8502        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8503
8504        if (DEBUG_ABI_SELECTION) {
8505            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8506                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8507                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8508        }
8509
8510        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8511            // We don't do this here during boot because we can do it all
8512            // at once after scanning all existing packages.
8513            //
8514            // We also do this *before* we perform dexopt on this package, so that
8515            // we can avoid redundant dexopts, and also to make sure we've got the
8516            // code and package path correct.
8517            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8518                    pkg, true /* boot complete */);
8519        }
8520
8521        if (mFactoryTest && pkg.requestedPermissions.contains(
8522                android.Manifest.permission.FACTORY_TEST)) {
8523            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8524        }
8525
8526        ArrayList<PackageParser.Package> clientLibPkgs = null;
8527
8528        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8529            if (nonMutatedPs != null) {
8530                synchronized (mPackages) {
8531                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8532                }
8533            }
8534            return pkg;
8535        }
8536
8537        // Only privileged apps and updated privileged apps can add child packages.
8538        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8539            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8540                throw new PackageManagerException("Only privileged apps and updated "
8541                        + "privileged apps can add child packages. Ignoring package "
8542                        + pkg.packageName);
8543            }
8544            final int childCount = pkg.childPackages.size();
8545            for (int i = 0; i < childCount; i++) {
8546                PackageParser.Package childPkg = pkg.childPackages.get(i);
8547                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8548                        childPkg.packageName)) {
8549                    throw new PackageManagerException("Cannot override a child package of "
8550                            + "another disabled system app. Ignoring package " + pkg.packageName);
8551                }
8552            }
8553        }
8554
8555        // writer
8556        synchronized (mPackages) {
8557            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8558                // Only system apps can add new shared libraries.
8559                if (pkg.libraryNames != null) {
8560                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8561                        String name = pkg.libraryNames.get(i);
8562                        boolean allowed = false;
8563                        if (pkg.isUpdatedSystemApp()) {
8564                            // New library entries can only be added through the
8565                            // system image.  This is important to get rid of a lot
8566                            // of nasty edge cases: for example if we allowed a non-
8567                            // system update of the app to add a library, then uninstalling
8568                            // the update would make the library go away, and assumptions
8569                            // we made such as through app install filtering would now
8570                            // have allowed apps on the device which aren't compatible
8571                            // with it.  Better to just have the restriction here, be
8572                            // conservative, and create many fewer cases that can negatively
8573                            // impact the user experience.
8574                            final PackageSetting sysPs = mSettings
8575                                    .getDisabledSystemPkgLPr(pkg.packageName);
8576                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8577                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8578                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8579                                        allowed = true;
8580                                        break;
8581                                    }
8582                                }
8583                            }
8584                        } else {
8585                            allowed = true;
8586                        }
8587                        if (allowed) {
8588                            if (!mSharedLibraries.containsKey(name)) {
8589                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8590                            } else if (!name.equals(pkg.packageName)) {
8591                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8592                                        + name + " already exists; skipping");
8593                            }
8594                        } else {
8595                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8596                                    + name + " that is not declared on system image; skipping");
8597                        }
8598                    }
8599                    if ((scanFlags & SCAN_BOOTING) == 0) {
8600                        // If we are not booting, we need to update any applications
8601                        // that are clients of our shared library.  If we are booting,
8602                        // this will all be done once the scan is complete.
8603                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8604                    }
8605                }
8606            }
8607        }
8608
8609        if ((scanFlags & SCAN_BOOTING) != 0) {
8610            // No apps can run during boot scan, so they don't need to be frozen
8611        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8612            // Caller asked to not kill app, so it's probably not frozen
8613        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8614            // Caller asked us to ignore frozen check for some reason; they
8615            // probably didn't know the package name
8616        } else {
8617            // We're doing major surgery on this package, so it better be frozen
8618            // right now to keep it from launching
8619            checkPackageFrozen(pkgName);
8620        }
8621
8622        // Also need to kill any apps that are dependent on the library.
8623        if (clientLibPkgs != null) {
8624            for (int i=0; i<clientLibPkgs.size(); i++) {
8625                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8626                killApplication(clientPkg.applicationInfo.packageName,
8627                        clientPkg.applicationInfo.uid, "update lib");
8628            }
8629        }
8630
8631        // Make sure we're not adding any bogus keyset info
8632        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8633        ksms.assertScannedPackageValid(pkg);
8634
8635        // writer
8636        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8637
8638        boolean createIdmapFailed = false;
8639        synchronized (mPackages) {
8640            // We don't expect installation to fail beyond this point
8641
8642            if (pkgSetting.pkg != null) {
8643                // Note that |user| might be null during the initial boot scan. If a codePath
8644                // for an app has changed during a boot scan, it's due to an app update that's
8645                // part of the system partition and marker changes must be applied to all users.
8646                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8647                    (user != null) ? user : UserHandle.ALL);
8648            }
8649
8650            // Add the new setting to mSettings
8651            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8652            // Add the new setting to mPackages
8653            mPackages.put(pkg.applicationInfo.packageName, pkg);
8654            // Make sure we don't accidentally delete its data.
8655            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8656            while (iter.hasNext()) {
8657                PackageCleanItem item = iter.next();
8658                if (pkgName.equals(item.packageName)) {
8659                    iter.remove();
8660                }
8661            }
8662
8663            // Take care of first install / last update times.
8664            if (currentTime != 0) {
8665                if (pkgSetting.firstInstallTime == 0) {
8666                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8667                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8668                    pkgSetting.lastUpdateTime = currentTime;
8669                }
8670            } else if (pkgSetting.firstInstallTime == 0) {
8671                // We need *something*.  Take time time stamp of the file.
8672                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8673            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8674                if (scanFileTime != pkgSetting.timeStamp) {
8675                    // A package on the system image has changed; consider this
8676                    // to be an update.
8677                    pkgSetting.lastUpdateTime = scanFileTime;
8678                }
8679            }
8680
8681            // Add the package's KeySets to the global KeySetManagerService
8682            ksms.addScannedPackageLPw(pkg);
8683
8684            int N = pkg.providers.size();
8685            StringBuilder r = null;
8686            int i;
8687            for (i=0; i<N; i++) {
8688                PackageParser.Provider p = pkg.providers.get(i);
8689                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8690                        p.info.processName, pkg.applicationInfo.uid);
8691                mProviders.addProvider(p);
8692                p.syncable = p.info.isSyncable;
8693                if (p.info.authority != null) {
8694                    String names[] = p.info.authority.split(";");
8695                    p.info.authority = null;
8696                    for (int j = 0; j < names.length; j++) {
8697                        if (j == 1 && p.syncable) {
8698                            // We only want the first authority for a provider to possibly be
8699                            // syncable, so if we already added this provider using a different
8700                            // authority clear the syncable flag. We copy the provider before
8701                            // changing it because the mProviders object contains a reference
8702                            // to a provider that we don't want to change.
8703                            // Only do this for the second authority since the resulting provider
8704                            // object can be the same for all future authorities for this provider.
8705                            p = new PackageParser.Provider(p);
8706                            p.syncable = false;
8707                        }
8708                        if (!mProvidersByAuthority.containsKey(names[j])) {
8709                            mProvidersByAuthority.put(names[j], p);
8710                            if (p.info.authority == null) {
8711                                p.info.authority = names[j];
8712                            } else {
8713                                p.info.authority = p.info.authority + ";" + names[j];
8714                            }
8715                            if (DEBUG_PACKAGE_SCANNING) {
8716                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8717                                    Log.d(TAG, "Registered content provider: " + names[j]
8718                                            + ", className = " + p.info.name + ", isSyncable = "
8719                                            + p.info.isSyncable);
8720                            }
8721                        } else {
8722                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8723                            Slog.w(TAG, "Skipping provider name " + names[j] +
8724                                    " (in package " + pkg.applicationInfo.packageName +
8725                                    "): name already used by "
8726                                    + ((other != null && other.getComponentName() != null)
8727                                            ? other.getComponentName().getPackageName() : "?"));
8728                        }
8729                    }
8730                }
8731                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8732                    if (r == null) {
8733                        r = new StringBuilder(256);
8734                    } else {
8735                        r.append(' ');
8736                    }
8737                    r.append(p.info.name);
8738                }
8739            }
8740            if (r != null) {
8741                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8742            }
8743
8744            N = pkg.services.size();
8745            r = null;
8746            for (i=0; i<N; i++) {
8747                PackageParser.Service s = pkg.services.get(i);
8748                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8749                        s.info.processName, pkg.applicationInfo.uid);
8750                mServices.addService(s);
8751                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8752                    if (r == null) {
8753                        r = new StringBuilder(256);
8754                    } else {
8755                        r.append(' ');
8756                    }
8757                    r.append(s.info.name);
8758                }
8759            }
8760            if (r != null) {
8761                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8762            }
8763
8764            N = pkg.receivers.size();
8765            r = null;
8766            for (i=0; i<N; i++) {
8767                PackageParser.Activity a = pkg.receivers.get(i);
8768                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8769                        a.info.processName, pkg.applicationInfo.uid);
8770                mReceivers.addActivity(a, "receiver");
8771                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8772                    if (r == null) {
8773                        r = new StringBuilder(256);
8774                    } else {
8775                        r.append(' ');
8776                    }
8777                    r.append(a.info.name);
8778                }
8779            }
8780            if (r != null) {
8781                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8782            }
8783
8784            N = pkg.activities.size();
8785            r = null;
8786            for (i=0; i<N; i++) {
8787                PackageParser.Activity a = pkg.activities.get(i);
8788                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8789                        a.info.processName, pkg.applicationInfo.uid);
8790                mActivities.addActivity(a, "activity");
8791                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8792                    if (r == null) {
8793                        r = new StringBuilder(256);
8794                    } else {
8795                        r.append(' ');
8796                    }
8797                    r.append(a.info.name);
8798                }
8799            }
8800            if (r != null) {
8801                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8802            }
8803
8804            N = pkg.permissionGroups.size();
8805            r = null;
8806            for (i=0; i<N; i++) {
8807                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8808                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8809                if (cur == null) {
8810                    mPermissionGroups.put(pg.info.name, pg);
8811                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8812                        if (r == null) {
8813                            r = new StringBuilder(256);
8814                        } else {
8815                            r.append(' ');
8816                        }
8817                        r.append(pg.info.name);
8818                    }
8819                } else {
8820                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8821                            + pg.info.packageName + " ignored: original from "
8822                            + cur.info.packageName);
8823                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8824                        if (r == null) {
8825                            r = new StringBuilder(256);
8826                        } else {
8827                            r.append(' ');
8828                        }
8829                        r.append("DUP:");
8830                        r.append(pg.info.name);
8831                    }
8832                }
8833            }
8834            if (r != null) {
8835                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8836            }
8837
8838            N = pkg.permissions.size();
8839            r = null;
8840            for (i=0; i<N; i++) {
8841                PackageParser.Permission p = pkg.permissions.get(i);
8842
8843                // Assume by default that we did not install this permission into the system.
8844                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8845
8846                // Now that permission groups have a special meaning, we ignore permission
8847                // groups for legacy apps to prevent unexpected behavior. In particular,
8848                // permissions for one app being granted to someone just becase they happen
8849                // to be in a group defined by another app (before this had no implications).
8850                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8851                    p.group = mPermissionGroups.get(p.info.group);
8852                    // Warn for a permission in an unknown group.
8853                    if (p.info.group != null && p.group == null) {
8854                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8855                                + p.info.packageName + " in an unknown group " + p.info.group);
8856                    }
8857                }
8858
8859                ArrayMap<String, BasePermission> permissionMap =
8860                        p.tree ? mSettings.mPermissionTrees
8861                                : mSettings.mPermissions;
8862                BasePermission bp = permissionMap.get(p.info.name);
8863
8864                // Allow system apps to redefine non-system permissions
8865                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8866                    final boolean currentOwnerIsSystem = (bp.perm != null
8867                            && isSystemApp(bp.perm.owner));
8868                    if (isSystemApp(p.owner)) {
8869                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8870                            // It's a built-in permission and no owner, take ownership now
8871                            bp.packageSetting = pkgSetting;
8872                            bp.perm = p;
8873                            bp.uid = pkg.applicationInfo.uid;
8874                            bp.sourcePackage = p.info.packageName;
8875                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8876                        } else if (!currentOwnerIsSystem) {
8877                            String msg = "New decl " + p.owner + " of permission  "
8878                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8879                            reportSettingsProblem(Log.WARN, msg);
8880                            bp = null;
8881                        }
8882                    }
8883                }
8884
8885                if (bp == null) {
8886                    bp = new BasePermission(p.info.name, p.info.packageName,
8887                            BasePermission.TYPE_NORMAL);
8888                    permissionMap.put(p.info.name, bp);
8889                }
8890
8891                if (bp.perm == null) {
8892                    if (bp.sourcePackage == null
8893                            || bp.sourcePackage.equals(p.info.packageName)) {
8894                        BasePermission tree = findPermissionTreeLP(p.info.name);
8895                        if (tree == null
8896                                || tree.sourcePackage.equals(p.info.packageName)) {
8897                            bp.packageSetting = pkgSetting;
8898                            bp.perm = p;
8899                            bp.uid = pkg.applicationInfo.uid;
8900                            bp.sourcePackage = p.info.packageName;
8901                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8902                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8903                                if (r == null) {
8904                                    r = new StringBuilder(256);
8905                                } else {
8906                                    r.append(' ');
8907                                }
8908                                r.append(p.info.name);
8909                            }
8910                        } else {
8911                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8912                                    + p.info.packageName + " ignored: base tree "
8913                                    + tree.name + " is from package "
8914                                    + tree.sourcePackage);
8915                        }
8916                    } else {
8917                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8918                                + p.info.packageName + " ignored: original from "
8919                                + bp.sourcePackage);
8920                    }
8921                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8922                    if (r == null) {
8923                        r = new StringBuilder(256);
8924                    } else {
8925                        r.append(' ');
8926                    }
8927                    r.append("DUP:");
8928                    r.append(p.info.name);
8929                }
8930                if (bp.perm == p) {
8931                    bp.protectionLevel = p.info.protectionLevel;
8932                }
8933            }
8934
8935            if (r != null) {
8936                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8937            }
8938
8939            N = pkg.instrumentation.size();
8940            r = null;
8941            for (i=0; i<N; i++) {
8942                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8943                a.info.packageName = pkg.applicationInfo.packageName;
8944                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8945                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8946                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8947                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8948                a.info.dataDir = pkg.applicationInfo.dataDir;
8949                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8950                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8951
8952                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8953                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8954                mInstrumentation.put(a.getComponentName(), a);
8955                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8956                    if (r == null) {
8957                        r = new StringBuilder(256);
8958                    } else {
8959                        r.append(' ');
8960                    }
8961                    r.append(a.info.name);
8962                }
8963            }
8964            if (r != null) {
8965                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8966            }
8967
8968            if (pkg.protectedBroadcasts != null) {
8969                N = pkg.protectedBroadcasts.size();
8970                for (i=0; i<N; i++) {
8971                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8972                }
8973            }
8974
8975            pkgSetting.setTimeStamp(scanFileTime);
8976
8977            // Create idmap files for pairs of (packages, overlay packages).
8978            // Note: "android", ie framework-res.apk, is handled by native layers.
8979            if (pkg.mOverlayTarget != null) {
8980                // This is an overlay package.
8981                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8982                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8983                        mOverlays.put(pkg.mOverlayTarget,
8984                                new ArrayMap<String, PackageParser.Package>());
8985                    }
8986                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8987                    map.put(pkg.packageName, pkg);
8988                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8989                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8990                        createIdmapFailed = true;
8991                    }
8992                }
8993            } else if (mOverlays.containsKey(pkg.packageName) &&
8994                    !pkg.packageName.equals("android")) {
8995                // This is a regular package, with one or more known overlay packages.
8996                createIdmapsForPackageLI(pkg);
8997            }
8998        }
8999
9000        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9001
9002        if (createIdmapFailed) {
9003            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9004                    "scanPackageLI failed to createIdmap");
9005        }
9006        return pkg;
9007    }
9008
9009    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9010            PackageParser.Package update, UserHandle user) {
9011        if (existing.applicationInfo == null || update.applicationInfo == null) {
9012            // This isn't due to an app installation.
9013            return;
9014        }
9015
9016        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9017        final File newCodePath = new File(update.applicationInfo.getCodePath());
9018
9019        // The codePath hasn't changed, so there's nothing for us to do.
9020        if (Objects.equals(oldCodePath, newCodePath)) {
9021            return;
9022        }
9023
9024        File canonicalNewCodePath;
9025        try {
9026            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9027        } catch (IOException e) {
9028            Slog.w(TAG, "Failed to get canonical path.", e);
9029            return;
9030        }
9031
9032        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9033        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9034        // that the last component of the path (i.e, the name) doesn't need canonicalization
9035        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9036        // but may change in the future. Hopefully this function won't exist at that point.
9037        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9038                oldCodePath.getName());
9039
9040        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9041        // with "@".
9042        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9043        if (!oldMarkerPrefix.endsWith("@")) {
9044            oldMarkerPrefix += "@";
9045        }
9046        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9047        if (!newMarkerPrefix.endsWith("@")) {
9048            newMarkerPrefix += "@";
9049        }
9050
9051        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9052        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9053        for (String updatedPath : updatedPaths) {
9054            String updatedPathName = new File(updatedPath).getName();
9055            markerSuffixes.add(updatedPathName.replace('/', '@'));
9056        }
9057
9058        for (int userId : resolveUserIds(user.getIdentifier())) {
9059            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9060
9061            for (String markerSuffix : markerSuffixes) {
9062                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9063                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9064                if (oldForeignUseMark.exists()) {
9065                    try {
9066                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9067                                newForeignUseMark.getAbsolutePath());
9068                    } catch (ErrnoException e) {
9069                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9070                        oldForeignUseMark.delete();
9071                    }
9072                }
9073            }
9074        }
9075    }
9076
9077    /**
9078     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9079     * is derived purely on the basis of the contents of {@code scanFile} and
9080     * {@code cpuAbiOverride}.
9081     *
9082     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9083     */
9084    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9085                                 String cpuAbiOverride, boolean extractLibs)
9086            throws PackageManagerException {
9087        // TODO: We can probably be smarter about this stuff. For installed apps,
9088        // we can calculate this information at install time once and for all. For
9089        // system apps, we can probably assume that this information doesn't change
9090        // after the first boot scan. As things stand, we do lots of unnecessary work.
9091
9092        // Give ourselves some initial paths; we'll come back for another
9093        // pass once we've determined ABI below.
9094        setNativeLibraryPaths(pkg);
9095
9096        // We would never need to extract libs for forward-locked and external packages,
9097        // since the container service will do it for us. We shouldn't attempt to
9098        // extract libs from system app when it was not updated.
9099        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9100                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9101            extractLibs = false;
9102        }
9103
9104        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9105        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9106
9107        NativeLibraryHelper.Handle handle = null;
9108        try {
9109            handle = NativeLibraryHelper.Handle.create(pkg);
9110            // TODO(multiArch): This can be null for apps that didn't go through the
9111            // usual installation process. We can calculate it again, like we
9112            // do during install time.
9113            //
9114            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9115            // unnecessary.
9116            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9117
9118            // Null out the abis so that they can be recalculated.
9119            pkg.applicationInfo.primaryCpuAbi = null;
9120            pkg.applicationInfo.secondaryCpuAbi = null;
9121            if (isMultiArch(pkg.applicationInfo)) {
9122                // Warn if we've set an abiOverride for multi-lib packages..
9123                // By definition, we need to copy both 32 and 64 bit libraries for
9124                // such packages.
9125                if (pkg.cpuAbiOverride != null
9126                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9127                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9128                }
9129
9130                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9131                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9132                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9133                    if (extractLibs) {
9134                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9135                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9136                                useIsaSpecificSubdirs);
9137                    } else {
9138                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9139                    }
9140                }
9141
9142                maybeThrowExceptionForMultiArchCopy(
9143                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9144
9145                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9146                    if (extractLibs) {
9147                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9148                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9149                                useIsaSpecificSubdirs);
9150                    } else {
9151                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9152                    }
9153                }
9154
9155                maybeThrowExceptionForMultiArchCopy(
9156                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9157
9158                if (abi64 >= 0) {
9159                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9160                }
9161
9162                if (abi32 >= 0) {
9163                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9164                    if (abi64 >= 0) {
9165                        if (pkg.use32bitAbi) {
9166                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9167                            pkg.applicationInfo.primaryCpuAbi = abi;
9168                        } else {
9169                            pkg.applicationInfo.secondaryCpuAbi = abi;
9170                        }
9171                    } else {
9172                        pkg.applicationInfo.primaryCpuAbi = abi;
9173                    }
9174                }
9175
9176            } else {
9177                String[] abiList = (cpuAbiOverride != null) ?
9178                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9179
9180                // Enable gross and lame hacks for apps that are built with old
9181                // SDK tools. We must scan their APKs for renderscript bitcode and
9182                // not launch them if it's present. Don't bother checking on devices
9183                // that don't have 64 bit support.
9184                boolean needsRenderScriptOverride = false;
9185                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9186                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9187                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9188                    needsRenderScriptOverride = true;
9189                }
9190
9191                final int copyRet;
9192                if (extractLibs) {
9193                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9194                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9195                } else {
9196                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9197                }
9198
9199                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9200                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9201                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9202                }
9203
9204                if (copyRet >= 0) {
9205                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9206                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9207                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9208                } else if (needsRenderScriptOverride) {
9209                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9210                }
9211            }
9212        } catch (IOException ioe) {
9213            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9214        } finally {
9215            IoUtils.closeQuietly(handle);
9216        }
9217
9218        // Now that we've calculated the ABIs and determined if it's an internal app,
9219        // we will go ahead and populate the nativeLibraryPath.
9220        setNativeLibraryPaths(pkg);
9221    }
9222
9223    /**
9224     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9225     * i.e, so that all packages can be run inside a single process if required.
9226     *
9227     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9228     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9229     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9230     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9231     * updating a package that belongs to a shared user.
9232     *
9233     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9234     * adds unnecessary complexity.
9235     */
9236    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9237            PackageParser.Package scannedPackage, boolean bootComplete) {
9238        String requiredInstructionSet = null;
9239        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9240            requiredInstructionSet = VMRuntime.getInstructionSet(
9241                     scannedPackage.applicationInfo.primaryCpuAbi);
9242        }
9243
9244        PackageSetting requirer = null;
9245        for (PackageSetting ps : packagesForUser) {
9246            // If packagesForUser contains scannedPackage, we skip it. This will happen
9247            // when scannedPackage is an update of an existing package. Without this check,
9248            // we will never be able to change the ABI of any package belonging to a shared
9249            // user, even if it's compatible with other packages.
9250            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9251                if (ps.primaryCpuAbiString == null) {
9252                    continue;
9253                }
9254
9255                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9256                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9257                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9258                    // this but there's not much we can do.
9259                    String errorMessage = "Instruction set mismatch, "
9260                            + ((requirer == null) ? "[caller]" : requirer)
9261                            + " requires " + requiredInstructionSet + " whereas " + ps
9262                            + " requires " + instructionSet;
9263                    Slog.w(TAG, errorMessage);
9264                }
9265
9266                if (requiredInstructionSet == null) {
9267                    requiredInstructionSet = instructionSet;
9268                    requirer = ps;
9269                }
9270            }
9271        }
9272
9273        if (requiredInstructionSet != null) {
9274            String adjustedAbi;
9275            if (requirer != null) {
9276                // requirer != null implies that either scannedPackage was null or that scannedPackage
9277                // did not require an ABI, in which case we have to adjust scannedPackage to match
9278                // the ABI of the set (which is the same as requirer's ABI)
9279                adjustedAbi = requirer.primaryCpuAbiString;
9280                if (scannedPackage != null) {
9281                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9282                }
9283            } else {
9284                // requirer == null implies that we're updating all ABIs in the set to
9285                // match scannedPackage.
9286                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9287            }
9288
9289            for (PackageSetting ps : packagesForUser) {
9290                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9291                    if (ps.primaryCpuAbiString != null) {
9292                        continue;
9293                    }
9294
9295                    ps.primaryCpuAbiString = adjustedAbi;
9296                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9297                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9298                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9299                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9300                                + " (requirer="
9301                                + (requirer == null ? "null" : requirer.pkg.packageName)
9302                                + ", scannedPackage="
9303                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9304                                + ")");
9305                        try {
9306                            mInstaller.rmdex(ps.codePathString,
9307                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9308                        } catch (InstallerException ignored) {
9309                        }
9310                    }
9311                }
9312            }
9313        }
9314    }
9315
9316    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9317        synchronized (mPackages) {
9318            mResolverReplaced = true;
9319            // Set up information for custom user intent resolution activity.
9320            mResolveActivity.applicationInfo = pkg.applicationInfo;
9321            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9322            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9323            mResolveActivity.processName = pkg.applicationInfo.packageName;
9324            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9325            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9326                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9327            mResolveActivity.theme = 0;
9328            mResolveActivity.exported = true;
9329            mResolveActivity.enabled = true;
9330            mResolveInfo.activityInfo = mResolveActivity;
9331            mResolveInfo.priority = 0;
9332            mResolveInfo.preferredOrder = 0;
9333            mResolveInfo.match = 0;
9334            mResolveComponentName = mCustomResolverComponentName;
9335            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9336                    mResolveComponentName);
9337        }
9338    }
9339
9340    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9341        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9342
9343        // Set up information for ephemeral installer activity
9344        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9345        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9346        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9347        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9348        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9349        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9350                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9351        mEphemeralInstallerActivity.theme = 0;
9352        mEphemeralInstallerActivity.exported = true;
9353        mEphemeralInstallerActivity.enabled = true;
9354        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9355        mEphemeralInstallerInfo.priority = 0;
9356        mEphemeralInstallerInfo.preferredOrder = 0;
9357        mEphemeralInstallerInfo.match = 0;
9358
9359        if (DEBUG_EPHEMERAL) {
9360            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9361        }
9362    }
9363
9364    private static String calculateBundledApkRoot(final String codePathString) {
9365        final File codePath = new File(codePathString);
9366        final File codeRoot;
9367        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9368            codeRoot = Environment.getRootDirectory();
9369        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9370            codeRoot = Environment.getOemDirectory();
9371        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9372            codeRoot = Environment.getVendorDirectory();
9373        } else {
9374            // Unrecognized code path; take its top real segment as the apk root:
9375            // e.g. /something/app/blah.apk => /something
9376            try {
9377                File f = codePath.getCanonicalFile();
9378                File parent = f.getParentFile();    // non-null because codePath is a file
9379                File tmp;
9380                while ((tmp = parent.getParentFile()) != null) {
9381                    f = parent;
9382                    parent = tmp;
9383                }
9384                codeRoot = f;
9385                Slog.w(TAG, "Unrecognized code path "
9386                        + codePath + " - using " + codeRoot);
9387            } catch (IOException e) {
9388                // Can't canonicalize the code path -- shenanigans?
9389                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9390                return Environment.getRootDirectory().getPath();
9391            }
9392        }
9393        return codeRoot.getPath();
9394    }
9395
9396    /**
9397     * Derive and set the location of native libraries for the given package,
9398     * which varies depending on where and how the package was installed.
9399     */
9400    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9401        final ApplicationInfo info = pkg.applicationInfo;
9402        final String codePath = pkg.codePath;
9403        final File codeFile = new File(codePath);
9404        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9405        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9406
9407        info.nativeLibraryRootDir = null;
9408        info.nativeLibraryRootRequiresIsa = false;
9409        info.nativeLibraryDir = null;
9410        info.secondaryNativeLibraryDir = null;
9411
9412        if (isApkFile(codeFile)) {
9413            // Monolithic install
9414            if (bundledApp) {
9415                // If "/system/lib64/apkname" exists, assume that is the per-package
9416                // native library directory to use; otherwise use "/system/lib/apkname".
9417                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9418                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9419                        getPrimaryInstructionSet(info));
9420
9421                // This is a bundled system app so choose the path based on the ABI.
9422                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9423                // is just the default path.
9424                final String apkName = deriveCodePathName(codePath);
9425                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9426                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9427                        apkName).getAbsolutePath();
9428
9429                if (info.secondaryCpuAbi != null) {
9430                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9431                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9432                            secondaryLibDir, apkName).getAbsolutePath();
9433                }
9434            } else if (asecApp) {
9435                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9436                        .getAbsolutePath();
9437            } else {
9438                final String apkName = deriveCodePathName(codePath);
9439                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9440                        .getAbsolutePath();
9441            }
9442
9443            info.nativeLibraryRootRequiresIsa = false;
9444            info.nativeLibraryDir = info.nativeLibraryRootDir;
9445        } else {
9446            // Cluster install
9447            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9448            info.nativeLibraryRootRequiresIsa = true;
9449
9450            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9451                    getPrimaryInstructionSet(info)).getAbsolutePath();
9452
9453            if (info.secondaryCpuAbi != null) {
9454                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9455                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9456            }
9457        }
9458    }
9459
9460    /**
9461     * Calculate the abis and roots for a bundled app. These can uniquely
9462     * be determined from the contents of the system partition, i.e whether
9463     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9464     * of this information, and instead assume that the system was built
9465     * sensibly.
9466     */
9467    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9468                                           PackageSetting pkgSetting) {
9469        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9470
9471        // If "/system/lib64/apkname" exists, assume that is the per-package
9472        // native library directory to use; otherwise use "/system/lib/apkname".
9473        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9474        setBundledAppAbi(pkg, apkRoot, apkName);
9475        // pkgSetting might be null during rescan following uninstall of updates
9476        // to a bundled app, so accommodate that possibility.  The settings in
9477        // that case will be established later from the parsed package.
9478        //
9479        // If the settings aren't null, sync them up with what we've just derived.
9480        // note that apkRoot isn't stored in the package settings.
9481        if (pkgSetting != null) {
9482            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9483            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9484        }
9485    }
9486
9487    /**
9488     * Deduces the ABI of a bundled app and sets the relevant fields on the
9489     * parsed pkg object.
9490     *
9491     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9492     *        under which system libraries are installed.
9493     * @param apkName the name of the installed package.
9494     */
9495    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9496        final File codeFile = new File(pkg.codePath);
9497
9498        final boolean has64BitLibs;
9499        final boolean has32BitLibs;
9500        if (isApkFile(codeFile)) {
9501            // Monolithic install
9502            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9503            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9504        } else {
9505            // Cluster install
9506            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9507            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9508                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9509                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9510                has64BitLibs = (new File(rootDir, isa)).exists();
9511            } else {
9512                has64BitLibs = false;
9513            }
9514            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9515                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9516                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9517                has32BitLibs = (new File(rootDir, isa)).exists();
9518            } else {
9519                has32BitLibs = false;
9520            }
9521        }
9522
9523        if (has64BitLibs && !has32BitLibs) {
9524            // The package has 64 bit libs, but not 32 bit libs. Its primary
9525            // ABI should be 64 bit. We can safely assume here that the bundled
9526            // native libraries correspond to the most preferred ABI in the list.
9527
9528            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9529            pkg.applicationInfo.secondaryCpuAbi = null;
9530        } else if (has32BitLibs && !has64BitLibs) {
9531            // The package has 32 bit libs but not 64 bit libs. Its primary
9532            // ABI should be 32 bit.
9533
9534            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9535            pkg.applicationInfo.secondaryCpuAbi = null;
9536        } else if (has32BitLibs && has64BitLibs) {
9537            // The application has both 64 and 32 bit bundled libraries. We check
9538            // here that the app declares multiArch support, and warn if it doesn't.
9539            //
9540            // We will be lenient here and record both ABIs. The primary will be the
9541            // ABI that's higher on the list, i.e, a device that's configured to prefer
9542            // 64 bit apps will see a 64 bit primary ABI,
9543
9544            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9545                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9546            }
9547
9548            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9549                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9550                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9551            } else {
9552                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9553                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9554            }
9555        } else {
9556            pkg.applicationInfo.primaryCpuAbi = null;
9557            pkg.applicationInfo.secondaryCpuAbi = null;
9558        }
9559    }
9560
9561    private void killApplication(String pkgName, int appId, String reason) {
9562        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9563    }
9564
9565    private void killApplication(String pkgName, int appId, int userId, String reason) {
9566        // Request the ActivityManager to kill the process(only for existing packages)
9567        // so that we do not end up in a confused state while the user is still using the older
9568        // version of the application while the new one gets installed.
9569        final long token = Binder.clearCallingIdentity();
9570        try {
9571            IActivityManager am = ActivityManagerNative.getDefault();
9572            if (am != null) {
9573                try {
9574                    am.killApplication(pkgName, appId, userId, reason);
9575                } catch (RemoteException e) {
9576                }
9577            }
9578        } finally {
9579            Binder.restoreCallingIdentity(token);
9580        }
9581    }
9582
9583    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9584        // Remove the parent package setting
9585        PackageSetting ps = (PackageSetting) pkg.mExtras;
9586        if (ps != null) {
9587            removePackageLI(ps, chatty);
9588        }
9589        // Remove the child package setting
9590        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9591        for (int i = 0; i < childCount; i++) {
9592            PackageParser.Package childPkg = pkg.childPackages.get(i);
9593            ps = (PackageSetting) childPkg.mExtras;
9594            if (ps != null) {
9595                removePackageLI(ps, chatty);
9596            }
9597        }
9598    }
9599
9600    void removePackageLI(PackageSetting ps, boolean chatty) {
9601        if (DEBUG_INSTALL) {
9602            if (chatty)
9603                Log.d(TAG, "Removing package " + ps.name);
9604        }
9605
9606        // writer
9607        synchronized (mPackages) {
9608            mPackages.remove(ps.name);
9609            final PackageParser.Package pkg = ps.pkg;
9610            if (pkg != null) {
9611                cleanPackageDataStructuresLILPw(pkg, chatty);
9612            }
9613        }
9614    }
9615
9616    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9617        if (DEBUG_INSTALL) {
9618            if (chatty)
9619                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9620        }
9621
9622        // writer
9623        synchronized (mPackages) {
9624            // Remove the parent package
9625            mPackages.remove(pkg.applicationInfo.packageName);
9626            cleanPackageDataStructuresLILPw(pkg, chatty);
9627
9628            // Remove the child packages
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                mPackages.remove(childPkg.applicationInfo.packageName);
9633                cleanPackageDataStructuresLILPw(childPkg, chatty);
9634            }
9635        }
9636    }
9637
9638    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9639        int N = pkg.providers.size();
9640        StringBuilder r = null;
9641        int i;
9642        for (i=0; i<N; i++) {
9643            PackageParser.Provider p = pkg.providers.get(i);
9644            mProviders.removeProvider(p);
9645            if (p.info.authority == null) {
9646
9647                /* There was another ContentProvider with this authority when
9648                 * this app was installed so this authority is null,
9649                 * Ignore it as we don't have to unregister the provider.
9650                 */
9651                continue;
9652            }
9653            String names[] = p.info.authority.split(";");
9654            for (int j = 0; j < names.length; j++) {
9655                if (mProvidersByAuthority.get(names[j]) == p) {
9656                    mProvidersByAuthority.remove(names[j]);
9657                    if (DEBUG_REMOVE) {
9658                        if (chatty)
9659                            Log.d(TAG, "Unregistered content provider: " + names[j]
9660                                    + ", className = " + p.info.name + ", isSyncable = "
9661                                    + p.info.isSyncable);
9662                    }
9663                }
9664            }
9665            if (DEBUG_REMOVE && chatty) {
9666                if (r == null) {
9667                    r = new StringBuilder(256);
9668                } else {
9669                    r.append(' ');
9670                }
9671                r.append(p.info.name);
9672            }
9673        }
9674        if (r != null) {
9675            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9676        }
9677
9678        N = pkg.services.size();
9679        r = null;
9680        for (i=0; i<N; i++) {
9681            PackageParser.Service s = pkg.services.get(i);
9682            mServices.removeService(s);
9683            if (chatty) {
9684                if (r == null) {
9685                    r = new StringBuilder(256);
9686                } else {
9687                    r.append(' ');
9688                }
9689                r.append(s.info.name);
9690            }
9691        }
9692        if (r != null) {
9693            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9694        }
9695
9696        N = pkg.receivers.size();
9697        r = null;
9698        for (i=0; i<N; i++) {
9699            PackageParser.Activity a = pkg.receivers.get(i);
9700            mReceivers.removeActivity(a, "receiver");
9701            if (DEBUG_REMOVE && chatty) {
9702                if (r == null) {
9703                    r = new StringBuilder(256);
9704                } else {
9705                    r.append(' ');
9706                }
9707                r.append(a.info.name);
9708            }
9709        }
9710        if (r != null) {
9711            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9712        }
9713
9714        N = pkg.activities.size();
9715        r = null;
9716        for (i=0; i<N; i++) {
9717            PackageParser.Activity a = pkg.activities.get(i);
9718            mActivities.removeActivity(a, "activity");
9719            if (DEBUG_REMOVE && chatty) {
9720                if (r == null) {
9721                    r = new StringBuilder(256);
9722                } else {
9723                    r.append(' ');
9724                }
9725                r.append(a.info.name);
9726            }
9727        }
9728        if (r != null) {
9729            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9730        }
9731
9732        N = pkg.permissions.size();
9733        r = null;
9734        for (i=0; i<N; i++) {
9735            PackageParser.Permission p = pkg.permissions.get(i);
9736            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9737            if (bp == null) {
9738                bp = mSettings.mPermissionTrees.get(p.info.name);
9739            }
9740            if (bp != null && bp.perm == p) {
9741                bp.perm = null;
9742                if (DEBUG_REMOVE && chatty) {
9743                    if (r == null) {
9744                        r = new StringBuilder(256);
9745                    } else {
9746                        r.append(' ');
9747                    }
9748                    r.append(p.info.name);
9749                }
9750            }
9751            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9752                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9753                if (appOpPkgs != null) {
9754                    appOpPkgs.remove(pkg.packageName);
9755                }
9756            }
9757        }
9758        if (r != null) {
9759            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9760        }
9761
9762        N = pkg.requestedPermissions.size();
9763        r = null;
9764        for (i=0; i<N; i++) {
9765            String perm = pkg.requestedPermissions.get(i);
9766            BasePermission bp = mSettings.mPermissions.get(perm);
9767            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9768                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9769                if (appOpPkgs != null) {
9770                    appOpPkgs.remove(pkg.packageName);
9771                    if (appOpPkgs.isEmpty()) {
9772                        mAppOpPermissionPackages.remove(perm);
9773                    }
9774                }
9775            }
9776        }
9777        if (r != null) {
9778            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9779        }
9780
9781        N = pkg.instrumentation.size();
9782        r = null;
9783        for (i=0; i<N; i++) {
9784            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9785            mInstrumentation.remove(a.getComponentName());
9786            if (DEBUG_REMOVE && chatty) {
9787                if (r == null) {
9788                    r = new StringBuilder(256);
9789                } else {
9790                    r.append(' ');
9791                }
9792                r.append(a.info.name);
9793            }
9794        }
9795        if (r != null) {
9796            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9797        }
9798
9799        r = null;
9800        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9801            // Only system apps can hold shared libraries.
9802            if (pkg.libraryNames != null) {
9803                for (i=0; i<pkg.libraryNames.size(); i++) {
9804                    String name = pkg.libraryNames.get(i);
9805                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9806                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9807                        mSharedLibraries.remove(name);
9808                        if (DEBUG_REMOVE && chatty) {
9809                            if (r == null) {
9810                                r = new StringBuilder(256);
9811                            } else {
9812                                r.append(' ');
9813                            }
9814                            r.append(name);
9815                        }
9816                    }
9817                }
9818            }
9819        }
9820        if (r != null) {
9821            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9822        }
9823    }
9824
9825    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9826        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9827            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9828                return true;
9829            }
9830        }
9831        return false;
9832    }
9833
9834    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9835    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9836    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9837
9838    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9839        // Update the parent permissions
9840        updatePermissionsLPw(pkg.packageName, pkg, flags);
9841        // Update the child permissions
9842        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9843        for (int i = 0; i < childCount; i++) {
9844            PackageParser.Package childPkg = pkg.childPackages.get(i);
9845            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9846        }
9847    }
9848
9849    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9850            int flags) {
9851        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9852        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9853    }
9854
9855    private void updatePermissionsLPw(String changingPkg,
9856            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9857        // Make sure there are no dangling permission trees.
9858        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9859        while (it.hasNext()) {
9860            final BasePermission bp = it.next();
9861            if (bp.packageSetting == null) {
9862                // We may not yet have parsed the package, so just see if
9863                // we still know about its settings.
9864                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9865            }
9866            if (bp.packageSetting == null) {
9867                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9868                        + " from package " + bp.sourcePackage);
9869                it.remove();
9870            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9871                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9872                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9873                            + " from package " + bp.sourcePackage);
9874                    flags |= UPDATE_PERMISSIONS_ALL;
9875                    it.remove();
9876                }
9877            }
9878        }
9879
9880        // Make sure all dynamic permissions have been assigned to a package,
9881        // and make sure there are no dangling permissions.
9882        it = mSettings.mPermissions.values().iterator();
9883        while (it.hasNext()) {
9884            final BasePermission bp = it.next();
9885            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9886                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9887                        + bp.name + " pkg=" + bp.sourcePackage
9888                        + " info=" + bp.pendingInfo);
9889                if (bp.packageSetting == null && bp.pendingInfo != null) {
9890                    final BasePermission tree = findPermissionTreeLP(bp.name);
9891                    if (tree != null && tree.perm != null) {
9892                        bp.packageSetting = tree.packageSetting;
9893                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9894                                new PermissionInfo(bp.pendingInfo));
9895                        bp.perm.info.packageName = tree.perm.info.packageName;
9896                        bp.perm.info.name = bp.name;
9897                        bp.uid = tree.uid;
9898                    }
9899                }
9900            }
9901            if (bp.packageSetting == null) {
9902                // We may not yet have parsed the package, so just see if
9903                // we still know about its settings.
9904                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9905            }
9906            if (bp.packageSetting == null) {
9907                Slog.w(TAG, "Removing dangling permission: " + bp.name
9908                        + " from package " + bp.sourcePackage);
9909                it.remove();
9910            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9911                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9912                    Slog.i(TAG, "Removing old permission: " + bp.name
9913                            + " from package " + bp.sourcePackage);
9914                    flags |= UPDATE_PERMISSIONS_ALL;
9915                    it.remove();
9916                }
9917            }
9918        }
9919
9920        // Now update the permissions for all packages, in particular
9921        // replace the granted permissions of the system packages.
9922        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9923            for (PackageParser.Package pkg : mPackages.values()) {
9924                if (pkg != pkgInfo) {
9925                    // Only replace for packages on requested volume
9926                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9927                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9928                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9929                    grantPermissionsLPw(pkg, replace, changingPkg);
9930                }
9931            }
9932        }
9933
9934        if (pkgInfo != null) {
9935            // Only replace for packages on requested volume
9936            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9937            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9938                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9939            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9940        }
9941    }
9942
9943    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9944            String packageOfInterest) {
9945        // IMPORTANT: There are two types of permissions: install and runtime.
9946        // Install time permissions are granted when the app is installed to
9947        // all device users and users added in the future. Runtime permissions
9948        // are granted at runtime explicitly to specific users. Normal and signature
9949        // protected permissions are install time permissions. Dangerous permissions
9950        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9951        // otherwise they are runtime permissions. This function does not manage
9952        // runtime permissions except for the case an app targeting Lollipop MR1
9953        // being upgraded to target a newer SDK, in which case dangerous permissions
9954        // are transformed from install time to runtime ones.
9955
9956        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9957        if (ps == null) {
9958            return;
9959        }
9960
9961        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9962
9963        PermissionsState permissionsState = ps.getPermissionsState();
9964        PermissionsState origPermissions = permissionsState;
9965
9966        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9967
9968        boolean runtimePermissionsRevoked = false;
9969        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9970
9971        boolean changedInstallPermission = false;
9972
9973        if (replace) {
9974            ps.installPermissionsFixed = false;
9975            if (!ps.isSharedUser()) {
9976                origPermissions = new PermissionsState(permissionsState);
9977                permissionsState.reset();
9978            } else {
9979                // We need to know only about runtime permission changes since the
9980                // calling code always writes the install permissions state but
9981                // the runtime ones are written only if changed. The only cases of
9982                // changed runtime permissions here are promotion of an install to
9983                // runtime and revocation of a runtime from a shared user.
9984                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9985                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9986                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9987                    runtimePermissionsRevoked = true;
9988                }
9989            }
9990        }
9991
9992        permissionsState.setGlobalGids(mGlobalGids);
9993
9994        final int N = pkg.requestedPermissions.size();
9995        for (int i=0; i<N; i++) {
9996            final String name = pkg.requestedPermissions.get(i);
9997            final BasePermission bp = mSettings.mPermissions.get(name);
9998
9999            if (DEBUG_INSTALL) {
10000                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10001            }
10002
10003            if (bp == null || bp.packageSetting == null) {
10004                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10005                    Slog.w(TAG, "Unknown permission " + name
10006                            + " in package " + pkg.packageName);
10007                }
10008                continue;
10009            }
10010
10011            final String perm = bp.name;
10012            boolean allowedSig = false;
10013            int grant = GRANT_DENIED;
10014
10015            // Keep track of app op permissions.
10016            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10017                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10018                if (pkgs == null) {
10019                    pkgs = new ArraySet<>();
10020                    mAppOpPermissionPackages.put(bp.name, pkgs);
10021                }
10022                pkgs.add(pkg.packageName);
10023            }
10024
10025            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10026            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10027                    >= Build.VERSION_CODES.M;
10028            switch (level) {
10029                case PermissionInfo.PROTECTION_NORMAL: {
10030                    // For all apps normal permissions are install time ones.
10031                    grant = GRANT_INSTALL;
10032                } break;
10033
10034                case PermissionInfo.PROTECTION_DANGEROUS: {
10035                    // If a permission review is required for legacy apps we represent
10036                    // their permissions as always granted runtime ones since we need
10037                    // to keep the review required permission flag per user while an
10038                    // install permission's state is shared across all users.
10039                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10040                        // For legacy apps dangerous permissions are install time ones.
10041                        grant = GRANT_INSTALL;
10042                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10043                        // For legacy apps that became modern, install becomes runtime.
10044                        grant = GRANT_UPGRADE;
10045                    } else if (mPromoteSystemApps
10046                            && isSystemApp(ps)
10047                            && mExistingSystemPackages.contains(ps.name)) {
10048                        // For legacy system apps, install becomes runtime.
10049                        // We cannot check hasInstallPermission() for system apps since those
10050                        // permissions were granted implicitly and not persisted pre-M.
10051                        grant = GRANT_UPGRADE;
10052                    } else {
10053                        // For modern apps keep runtime permissions unchanged.
10054                        grant = GRANT_RUNTIME;
10055                    }
10056                } break;
10057
10058                case PermissionInfo.PROTECTION_SIGNATURE: {
10059                    // For all apps signature permissions are install time ones.
10060                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10061                    if (allowedSig) {
10062                        grant = GRANT_INSTALL;
10063                    }
10064                } break;
10065            }
10066
10067            if (DEBUG_INSTALL) {
10068                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10069            }
10070
10071            if (grant != GRANT_DENIED) {
10072                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10073                    // If this is an existing, non-system package, then
10074                    // we can't add any new permissions to it.
10075                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10076                        // Except...  if this is a permission that was added
10077                        // to the platform (note: need to only do this when
10078                        // updating the platform).
10079                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10080                            grant = GRANT_DENIED;
10081                        }
10082                    }
10083                }
10084
10085                switch (grant) {
10086                    case GRANT_INSTALL: {
10087                        // Revoke this as runtime permission to handle the case of
10088                        // a runtime permission being downgraded to an install one.
10089                        // Also in permission review mode we keep dangerous permissions
10090                        // for legacy apps
10091                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10092                            if (origPermissions.getRuntimePermissionState(
10093                                    bp.name, userId) != null) {
10094                                // Revoke the runtime permission and clear the flags.
10095                                origPermissions.revokeRuntimePermission(bp, userId);
10096                                origPermissions.updatePermissionFlags(bp, userId,
10097                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10098                                // If we revoked a permission permission, we have to write.
10099                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10100                                        changedRuntimePermissionUserIds, userId);
10101                            }
10102                        }
10103                        // Grant an install permission.
10104                        if (permissionsState.grantInstallPermission(bp) !=
10105                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10106                            changedInstallPermission = true;
10107                        }
10108                    } break;
10109
10110                    case GRANT_RUNTIME: {
10111                        // Grant previously granted runtime permissions.
10112                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10113                            PermissionState permissionState = origPermissions
10114                                    .getRuntimePermissionState(bp.name, userId);
10115                            int flags = permissionState != null
10116                                    ? permissionState.getFlags() : 0;
10117                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10118                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10119                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10120                                    // If we cannot put the permission as it was, we have to write.
10121                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10122                                            changedRuntimePermissionUserIds, userId);
10123                                }
10124                                // If the app supports runtime permissions no need for a review.
10125                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10126                                        && appSupportsRuntimePermissions
10127                                        && (flags & PackageManager
10128                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10129                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10130                                    // Since we changed the flags, we have to write.
10131                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10132                                            changedRuntimePermissionUserIds, userId);
10133                                }
10134                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10135                                    && !appSupportsRuntimePermissions) {
10136                                // For legacy apps that need a permission review, every new
10137                                // runtime permission is granted but it is pending a review.
10138                                // We also need to review only platform defined runtime
10139                                // permissions as these are the only ones the platform knows
10140                                // how to disable the API to simulate revocation as legacy
10141                                // apps don't expect to run with revoked permissions.
10142                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10143                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10144                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10145                                        // We changed the flags, hence have to write.
10146                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10147                                                changedRuntimePermissionUserIds, userId);
10148                                    }
10149                                }
10150                                if (permissionsState.grantRuntimePermission(bp, userId)
10151                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10152                                    // We changed the permission, hence have to write.
10153                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10154                                            changedRuntimePermissionUserIds, userId);
10155                                }
10156                            }
10157                            // Propagate the permission flags.
10158                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10159                        }
10160                    } break;
10161
10162                    case GRANT_UPGRADE: {
10163                        // Grant runtime permissions for a previously held install permission.
10164                        PermissionState permissionState = origPermissions
10165                                .getInstallPermissionState(bp.name);
10166                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10167
10168                        if (origPermissions.revokeInstallPermission(bp)
10169                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10170                            // We will be transferring the permission flags, so clear them.
10171                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10172                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10173                            changedInstallPermission = true;
10174                        }
10175
10176                        // If the permission is not to be promoted to runtime we ignore it and
10177                        // also its other flags as they are not applicable to install permissions.
10178                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10179                            for (int userId : currentUserIds) {
10180                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10181                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10182                                    // Transfer the permission flags.
10183                                    permissionsState.updatePermissionFlags(bp, userId,
10184                                            flags, flags);
10185                                    // If we granted the permission, we have to write.
10186                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10187                                            changedRuntimePermissionUserIds, userId);
10188                                }
10189                            }
10190                        }
10191                    } break;
10192
10193                    default: {
10194                        if (packageOfInterest == null
10195                                || packageOfInterest.equals(pkg.packageName)) {
10196                            Slog.w(TAG, "Not granting permission " + perm
10197                                    + " to package " + pkg.packageName
10198                                    + " because it was previously installed without");
10199                        }
10200                    } break;
10201                }
10202            } else {
10203                if (permissionsState.revokeInstallPermission(bp) !=
10204                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10205                    // Also drop the permission flags.
10206                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10207                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10208                    changedInstallPermission = true;
10209                    Slog.i(TAG, "Un-granting permission " + perm
10210                            + " from package " + pkg.packageName
10211                            + " (protectionLevel=" + bp.protectionLevel
10212                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10213                            + ")");
10214                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10215                    // Don't print warning for app op permissions, since it is fine for them
10216                    // not to be granted, there is a UI for the user to decide.
10217                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10218                        Slog.w(TAG, "Not granting permission " + perm
10219                                + " to package " + pkg.packageName
10220                                + " (protectionLevel=" + bp.protectionLevel
10221                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10222                                + ")");
10223                    }
10224                }
10225            }
10226        }
10227
10228        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10229                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10230            // This is the first that we have heard about this package, so the
10231            // permissions we have now selected are fixed until explicitly
10232            // changed.
10233            ps.installPermissionsFixed = true;
10234        }
10235
10236        // Persist the runtime permissions state for users with changes. If permissions
10237        // were revoked because no app in the shared user declares them we have to
10238        // write synchronously to avoid losing runtime permissions state.
10239        for (int userId : changedRuntimePermissionUserIds) {
10240            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10241        }
10242
10243        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10244    }
10245
10246    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10247        boolean allowed = false;
10248        final int NP = PackageParser.NEW_PERMISSIONS.length;
10249        for (int ip=0; ip<NP; ip++) {
10250            final PackageParser.NewPermissionInfo npi
10251                    = PackageParser.NEW_PERMISSIONS[ip];
10252            if (npi.name.equals(perm)
10253                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10254                allowed = true;
10255                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10256                        + pkg.packageName);
10257                break;
10258            }
10259        }
10260        return allowed;
10261    }
10262
10263    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10264            BasePermission bp, PermissionsState origPermissions) {
10265        boolean allowed;
10266        allowed = (compareSignatures(
10267                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10268                        == PackageManager.SIGNATURE_MATCH)
10269                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10270                        == PackageManager.SIGNATURE_MATCH);
10271        if (!allowed && (bp.protectionLevel
10272                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10273            if (isSystemApp(pkg)) {
10274                // For updated system applications, a system permission
10275                // is granted only if it had been defined by the original application.
10276                if (pkg.isUpdatedSystemApp()) {
10277                    final PackageSetting sysPs = mSettings
10278                            .getDisabledSystemPkgLPr(pkg.packageName);
10279                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10280                        // If the original was granted this permission, we take
10281                        // that grant decision as read and propagate it to the
10282                        // update.
10283                        if (sysPs.isPrivileged()) {
10284                            allowed = true;
10285                        }
10286                    } else {
10287                        // The system apk may have been updated with an older
10288                        // version of the one on the data partition, but which
10289                        // granted a new system permission that it didn't have
10290                        // before.  In this case we do want to allow the app to
10291                        // now get the new permission if the ancestral apk is
10292                        // privileged to get it.
10293                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10294                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10295                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10296                                    allowed = true;
10297                                    break;
10298                                }
10299                            }
10300                        }
10301                        // Also if a privileged parent package on the system image or any of
10302                        // its children requested a privileged permission, the updated child
10303                        // packages can also get the permission.
10304                        if (pkg.parentPackage != null) {
10305                            final PackageSetting disabledSysParentPs = mSettings
10306                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10307                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10308                                    && disabledSysParentPs.isPrivileged()) {
10309                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10310                                    allowed = true;
10311                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10312                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10313                                    for (int i = 0; i < count; i++) {
10314                                        PackageParser.Package disabledSysChildPkg =
10315                                                disabledSysParentPs.pkg.childPackages.get(i);
10316                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10317                                                perm)) {
10318                                            allowed = true;
10319                                            break;
10320                                        }
10321                                    }
10322                                }
10323                            }
10324                        }
10325                    }
10326                } else {
10327                    allowed = isPrivilegedApp(pkg);
10328                }
10329            }
10330        }
10331        if (!allowed) {
10332            if (!allowed && (bp.protectionLevel
10333                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10334                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10335                // If this was a previously normal/dangerous permission that got moved
10336                // to a system permission as part of the runtime permission redesign, then
10337                // we still want to blindly grant it to old apps.
10338                allowed = true;
10339            }
10340            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10341                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10342                // If this permission is to be granted to the system installer and
10343                // this app is an installer, then it gets the permission.
10344                allowed = true;
10345            }
10346            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10347                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10348                // If this permission is to be granted to the system verifier and
10349                // this app is a verifier, then it gets the permission.
10350                allowed = true;
10351            }
10352            if (!allowed && (bp.protectionLevel
10353                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10354                    && isSystemApp(pkg)) {
10355                // Any pre-installed system app is allowed to get this permission.
10356                allowed = true;
10357            }
10358            if (!allowed && (bp.protectionLevel
10359                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10360                // For development permissions, a development permission
10361                // is granted only if it was already granted.
10362                allowed = origPermissions.hasInstallPermission(perm);
10363            }
10364            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10365                    && pkg.packageName.equals(mSetupWizardPackage)) {
10366                // If this permission is to be granted to the system setup wizard and
10367                // this app is a setup wizard, then it gets the permission.
10368                allowed = true;
10369            }
10370        }
10371        return allowed;
10372    }
10373
10374    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10375        final int permCount = pkg.requestedPermissions.size();
10376        for (int j = 0; j < permCount; j++) {
10377            String requestedPermission = pkg.requestedPermissions.get(j);
10378            if (permission.equals(requestedPermission)) {
10379                return true;
10380            }
10381        }
10382        return false;
10383    }
10384
10385    final class ActivityIntentResolver
10386            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10387        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10388                boolean defaultOnly, int userId) {
10389            if (!sUserManager.exists(userId)) return null;
10390            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10391            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10392        }
10393
10394        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10395                int userId) {
10396            if (!sUserManager.exists(userId)) return null;
10397            mFlags = flags;
10398            return super.queryIntent(intent, resolvedType,
10399                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10400        }
10401
10402        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10403                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10404            if (!sUserManager.exists(userId)) return null;
10405            if (packageActivities == null) {
10406                return null;
10407            }
10408            mFlags = flags;
10409            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10410            final int N = packageActivities.size();
10411            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10412                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10413
10414            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10415            for (int i = 0; i < N; ++i) {
10416                intentFilters = packageActivities.get(i).intents;
10417                if (intentFilters != null && intentFilters.size() > 0) {
10418                    PackageParser.ActivityIntentInfo[] array =
10419                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10420                    intentFilters.toArray(array);
10421                    listCut.add(array);
10422                }
10423            }
10424            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10425        }
10426
10427        /**
10428         * Finds a privileged activity that matches the specified activity names.
10429         */
10430        private PackageParser.Activity findMatchingActivity(
10431                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10432            for (PackageParser.Activity sysActivity : activityList) {
10433                if (sysActivity.info.name.equals(activityInfo.name)) {
10434                    return sysActivity;
10435                }
10436                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10437                    return sysActivity;
10438                }
10439                if (sysActivity.info.targetActivity != null) {
10440                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10441                        return sysActivity;
10442                    }
10443                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10444                        return sysActivity;
10445                    }
10446                }
10447            }
10448            return null;
10449        }
10450
10451        public class IterGenerator<E> {
10452            public Iterator<E> generate(ActivityIntentInfo info) {
10453                return null;
10454            }
10455        }
10456
10457        public class ActionIterGenerator extends IterGenerator<String> {
10458            @Override
10459            public Iterator<String> generate(ActivityIntentInfo info) {
10460                return info.actionsIterator();
10461            }
10462        }
10463
10464        public class CategoriesIterGenerator extends IterGenerator<String> {
10465            @Override
10466            public Iterator<String> generate(ActivityIntentInfo info) {
10467                return info.categoriesIterator();
10468            }
10469        }
10470
10471        public class SchemesIterGenerator extends IterGenerator<String> {
10472            @Override
10473            public Iterator<String> generate(ActivityIntentInfo info) {
10474                return info.schemesIterator();
10475            }
10476        }
10477
10478        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10479            @Override
10480            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10481                return info.authoritiesIterator();
10482            }
10483        }
10484
10485        /**
10486         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10487         * MODIFIED. Do not pass in a list that should not be changed.
10488         */
10489        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10490                IterGenerator<T> generator, Iterator<T> searchIterator) {
10491            // loop through the set of actions; every one must be found in the intent filter
10492            while (searchIterator.hasNext()) {
10493                // we must have at least one filter in the list to consider a match
10494                if (intentList.size() == 0) {
10495                    break;
10496                }
10497
10498                final T searchAction = searchIterator.next();
10499
10500                // loop through the set of intent filters
10501                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10502                while (intentIter.hasNext()) {
10503                    final ActivityIntentInfo intentInfo = intentIter.next();
10504                    boolean selectionFound = false;
10505
10506                    // loop through the intent filter's selection criteria; at least one
10507                    // of them must match the searched criteria
10508                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10509                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10510                        final T intentSelection = intentSelectionIter.next();
10511                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10512                            selectionFound = true;
10513                            break;
10514                        }
10515                    }
10516
10517                    // the selection criteria wasn't found in this filter's set; this filter
10518                    // is not a potential match
10519                    if (!selectionFound) {
10520                        intentIter.remove();
10521                    }
10522                }
10523            }
10524        }
10525
10526        private boolean isProtectedAction(ActivityIntentInfo filter) {
10527            final Iterator<String> actionsIter = filter.actionsIterator();
10528            while (actionsIter != null && actionsIter.hasNext()) {
10529                final String filterAction = actionsIter.next();
10530                if (PROTECTED_ACTIONS.contains(filterAction)) {
10531                    return true;
10532                }
10533            }
10534            return false;
10535        }
10536
10537        /**
10538         * Adjusts the priority of the given intent filter according to policy.
10539         * <p>
10540         * <ul>
10541         * <li>The priority for non privileged applications is capped to '0'</li>
10542         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10543         * <li>The priority for unbundled updates to privileged applications is capped to the
10544         *      priority defined on the system partition</li>
10545         * </ul>
10546         * <p>
10547         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10548         * allowed to obtain any priority on any action.
10549         */
10550        private void adjustPriority(
10551                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10552            // nothing to do; priority is fine as-is
10553            if (intent.getPriority() <= 0) {
10554                return;
10555            }
10556
10557            final ActivityInfo activityInfo = intent.activity.info;
10558            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10559
10560            final boolean privilegedApp =
10561                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10562            if (!privilegedApp) {
10563                // non-privileged applications can never define a priority >0
10564                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10565                        + " package: " + applicationInfo.packageName
10566                        + " activity: " + intent.activity.className
10567                        + " origPrio: " + intent.getPriority());
10568                intent.setPriority(0);
10569                return;
10570            }
10571
10572            if (systemActivities == null) {
10573                // the system package is not disabled; we're parsing the system partition
10574                if (isProtectedAction(intent)) {
10575                    if (mDeferProtectedFilters) {
10576                        // We can't deal with these just yet. No component should ever obtain a
10577                        // >0 priority for a protected actions, with ONE exception -- the setup
10578                        // wizard. The setup wizard, however, cannot be known until we're able to
10579                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10580                        // until all intent filters have been processed. Chicken, meet egg.
10581                        // Let the filter temporarily have a high priority and rectify the
10582                        // priorities after all system packages have been scanned.
10583                        mProtectedFilters.add(intent);
10584                        if (DEBUG_FILTERS) {
10585                            Slog.i(TAG, "Protected action; save for later;"
10586                                    + " package: " + applicationInfo.packageName
10587                                    + " activity: " + intent.activity.className
10588                                    + " origPrio: " + intent.getPriority());
10589                        }
10590                        return;
10591                    } else {
10592                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10593                            Slog.i(TAG, "No setup wizard;"
10594                                + " All protected intents capped to priority 0");
10595                        }
10596                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10597                            if (DEBUG_FILTERS) {
10598                                Slog.i(TAG, "Found setup wizard;"
10599                                    + " allow priority " + intent.getPriority() + ";"
10600                                    + " package: " + intent.activity.info.packageName
10601                                    + " activity: " + intent.activity.className
10602                                    + " priority: " + intent.getPriority());
10603                            }
10604                            // setup wizard gets whatever it wants
10605                            return;
10606                        }
10607                        Slog.w(TAG, "Protected action; cap priority to 0;"
10608                                + " package: " + intent.activity.info.packageName
10609                                + " activity: " + intent.activity.className
10610                                + " origPrio: " + intent.getPriority());
10611                        intent.setPriority(0);
10612                        return;
10613                    }
10614                }
10615                // privileged apps on the system image get whatever priority they request
10616                return;
10617            }
10618
10619            // privileged app unbundled update ... try to find the same activity
10620            final PackageParser.Activity foundActivity =
10621                    findMatchingActivity(systemActivities, activityInfo);
10622            if (foundActivity == null) {
10623                // this is a new activity; it cannot obtain >0 priority
10624                if (DEBUG_FILTERS) {
10625                    Slog.i(TAG, "New activity; cap priority to 0;"
10626                            + " package: " + applicationInfo.packageName
10627                            + " activity: " + intent.activity.className
10628                            + " origPrio: " + intent.getPriority());
10629                }
10630                intent.setPriority(0);
10631                return;
10632            }
10633
10634            // found activity, now check for filter equivalence
10635
10636            // a shallow copy is enough; we modify the list, not its contents
10637            final List<ActivityIntentInfo> intentListCopy =
10638                    new ArrayList<>(foundActivity.intents);
10639            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10640
10641            // find matching action subsets
10642            final Iterator<String> actionsIterator = intent.actionsIterator();
10643            if (actionsIterator != null) {
10644                getIntentListSubset(
10645                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10646                if (intentListCopy.size() == 0) {
10647                    // no more intents to match; we're not equivalent
10648                    if (DEBUG_FILTERS) {
10649                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10650                                + " package: " + applicationInfo.packageName
10651                                + " activity: " + intent.activity.className
10652                                + " origPrio: " + intent.getPriority());
10653                    }
10654                    intent.setPriority(0);
10655                    return;
10656                }
10657            }
10658
10659            // find matching category subsets
10660            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10661            if (categoriesIterator != null) {
10662                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10663                        categoriesIterator);
10664                if (intentListCopy.size() == 0) {
10665                    // no more intents to match; we're not equivalent
10666                    if (DEBUG_FILTERS) {
10667                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10668                                + " package: " + applicationInfo.packageName
10669                                + " activity: " + intent.activity.className
10670                                + " origPrio: " + intent.getPriority());
10671                    }
10672                    intent.setPriority(0);
10673                    return;
10674                }
10675            }
10676
10677            // find matching schemes subsets
10678            final Iterator<String> schemesIterator = intent.schemesIterator();
10679            if (schemesIterator != null) {
10680                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10681                        schemesIterator);
10682                if (intentListCopy.size() == 0) {
10683                    // no more intents to match; we're not equivalent
10684                    if (DEBUG_FILTERS) {
10685                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10686                                + " package: " + applicationInfo.packageName
10687                                + " activity: " + intent.activity.className
10688                                + " origPrio: " + intent.getPriority());
10689                    }
10690                    intent.setPriority(0);
10691                    return;
10692                }
10693            }
10694
10695            // find matching authorities subsets
10696            final Iterator<IntentFilter.AuthorityEntry>
10697                    authoritiesIterator = intent.authoritiesIterator();
10698            if (authoritiesIterator != null) {
10699                getIntentListSubset(intentListCopy,
10700                        new AuthoritiesIterGenerator(),
10701                        authoritiesIterator);
10702                if (intentListCopy.size() == 0) {
10703                    // no more intents to match; we're not equivalent
10704                    if (DEBUG_FILTERS) {
10705                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10706                                + " package: " + applicationInfo.packageName
10707                                + " activity: " + intent.activity.className
10708                                + " origPrio: " + intent.getPriority());
10709                    }
10710                    intent.setPriority(0);
10711                    return;
10712                }
10713            }
10714
10715            // we found matching filter(s); app gets the max priority of all intents
10716            int cappedPriority = 0;
10717            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10718                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10719            }
10720            if (intent.getPriority() > cappedPriority) {
10721                if (DEBUG_FILTERS) {
10722                    Slog.i(TAG, "Found matching filter(s);"
10723                            + " cap priority to " + cappedPriority + ";"
10724                            + " package: " + applicationInfo.packageName
10725                            + " activity: " + intent.activity.className
10726                            + " origPrio: " + intent.getPriority());
10727                }
10728                intent.setPriority(cappedPriority);
10729                return;
10730            }
10731            // all this for nothing; the requested priority was <= what was on the system
10732        }
10733
10734        public final void addActivity(PackageParser.Activity a, String type) {
10735            mActivities.put(a.getComponentName(), a);
10736            if (DEBUG_SHOW_INFO)
10737                Log.v(
10738                TAG, "  " + type + " " +
10739                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10740            if (DEBUG_SHOW_INFO)
10741                Log.v(TAG, "    Class=" + a.info.name);
10742            final int NI = a.intents.size();
10743            for (int j=0; j<NI; j++) {
10744                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10745                if ("activity".equals(type)) {
10746                    final PackageSetting ps =
10747                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10748                    final List<PackageParser.Activity> systemActivities =
10749                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10750                    adjustPriority(systemActivities, intent);
10751                }
10752                if (DEBUG_SHOW_INFO) {
10753                    Log.v(TAG, "    IntentFilter:");
10754                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10755                }
10756                if (!intent.debugCheck()) {
10757                    Log.w(TAG, "==> For Activity " + a.info.name);
10758                }
10759                addFilter(intent);
10760            }
10761        }
10762
10763        public final void removeActivity(PackageParser.Activity a, String type) {
10764            mActivities.remove(a.getComponentName());
10765            if (DEBUG_SHOW_INFO) {
10766                Log.v(TAG, "  " + type + " "
10767                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10768                                : a.info.name) + ":");
10769                Log.v(TAG, "    Class=" + a.info.name);
10770            }
10771            final int NI = a.intents.size();
10772            for (int j=0; j<NI; j++) {
10773                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10774                if (DEBUG_SHOW_INFO) {
10775                    Log.v(TAG, "    IntentFilter:");
10776                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10777                }
10778                removeFilter(intent);
10779            }
10780        }
10781
10782        @Override
10783        protected boolean allowFilterResult(
10784                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10785            ActivityInfo filterAi = filter.activity.info;
10786            for (int i=dest.size()-1; i>=0; i--) {
10787                ActivityInfo destAi = dest.get(i).activityInfo;
10788                if (destAi.name == filterAi.name
10789                        && destAi.packageName == filterAi.packageName) {
10790                    return false;
10791                }
10792            }
10793            return true;
10794        }
10795
10796        @Override
10797        protected ActivityIntentInfo[] newArray(int size) {
10798            return new ActivityIntentInfo[size];
10799        }
10800
10801        @Override
10802        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10803            if (!sUserManager.exists(userId)) return true;
10804            PackageParser.Package p = filter.activity.owner;
10805            if (p != null) {
10806                PackageSetting ps = (PackageSetting)p.mExtras;
10807                if (ps != null) {
10808                    // System apps are never considered stopped for purposes of
10809                    // filtering, because there may be no way for the user to
10810                    // actually re-launch them.
10811                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10812                            && ps.getStopped(userId);
10813                }
10814            }
10815            return false;
10816        }
10817
10818        @Override
10819        protected boolean isPackageForFilter(String packageName,
10820                PackageParser.ActivityIntentInfo info) {
10821            return packageName.equals(info.activity.owner.packageName);
10822        }
10823
10824        @Override
10825        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10826                int match, int userId) {
10827            if (!sUserManager.exists(userId)) return null;
10828            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10829                return null;
10830            }
10831            final PackageParser.Activity activity = info.activity;
10832            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10833            if (ps == null) {
10834                return null;
10835            }
10836            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10837                    ps.readUserState(userId), userId);
10838            if (ai == null) {
10839                return null;
10840            }
10841            final ResolveInfo res = new ResolveInfo();
10842            res.activityInfo = ai;
10843            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10844                res.filter = info;
10845            }
10846            if (info != null) {
10847                res.handleAllWebDataURI = info.handleAllWebDataURI();
10848            }
10849            res.priority = info.getPriority();
10850            res.preferredOrder = activity.owner.mPreferredOrder;
10851            //System.out.println("Result: " + res.activityInfo.className +
10852            //                   " = " + res.priority);
10853            res.match = match;
10854            res.isDefault = info.hasDefault;
10855            res.labelRes = info.labelRes;
10856            res.nonLocalizedLabel = info.nonLocalizedLabel;
10857            if (userNeedsBadging(userId)) {
10858                res.noResourceId = true;
10859            } else {
10860                res.icon = info.icon;
10861            }
10862            res.iconResourceId = info.icon;
10863            res.system = res.activityInfo.applicationInfo.isSystemApp();
10864            return res;
10865        }
10866
10867        @Override
10868        protected void sortResults(List<ResolveInfo> results) {
10869            Collections.sort(results, mResolvePrioritySorter);
10870        }
10871
10872        @Override
10873        protected void dumpFilter(PrintWriter out, String prefix,
10874                PackageParser.ActivityIntentInfo filter) {
10875            out.print(prefix); out.print(
10876                    Integer.toHexString(System.identityHashCode(filter.activity)));
10877                    out.print(' ');
10878                    filter.activity.printComponentShortName(out);
10879                    out.print(" filter ");
10880                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10881        }
10882
10883        @Override
10884        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10885            return filter.activity;
10886        }
10887
10888        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10889            PackageParser.Activity activity = (PackageParser.Activity)label;
10890            out.print(prefix); out.print(
10891                    Integer.toHexString(System.identityHashCode(activity)));
10892                    out.print(' ');
10893                    activity.printComponentShortName(out);
10894            if (count > 1) {
10895                out.print(" ("); out.print(count); out.print(" filters)");
10896            }
10897            out.println();
10898        }
10899
10900        // Keys are String (activity class name), values are Activity.
10901        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10902                = new ArrayMap<ComponentName, PackageParser.Activity>();
10903        private int mFlags;
10904    }
10905
10906    private final class ServiceIntentResolver
10907            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10908        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10909                boolean defaultOnly, int userId) {
10910            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10911            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10912        }
10913
10914        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10915                int userId) {
10916            if (!sUserManager.exists(userId)) return null;
10917            mFlags = flags;
10918            return super.queryIntent(intent, resolvedType,
10919                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10920        }
10921
10922        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10923                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10924            if (!sUserManager.exists(userId)) return null;
10925            if (packageServices == null) {
10926                return null;
10927            }
10928            mFlags = flags;
10929            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10930            final int N = packageServices.size();
10931            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10932                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10933
10934            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10935            for (int i = 0; i < N; ++i) {
10936                intentFilters = packageServices.get(i).intents;
10937                if (intentFilters != null && intentFilters.size() > 0) {
10938                    PackageParser.ServiceIntentInfo[] array =
10939                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10940                    intentFilters.toArray(array);
10941                    listCut.add(array);
10942                }
10943            }
10944            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10945        }
10946
10947        public final void addService(PackageParser.Service s) {
10948            mServices.put(s.getComponentName(), s);
10949            if (DEBUG_SHOW_INFO) {
10950                Log.v(TAG, "  "
10951                        + (s.info.nonLocalizedLabel != null
10952                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10953                Log.v(TAG, "    Class=" + s.info.name);
10954            }
10955            final int NI = s.intents.size();
10956            int j;
10957            for (j=0; j<NI; j++) {
10958                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10959                if (DEBUG_SHOW_INFO) {
10960                    Log.v(TAG, "    IntentFilter:");
10961                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10962                }
10963                if (!intent.debugCheck()) {
10964                    Log.w(TAG, "==> For Service " + s.info.name);
10965                }
10966                addFilter(intent);
10967            }
10968        }
10969
10970        public final void removeService(PackageParser.Service s) {
10971            mServices.remove(s.getComponentName());
10972            if (DEBUG_SHOW_INFO) {
10973                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10974                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10975                Log.v(TAG, "    Class=" + s.info.name);
10976            }
10977            final int NI = s.intents.size();
10978            int j;
10979            for (j=0; j<NI; j++) {
10980                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10981                if (DEBUG_SHOW_INFO) {
10982                    Log.v(TAG, "    IntentFilter:");
10983                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10984                }
10985                removeFilter(intent);
10986            }
10987        }
10988
10989        @Override
10990        protected boolean allowFilterResult(
10991                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10992            ServiceInfo filterSi = filter.service.info;
10993            for (int i=dest.size()-1; i>=0; i--) {
10994                ServiceInfo destAi = dest.get(i).serviceInfo;
10995                if (destAi.name == filterSi.name
10996                        && destAi.packageName == filterSi.packageName) {
10997                    return false;
10998                }
10999            }
11000            return true;
11001        }
11002
11003        @Override
11004        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11005            return new PackageParser.ServiceIntentInfo[size];
11006        }
11007
11008        @Override
11009        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11010            if (!sUserManager.exists(userId)) return true;
11011            PackageParser.Package p = filter.service.owner;
11012            if (p != null) {
11013                PackageSetting ps = (PackageSetting)p.mExtras;
11014                if (ps != null) {
11015                    // System apps are never considered stopped for purposes of
11016                    // filtering, because there may be no way for the user to
11017                    // actually re-launch them.
11018                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11019                            && ps.getStopped(userId);
11020                }
11021            }
11022            return false;
11023        }
11024
11025        @Override
11026        protected boolean isPackageForFilter(String packageName,
11027                PackageParser.ServiceIntentInfo info) {
11028            return packageName.equals(info.service.owner.packageName);
11029        }
11030
11031        @Override
11032        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11033                int match, int userId) {
11034            if (!sUserManager.exists(userId)) return null;
11035            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11036            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11037                return null;
11038            }
11039            final PackageParser.Service service = info.service;
11040            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11041            if (ps == null) {
11042                return null;
11043            }
11044            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11045                    ps.readUserState(userId), userId);
11046            if (si == null) {
11047                return null;
11048            }
11049            final ResolveInfo res = new ResolveInfo();
11050            res.serviceInfo = si;
11051            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11052                res.filter = filter;
11053            }
11054            res.priority = info.getPriority();
11055            res.preferredOrder = service.owner.mPreferredOrder;
11056            res.match = match;
11057            res.isDefault = info.hasDefault;
11058            res.labelRes = info.labelRes;
11059            res.nonLocalizedLabel = info.nonLocalizedLabel;
11060            res.icon = info.icon;
11061            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11062            return res;
11063        }
11064
11065        @Override
11066        protected void sortResults(List<ResolveInfo> results) {
11067            Collections.sort(results, mResolvePrioritySorter);
11068        }
11069
11070        @Override
11071        protected void dumpFilter(PrintWriter out, String prefix,
11072                PackageParser.ServiceIntentInfo filter) {
11073            out.print(prefix); out.print(
11074                    Integer.toHexString(System.identityHashCode(filter.service)));
11075                    out.print(' ');
11076                    filter.service.printComponentShortName(out);
11077                    out.print(" filter ");
11078                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11079        }
11080
11081        @Override
11082        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11083            return filter.service;
11084        }
11085
11086        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11087            PackageParser.Service service = (PackageParser.Service)label;
11088            out.print(prefix); out.print(
11089                    Integer.toHexString(System.identityHashCode(service)));
11090                    out.print(' ');
11091                    service.printComponentShortName(out);
11092            if (count > 1) {
11093                out.print(" ("); out.print(count); out.print(" filters)");
11094            }
11095            out.println();
11096        }
11097
11098//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11099//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11100//            final List<ResolveInfo> retList = Lists.newArrayList();
11101//            while (i.hasNext()) {
11102//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11103//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11104//                    retList.add(resolveInfo);
11105//                }
11106//            }
11107//            return retList;
11108//        }
11109
11110        // Keys are String (activity class name), values are Activity.
11111        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11112                = new ArrayMap<ComponentName, PackageParser.Service>();
11113        private int mFlags;
11114    };
11115
11116    private final class ProviderIntentResolver
11117            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11118        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11119                boolean defaultOnly, int userId) {
11120            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11121            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11122        }
11123
11124        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11125                int userId) {
11126            if (!sUserManager.exists(userId))
11127                return null;
11128            mFlags = flags;
11129            return super.queryIntent(intent, resolvedType,
11130                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11131        }
11132
11133        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11134                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11135            if (!sUserManager.exists(userId))
11136                return null;
11137            if (packageProviders == null) {
11138                return null;
11139            }
11140            mFlags = flags;
11141            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11142            final int N = packageProviders.size();
11143            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11144                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11145
11146            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11147            for (int i = 0; i < N; ++i) {
11148                intentFilters = packageProviders.get(i).intents;
11149                if (intentFilters != null && intentFilters.size() > 0) {
11150                    PackageParser.ProviderIntentInfo[] array =
11151                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11152                    intentFilters.toArray(array);
11153                    listCut.add(array);
11154                }
11155            }
11156            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11157        }
11158
11159        public final void addProvider(PackageParser.Provider p) {
11160            if (mProviders.containsKey(p.getComponentName())) {
11161                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11162                return;
11163            }
11164
11165            mProviders.put(p.getComponentName(), p);
11166            if (DEBUG_SHOW_INFO) {
11167                Log.v(TAG, "  "
11168                        + (p.info.nonLocalizedLabel != null
11169                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11170                Log.v(TAG, "    Class=" + p.info.name);
11171            }
11172            final int NI = p.intents.size();
11173            int j;
11174            for (j = 0; j < NI; j++) {
11175                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11176                if (DEBUG_SHOW_INFO) {
11177                    Log.v(TAG, "    IntentFilter:");
11178                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11179                }
11180                if (!intent.debugCheck()) {
11181                    Log.w(TAG, "==> For Provider " + p.info.name);
11182                }
11183                addFilter(intent);
11184            }
11185        }
11186
11187        public final void removeProvider(PackageParser.Provider p) {
11188            mProviders.remove(p.getComponentName());
11189            if (DEBUG_SHOW_INFO) {
11190                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11191                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11192                Log.v(TAG, "    Class=" + p.info.name);
11193            }
11194            final int NI = p.intents.size();
11195            int j;
11196            for (j = 0; j < NI; j++) {
11197                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11198                if (DEBUG_SHOW_INFO) {
11199                    Log.v(TAG, "    IntentFilter:");
11200                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11201                }
11202                removeFilter(intent);
11203            }
11204        }
11205
11206        @Override
11207        protected boolean allowFilterResult(
11208                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11209            ProviderInfo filterPi = filter.provider.info;
11210            for (int i = dest.size() - 1; i >= 0; i--) {
11211                ProviderInfo destPi = dest.get(i).providerInfo;
11212                if (destPi.name == filterPi.name
11213                        && destPi.packageName == filterPi.packageName) {
11214                    return false;
11215                }
11216            }
11217            return true;
11218        }
11219
11220        @Override
11221        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11222            return new PackageParser.ProviderIntentInfo[size];
11223        }
11224
11225        @Override
11226        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11227            if (!sUserManager.exists(userId))
11228                return true;
11229            PackageParser.Package p = filter.provider.owner;
11230            if (p != null) {
11231                PackageSetting ps = (PackageSetting) p.mExtras;
11232                if (ps != null) {
11233                    // System apps are never considered stopped for purposes of
11234                    // filtering, because there may be no way for the user to
11235                    // actually re-launch them.
11236                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11237                            && ps.getStopped(userId);
11238                }
11239            }
11240            return false;
11241        }
11242
11243        @Override
11244        protected boolean isPackageForFilter(String packageName,
11245                PackageParser.ProviderIntentInfo info) {
11246            return packageName.equals(info.provider.owner.packageName);
11247        }
11248
11249        @Override
11250        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11251                int match, int userId) {
11252            if (!sUserManager.exists(userId))
11253                return null;
11254            final PackageParser.ProviderIntentInfo info = filter;
11255            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11256                return null;
11257            }
11258            final PackageParser.Provider provider = info.provider;
11259            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11260            if (ps == null) {
11261                return null;
11262            }
11263            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11264                    ps.readUserState(userId), userId);
11265            if (pi == null) {
11266                return null;
11267            }
11268            final ResolveInfo res = new ResolveInfo();
11269            res.providerInfo = pi;
11270            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11271                res.filter = filter;
11272            }
11273            res.priority = info.getPriority();
11274            res.preferredOrder = provider.owner.mPreferredOrder;
11275            res.match = match;
11276            res.isDefault = info.hasDefault;
11277            res.labelRes = info.labelRes;
11278            res.nonLocalizedLabel = info.nonLocalizedLabel;
11279            res.icon = info.icon;
11280            res.system = res.providerInfo.applicationInfo.isSystemApp();
11281            return res;
11282        }
11283
11284        @Override
11285        protected void sortResults(List<ResolveInfo> results) {
11286            Collections.sort(results, mResolvePrioritySorter);
11287        }
11288
11289        @Override
11290        protected void dumpFilter(PrintWriter out, String prefix,
11291                PackageParser.ProviderIntentInfo filter) {
11292            out.print(prefix);
11293            out.print(
11294                    Integer.toHexString(System.identityHashCode(filter.provider)));
11295            out.print(' ');
11296            filter.provider.printComponentShortName(out);
11297            out.print(" filter ");
11298            out.println(Integer.toHexString(System.identityHashCode(filter)));
11299        }
11300
11301        @Override
11302        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11303            return filter.provider;
11304        }
11305
11306        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11307            PackageParser.Provider provider = (PackageParser.Provider)label;
11308            out.print(prefix); out.print(
11309                    Integer.toHexString(System.identityHashCode(provider)));
11310                    out.print(' ');
11311                    provider.printComponentShortName(out);
11312            if (count > 1) {
11313                out.print(" ("); out.print(count); out.print(" filters)");
11314            }
11315            out.println();
11316        }
11317
11318        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11319                = new ArrayMap<ComponentName, PackageParser.Provider>();
11320        private int mFlags;
11321    }
11322
11323    private static final class EphemeralIntentResolver
11324            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11325        @Override
11326        protected EphemeralResolveIntentInfo[] newArray(int size) {
11327            return new EphemeralResolveIntentInfo[size];
11328        }
11329
11330        @Override
11331        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11332            return true;
11333        }
11334
11335        @Override
11336        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11337                int userId) {
11338            if (!sUserManager.exists(userId)) {
11339                return null;
11340            }
11341            return info.getEphemeralResolveInfo();
11342        }
11343    }
11344
11345    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11346            new Comparator<ResolveInfo>() {
11347        public int compare(ResolveInfo r1, ResolveInfo r2) {
11348            int v1 = r1.priority;
11349            int v2 = r2.priority;
11350            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11351            if (v1 != v2) {
11352                return (v1 > v2) ? -1 : 1;
11353            }
11354            v1 = r1.preferredOrder;
11355            v2 = r2.preferredOrder;
11356            if (v1 != v2) {
11357                return (v1 > v2) ? -1 : 1;
11358            }
11359            if (r1.isDefault != r2.isDefault) {
11360                return r1.isDefault ? -1 : 1;
11361            }
11362            v1 = r1.match;
11363            v2 = r2.match;
11364            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11365            if (v1 != v2) {
11366                return (v1 > v2) ? -1 : 1;
11367            }
11368            if (r1.system != r2.system) {
11369                return r1.system ? -1 : 1;
11370            }
11371            if (r1.activityInfo != null) {
11372                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11373            }
11374            if (r1.serviceInfo != null) {
11375                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11376            }
11377            if (r1.providerInfo != null) {
11378                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11379            }
11380            return 0;
11381        }
11382    };
11383
11384    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11385            new Comparator<ProviderInfo>() {
11386        public int compare(ProviderInfo p1, ProviderInfo p2) {
11387            final int v1 = p1.initOrder;
11388            final int v2 = p2.initOrder;
11389            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11390        }
11391    };
11392
11393    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11394            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11395            final int[] userIds) {
11396        mHandler.post(new Runnable() {
11397            @Override
11398            public void run() {
11399                try {
11400                    final IActivityManager am = ActivityManagerNative.getDefault();
11401                    if (am == null) return;
11402                    final int[] resolvedUserIds;
11403                    if (userIds == null) {
11404                        resolvedUserIds = am.getRunningUserIds();
11405                    } else {
11406                        resolvedUserIds = userIds;
11407                    }
11408                    for (int id : resolvedUserIds) {
11409                        final Intent intent = new Intent(action,
11410                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11411                        if (extras != null) {
11412                            intent.putExtras(extras);
11413                        }
11414                        if (targetPkg != null) {
11415                            intent.setPackage(targetPkg);
11416                        }
11417                        // Modify the UID when posting to other users
11418                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11419                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11420                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11421                            intent.putExtra(Intent.EXTRA_UID, uid);
11422                        }
11423                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11424                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11425                        if (DEBUG_BROADCASTS) {
11426                            RuntimeException here = new RuntimeException("here");
11427                            here.fillInStackTrace();
11428                            Slog.d(TAG, "Sending to user " + id + ": "
11429                                    + intent.toShortString(false, true, false, false)
11430                                    + " " + intent.getExtras(), here);
11431                        }
11432                        am.broadcastIntent(null, intent, null, finishedReceiver,
11433                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11434                                null, finishedReceiver != null, false, id);
11435                    }
11436                } catch (RemoteException ex) {
11437                }
11438            }
11439        });
11440    }
11441
11442    /**
11443     * Check if the external storage media is available. This is true if there
11444     * is a mounted external storage medium or if the external storage is
11445     * emulated.
11446     */
11447    private boolean isExternalMediaAvailable() {
11448        return mMediaMounted || Environment.isExternalStorageEmulated();
11449    }
11450
11451    @Override
11452    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11453        // writer
11454        synchronized (mPackages) {
11455            if (!isExternalMediaAvailable()) {
11456                // If the external storage is no longer mounted at this point,
11457                // the caller may not have been able to delete all of this
11458                // packages files and can not delete any more.  Bail.
11459                return null;
11460            }
11461            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11462            if (lastPackage != null) {
11463                pkgs.remove(lastPackage);
11464            }
11465            if (pkgs.size() > 0) {
11466                return pkgs.get(0);
11467            }
11468        }
11469        return null;
11470    }
11471
11472    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11473        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11474                userId, andCode ? 1 : 0, packageName);
11475        if (mSystemReady) {
11476            msg.sendToTarget();
11477        } else {
11478            if (mPostSystemReadyMessages == null) {
11479                mPostSystemReadyMessages = new ArrayList<>();
11480            }
11481            mPostSystemReadyMessages.add(msg);
11482        }
11483    }
11484
11485    void startCleaningPackages() {
11486        // reader
11487        if (!isExternalMediaAvailable()) {
11488            return;
11489        }
11490        synchronized (mPackages) {
11491            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11492                return;
11493            }
11494        }
11495        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11496        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11497        IActivityManager am = ActivityManagerNative.getDefault();
11498        if (am != null) {
11499            try {
11500                am.startService(null, intent, null, mContext.getOpPackageName(),
11501                        UserHandle.USER_SYSTEM);
11502            } catch (RemoteException e) {
11503            }
11504        }
11505    }
11506
11507    @Override
11508    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11509            int installFlags, String installerPackageName, int userId) {
11510        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11511
11512        final int callingUid = Binder.getCallingUid();
11513        enforceCrossUserPermission(callingUid, userId,
11514                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11515
11516        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11517            try {
11518                if (observer != null) {
11519                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11520                }
11521            } catch (RemoteException re) {
11522            }
11523            return;
11524        }
11525
11526        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11527            installFlags |= PackageManager.INSTALL_FROM_ADB;
11528
11529        } else {
11530            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11531            // about installerPackageName.
11532
11533            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11534            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11535        }
11536
11537        UserHandle user;
11538        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11539            user = UserHandle.ALL;
11540        } else {
11541            user = new UserHandle(userId);
11542        }
11543
11544        // Only system components can circumvent runtime permissions when installing.
11545        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11546                && mContext.checkCallingOrSelfPermission(Manifest.permission
11547                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11548            throw new SecurityException("You need the "
11549                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11550                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11551        }
11552
11553        final File originFile = new File(originPath);
11554        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11555
11556        final Message msg = mHandler.obtainMessage(INIT_COPY);
11557        final VerificationInfo verificationInfo = new VerificationInfo(
11558                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11559        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11560                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11561                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11562                null /*certificates*/);
11563        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11564        msg.obj = params;
11565
11566        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11567                System.identityHashCode(msg.obj));
11568        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11569                System.identityHashCode(msg.obj));
11570
11571        mHandler.sendMessage(msg);
11572    }
11573
11574    void installStage(String packageName, File stagedDir, String stagedCid,
11575            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11576            String installerPackageName, int installerUid, UserHandle user,
11577            Certificate[][] certificates) {
11578        if (DEBUG_EPHEMERAL) {
11579            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11580                Slog.d(TAG, "Ephemeral install of " + packageName);
11581            }
11582        }
11583        final VerificationInfo verificationInfo = new VerificationInfo(
11584                sessionParams.originatingUri, sessionParams.referrerUri,
11585                sessionParams.originatingUid, installerUid);
11586
11587        final OriginInfo origin;
11588        if (stagedDir != null) {
11589            origin = OriginInfo.fromStagedFile(stagedDir);
11590        } else {
11591            origin = OriginInfo.fromStagedContainer(stagedCid);
11592        }
11593
11594        final Message msg = mHandler.obtainMessage(INIT_COPY);
11595        final InstallParams params = new InstallParams(origin, null, observer,
11596                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11597                verificationInfo, user, sessionParams.abiOverride,
11598                sessionParams.grantedRuntimePermissions, certificates);
11599        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11600        msg.obj = params;
11601
11602        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11603                System.identityHashCode(msg.obj));
11604        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11605                System.identityHashCode(msg.obj));
11606
11607        mHandler.sendMessage(msg);
11608    }
11609
11610    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11611            int userId) {
11612        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11613        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11614    }
11615
11616    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11617            int appId, int userId) {
11618        Bundle extras = new Bundle(1);
11619        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11620
11621        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11622                packageName, extras, 0, null, null, new int[] {userId});
11623        try {
11624            IActivityManager am = ActivityManagerNative.getDefault();
11625            if (isSystem && am.isUserRunning(userId, 0)) {
11626                // The just-installed/enabled app is bundled on the system, so presumed
11627                // to be able to run automatically without needing an explicit launch.
11628                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11629                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11630                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11631                        .setPackage(packageName);
11632                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11633                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11634            }
11635        } catch (RemoteException e) {
11636            // shouldn't happen
11637            Slog.w(TAG, "Unable to bootstrap installed package", e);
11638        }
11639    }
11640
11641    @Override
11642    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11643            int userId) {
11644        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11645        PackageSetting pkgSetting;
11646        final int uid = Binder.getCallingUid();
11647        enforceCrossUserPermission(uid, userId,
11648                true /* requireFullPermission */, true /* checkShell */,
11649                "setApplicationHiddenSetting for user " + userId);
11650
11651        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11652            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11653            return false;
11654        }
11655
11656        long callingId = Binder.clearCallingIdentity();
11657        try {
11658            boolean sendAdded = false;
11659            boolean sendRemoved = false;
11660            // writer
11661            synchronized (mPackages) {
11662                pkgSetting = mSettings.mPackages.get(packageName);
11663                if (pkgSetting == null) {
11664                    return false;
11665                }
11666                // Only allow protected packages to hide themselves.
11667                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11668                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11669                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11670                    return false;
11671                }
11672                if (pkgSetting.getHidden(userId) != hidden) {
11673                    pkgSetting.setHidden(hidden, userId);
11674                    mSettings.writePackageRestrictionsLPr(userId);
11675                    if (hidden) {
11676                        sendRemoved = true;
11677                    } else {
11678                        sendAdded = true;
11679                    }
11680                }
11681            }
11682            if (sendAdded) {
11683                sendPackageAddedForUser(packageName, pkgSetting, userId);
11684                return true;
11685            }
11686            if (sendRemoved) {
11687                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11688                        "hiding pkg");
11689                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11690                return true;
11691            }
11692        } finally {
11693            Binder.restoreCallingIdentity(callingId);
11694        }
11695        return false;
11696    }
11697
11698    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11699            int userId) {
11700        final PackageRemovedInfo info = new PackageRemovedInfo();
11701        info.removedPackage = packageName;
11702        info.removedUsers = new int[] {userId};
11703        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11704        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11705    }
11706
11707    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11708        if (pkgList.length > 0) {
11709            Bundle extras = new Bundle(1);
11710            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11711
11712            sendPackageBroadcast(
11713                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11714                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11715                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11716                    new int[] {userId});
11717        }
11718    }
11719
11720    /**
11721     * Returns true if application is not found or there was an error. Otherwise it returns
11722     * the hidden state of the package for the given user.
11723     */
11724    @Override
11725    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11726        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11727        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11728                true /* requireFullPermission */, false /* checkShell */,
11729                "getApplicationHidden for user " + userId);
11730        PackageSetting pkgSetting;
11731        long callingId = Binder.clearCallingIdentity();
11732        try {
11733            // writer
11734            synchronized (mPackages) {
11735                pkgSetting = mSettings.mPackages.get(packageName);
11736                if (pkgSetting == null) {
11737                    return true;
11738                }
11739                return pkgSetting.getHidden(userId);
11740            }
11741        } finally {
11742            Binder.restoreCallingIdentity(callingId);
11743        }
11744    }
11745
11746    /**
11747     * @hide
11748     */
11749    @Override
11750    public int installExistingPackageAsUser(String packageName, int userId) {
11751        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11752                null);
11753        PackageSetting pkgSetting;
11754        final int uid = Binder.getCallingUid();
11755        enforceCrossUserPermission(uid, userId,
11756                true /* requireFullPermission */, true /* checkShell */,
11757                "installExistingPackage for user " + userId);
11758        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11759            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11760        }
11761
11762        long callingId = Binder.clearCallingIdentity();
11763        try {
11764            boolean installed = false;
11765
11766            // writer
11767            synchronized (mPackages) {
11768                pkgSetting = mSettings.mPackages.get(packageName);
11769                if (pkgSetting == null) {
11770                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11771                }
11772                if (!pkgSetting.getInstalled(userId)) {
11773                    pkgSetting.setInstalled(true, userId);
11774                    pkgSetting.setHidden(false, userId);
11775                    mSettings.writePackageRestrictionsLPr(userId);
11776                    installed = true;
11777                }
11778            }
11779
11780            if (installed) {
11781                if (pkgSetting.pkg != null) {
11782                    synchronized (mInstallLock) {
11783                        // We don't need to freeze for a brand new install
11784                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11785                    }
11786                }
11787                sendPackageAddedForUser(packageName, pkgSetting, userId);
11788            }
11789        } finally {
11790            Binder.restoreCallingIdentity(callingId);
11791        }
11792
11793        return PackageManager.INSTALL_SUCCEEDED;
11794    }
11795
11796    boolean isUserRestricted(int userId, String restrictionKey) {
11797        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11798        if (restrictions.getBoolean(restrictionKey, false)) {
11799            Log.w(TAG, "User is restricted: " + restrictionKey);
11800            return true;
11801        }
11802        return false;
11803    }
11804
11805    @Override
11806    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11807            int userId) {
11808        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11809        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11810                true /* requireFullPermission */, true /* checkShell */,
11811                "setPackagesSuspended for user " + userId);
11812
11813        if (ArrayUtils.isEmpty(packageNames)) {
11814            return packageNames;
11815        }
11816
11817        // List of package names for whom the suspended state has changed.
11818        List<String> changedPackages = new ArrayList<>(packageNames.length);
11819        // List of package names for whom the suspended state is not set as requested in this
11820        // method.
11821        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11822        long callingId = Binder.clearCallingIdentity();
11823        try {
11824            for (int i = 0; i < packageNames.length; i++) {
11825                String packageName = packageNames[i];
11826                boolean changed = false;
11827                final int appId;
11828                synchronized (mPackages) {
11829                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11830                    if (pkgSetting == null) {
11831                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11832                                + "\". Skipping suspending/un-suspending.");
11833                        unactionedPackages.add(packageName);
11834                        continue;
11835                    }
11836                    appId = pkgSetting.appId;
11837                    if (pkgSetting.getSuspended(userId) != suspended) {
11838                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11839                            unactionedPackages.add(packageName);
11840                            continue;
11841                        }
11842                        pkgSetting.setSuspended(suspended, userId);
11843                        mSettings.writePackageRestrictionsLPr(userId);
11844                        changed = true;
11845                        changedPackages.add(packageName);
11846                    }
11847                }
11848
11849                if (changed && suspended) {
11850                    killApplication(packageName, UserHandle.getUid(userId, appId),
11851                            "suspending package");
11852                }
11853            }
11854        } finally {
11855            Binder.restoreCallingIdentity(callingId);
11856        }
11857
11858        if (!changedPackages.isEmpty()) {
11859            sendPackagesSuspendedForUser(changedPackages.toArray(
11860                    new String[changedPackages.size()]), userId, suspended);
11861        }
11862
11863        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11864    }
11865
11866    @Override
11867    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11868        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11869                true /* requireFullPermission */, false /* checkShell */,
11870                "isPackageSuspendedForUser for user " + userId);
11871        synchronized (mPackages) {
11872            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11873            if (pkgSetting == null) {
11874                throw new IllegalArgumentException("Unknown target package: " + packageName);
11875            }
11876            return pkgSetting.getSuspended(userId);
11877        }
11878    }
11879
11880    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11881        if (isPackageDeviceAdmin(packageName, userId)) {
11882            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11883                    + "\": has an active device admin");
11884            return false;
11885        }
11886
11887        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11888        if (packageName.equals(activeLauncherPackageName)) {
11889            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11890                    + "\": contains the active launcher");
11891            return false;
11892        }
11893
11894        if (packageName.equals(mRequiredInstallerPackage)) {
11895            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11896                    + "\": required for package installation");
11897            return false;
11898        }
11899
11900        if (packageName.equals(mRequiredVerifierPackage)) {
11901            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11902                    + "\": required for package verification");
11903            return false;
11904        }
11905
11906        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11907            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11908                    + "\": is the default dialer");
11909            return false;
11910        }
11911
11912        return true;
11913    }
11914
11915    private String getActiveLauncherPackageName(int userId) {
11916        Intent intent = new Intent(Intent.ACTION_MAIN);
11917        intent.addCategory(Intent.CATEGORY_HOME);
11918        ResolveInfo resolveInfo = resolveIntent(
11919                intent,
11920                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11921                PackageManager.MATCH_DEFAULT_ONLY,
11922                userId);
11923
11924        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11925    }
11926
11927    private String getDefaultDialerPackageName(int userId) {
11928        synchronized (mPackages) {
11929            return mSettings.getDefaultDialerPackageNameLPw(userId);
11930        }
11931    }
11932
11933    @Override
11934    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11935        mContext.enforceCallingOrSelfPermission(
11936                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11937                "Only package verification agents can verify applications");
11938
11939        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11940        final PackageVerificationResponse response = new PackageVerificationResponse(
11941                verificationCode, Binder.getCallingUid());
11942        msg.arg1 = id;
11943        msg.obj = response;
11944        mHandler.sendMessage(msg);
11945    }
11946
11947    @Override
11948    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11949            long millisecondsToDelay) {
11950        mContext.enforceCallingOrSelfPermission(
11951                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11952                "Only package verification agents can extend verification timeouts");
11953
11954        final PackageVerificationState state = mPendingVerification.get(id);
11955        final PackageVerificationResponse response = new PackageVerificationResponse(
11956                verificationCodeAtTimeout, Binder.getCallingUid());
11957
11958        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11959            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11960        }
11961        if (millisecondsToDelay < 0) {
11962            millisecondsToDelay = 0;
11963        }
11964        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11965                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11966            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11967        }
11968
11969        if ((state != null) && !state.timeoutExtended()) {
11970            state.extendTimeout();
11971
11972            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11973            msg.arg1 = id;
11974            msg.obj = response;
11975            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11976        }
11977    }
11978
11979    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11980            int verificationCode, UserHandle user) {
11981        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11982        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11983        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11984        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11985        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11986
11987        mContext.sendBroadcastAsUser(intent, user,
11988                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11989    }
11990
11991    private ComponentName matchComponentForVerifier(String packageName,
11992            List<ResolveInfo> receivers) {
11993        ActivityInfo targetReceiver = null;
11994
11995        final int NR = receivers.size();
11996        for (int i = 0; i < NR; i++) {
11997            final ResolveInfo info = receivers.get(i);
11998            if (info.activityInfo == null) {
11999                continue;
12000            }
12001
12002            if (packageName.equals(info.activityInfo.packageName)) {
12003                targetReceiver = info.activityInfo;
12004                break;
12005            }
12006        }
12007
12008        if (targetReceiver == null) {
12009            return null;
12010        }
12011
12012        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12013    }
12014
12015    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12016            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12017        if (pkgInfo.verifiers.length == 0) {
12018            return null;
12019        }
12020
12021        final int N = pkgInfo.verifiers.length;
12022        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12023        for (int i = 0; i < N; i++) {
12024            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12025
12026            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12027                    receivers);
12028            if (comp == null) {
12029                continue;
12030            }
12031
12032            final int verifierUid = getUidForVerifier(verifierInfo);
12033            if (verifierUid == -1) {
12034                continue;
12035            }
12036
12037            if (DEBUG_VERIFY) {
12038                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12039                        + " with the correct signature");
12040            }
12041            sufficientVerifiers.add(comp);
12042            verificationState.addSufficientVerifier(verifierUid);
12043        }
12044
12045        return sufficientVerifiers;
12046    }
12047
12048    private int getUidForVerifier(VerifierInfo verifierInfo) {
12049        synchronized (mPackages) {
12050            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12051            if (pkg == null) {
12052                return -1;
12053            } else if (pkg.mSignatures.length != 1) {
12054                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12055                        + " has more than one signature; ignoring");
12056                return -1;
12057            }
12058
12059            /*
12060             * If the public key of the package's signature does not match
12061             * our expected public key, then this is a different package and
12062             * we should skip.
12063             */
12064
12065            final byte[] expectedPublicKey;
12066            try {
12067                final Signature verifierSig = pkg.mSignatures[0];
12068                final PublicKey publicKey = verifierSig.getPublicKey();
12069                expectedPublicKey = publicKey.getEncoded();
12070            } catch (CertificateException e) {
12071                return -1;
12072            }
12073
12074            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12075
12076            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12077                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12078                        + " does not have the expected public key; ignoring");
12079                return -1;
12080            }
12081
12082            return pkg.applicationInfo.uid;
12083        }
12084    }
12085
12086    @Override
12087    public void finishPackageInstall(int token, boolean didLaunch) {
12088        enforceSystemOrRoot("Only the system is allowed to finish installs");
12089
12090        if (DEBUG_INSTALL) {
12091            Slog.v(TAG, "BM finishing package install for " + token);
12092        }
12093        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12094
12095        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12096        mHandler.sendMessage(msg);
12097    }
12098
12099    /**
12100     * Get the verification agent timeout.
12101     *
12102     * @return verification timeout in milliseconds
12103     */
12104    private long getVerificationTimeout() {
12105        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12106                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12107                DEFAULT_VERIFICATION_TIMEOUT);
12108    }
12109
12110    /**
12111     * Get the default verification agent response code.
12112     *
12113     * @return default verification response code
12114     */
12115    private int getDefaultVerificationResponse() {
12116        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12117                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12118                DEFAULT_VERIFICATION_RESPONSE);
12119    }
12120
12121    /**
12122     * Check whether or not package verification has been enabled.
12123     *
12124     * @return true if verification should be performed
12125     */
12126    private boolean isVerificationEnabled(int userId, int installFlags) {
12127        if (!DEFAULT_VERIFY_ENABLE) {
12128            return false;
12129        }
12130        // Ephemeral apps don't get the full verification treatment
12131        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12132            if (DEBUG_EPHEMERAL) {
12133                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12134            }
12135            return false;
12136        }
12137
12138        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12139
12140        // Check if installing from ADB
12141        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12142            // Do not run verification in a test harness environment
12143            if (ActivityManager.isRunningInTestHarness()) {
12144                return false;
12145            }
12146            if (ensureVerifyAppsEnabled) {
12147                return true;
12148            }
12149            // Check if the developer does not want package verification for ADB installs
12150            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12151                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12152                return false;
12153            }
12154        }
12155
12156        if (ensureVerifyAppsEnabled) {
12157            return true;
12158        }
12159
12160        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12161                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12162    }
12163
12164    @Override
12165    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12166            throws RemoteException {
12167        mContext.enforceCallingOrSelfPermission(
12168                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12169                "Only intentfilter verification agents can verify applications");
12170
12171        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12172        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12173                Binder.getCallingUid(), verificationCode, failedDomains);
12174        msg.arg1 = id;
12175        msg.obj = response;
12176        mHandler.sendMessage(msg);
12177    }
12178
12179    @Override
12180    public int getIntentVerificationStatus(String packageName, int userId) {
12181        synchronized (mPackages) {
12182            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12183        }
12184    }
12185
12186    @Override
12187    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12188        mContext.enforceCallingOrSelfPermission(
12189                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12190
12191        boolean result = false;
12192        synchronized (mPackages) {
12193            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12194        }
12195        if (result) {
12196            scheduleWritePackageRestrictionsLocked(userId);
12197        }
12198        return result;
12199    }
12200
12201    @Override
12202    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12203            String packageName) {
12204        synchronized (mPackages) {
12205            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12206        }
12207    }
12208
12209    @Override
12210    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12211        if (TextUtils.isEmpty(packageName)) {
12212            return ParceledListSlice.emptyList();
12213        }
12214        synchronized (mPackages) {
12215            PackageParser.Package pkg = mPackages.get(packageName);
12216            if (pkg == null || pkg.activities == null) {
12217                return ParceledListSlice.emptyList();
12218            }
12219            final int count = pkg.activities.size();
12220            ArrayList<IntentFilter> result = new ArrayList<>();
12221            for (int n=0; n<count; n++) {
12222                PackageParser.Activity activity = pkg.activities.get(n);
12223                if (activity.intents != null && activity.intents.size() > 0) {
12224                    result.addAll(activity.intents);
12225                }
12226            }
12227            return new ParceledListSlice<>(result);
12228        }
12229    }
12230
12231    @Override
12232    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12233        mContext.enforceCallingOrSelfPermission(
12234                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12235
12236        synchronized (mPackages) {
12237            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12238            if (packageName != null) {
12239                result |= updateIntentVerificationStatus(packageName,
12240                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12241                        userId);
12242                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12243                        packageName, userId);
12244            }
12245            return result;
12246        }
12247    }
12248
12249    @Override
12250    public String getDefaultBrowserPackageName(int userId) {
12251        synchronized (mPackages) {
12252            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12253        }
12254    }
12255
12256    /**
12257     * Get the "allow unknown sources" setting.
12258     *
12259     * @return the current "allow unknown sources" setting
12260     */
12261    private int getUnknownSourcesSettings() {
12262        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12263                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12264                -1);
12265    }
12266
12267    @Override
12268    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12269        final int uid = Binder.getCallingUid();
12270        // writer
12271        synchronized (mPackages) {
12272            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12273            if (targetPackageSetting == null) {
12274                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12275            }
12276
12277            PackageSetting installerPackageSetting;
12278            if (installerPackageName != null) {
12279                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12280                if (installerPackageSetting == null) {
12281                    throw new IllegalArgumentException("Unknown installer package: "
12282                            + installerPackageName);
12283                }
12284            } else {
12285                installerPackageSetting = null;
12286            }
12287
12288            Signature[] callerSignature;
12289            Object obj = mSettings.getUserIdLPr(uid);
12290            if (obj != null) {
12291                if (obj instanceof SharedUserSetting) {
12292                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12293                } else if (obj instanceof PackageSetting) {
12294                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12295                } else {
12296                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12297                }
12298            } else {
12299                throw new SecurityException("Unknown calling UID: " + uid);
12300            }
12301
12302            // Verify: can't set installerPackageName to a package that is
12303            // not signed with the same cert as the caller.
12304            if (installerPackageSetting != null) {
12305                if (compareSignatures(callerSignature,
12306                        installerPackageSetting.signatures.mSignatures)
12307                        != PackageManager.SIGNATURE_MATCH) {
12308                    throw new SecurityException(
12309                            "Caller does not have same cert as new installer package "
12310                            + installerPackageName);
12311                }
12312            }
12313
12314            // Verify: if target already has an installer package, it must
12315            // be signed with the same cert as the caller.
12316            if (targetPackageSetting.installerPackageName != null) {
12317                PackageSetting setting = mSettings.mPackages.get(
12318                        targetPackageSetting.installerPackageName);
12319                // If the currently set package isn't valid, then it's always
12320                // okay to change it.
12321                if (setting != null) {
12322                    if (compareSignatures(callerSignature,
12323                            setting.signatures.mSignatures)
12324                            != PackageManager.SIGNATURE_MATCH) {
12325                        throw new SecurityException(
12326                                "Caller does not have same cert as old installer package "
12327                                + targetPackageSetting.installerPackageName);
12328                    }
12329                }
12330            }
12331
12332            // Okay!
12333            targetPackageSetting.installerPackageName = installerPackageName;
12334            if (installerPackageName != null) {
12335                mSettings.mInstallerPackages.add(installerPackageName);
12336            }
12337            scheduleWriteSettingsLocked();
12338        }
12339    }
12340
12341    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12342        // Queue up an async operation since the package installation may take a little while.
12343        mHandler.post(new Runnable() {
12344            public void run() {
12345                mHandler.removeCallbacks(this);
12346                 // Result object to be returned
12347                PackageInstalledInfo res = new PackageInstalledInfo();
12348                res.setReturnCode(currentStatus);
12349                res.uid = -1;
12350                res.pkg = null;
12351                res.removedInfo = null;
12352                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12353                    args.doPreInstall(res.returnCode);
12354                    synchronized (mInstallLock) {
12355                        installPackageTracedLI(args, res);
12356                    }
12357                    args.doPostInstall(res.returnCode, res.uid);
12358                }
12359
12360                // A restore should be performed at this point if (a) the install
12361                // succeeded, (b) the operation is not an update, and (c) the new
12362                // package has not opted out of backup participation.
12363                final boolean update = res.removedInfo != null
12364                        && res.removedInfo.removedPackage != null;
12365                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12366                boolean doRestore = !update
12367                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12368
12369                // Set up the post-install work request bookkeeping.  This will be used
12370                // and cleaned up by the post-install event handling regardless of whether
12371                // there's a restore pass performed.  Token values are >= 1.
12372                int token;
12373                if (mNextInstallToken < 0) mNextInstallToken = 1;
12374                token = mNextInstallToken++;
12375
12376                PostInstallData data = new PostInstallData(args, res);
12377                mRunningInstalls.put(token, data);
12378                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12379
12380                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12381                    // Pass responsibility to the Backup Manager.  It will perform a
12382                    // restore if appropriate, then pass responsibility back to the
12383                    // Package Manager to run the post-install observer callbacks
12384                    // and broadcasts.
12385                    IBackupManager bm = IBackupManager.Stub.asInterface(
12386                            ServiceManager.getService(Context.BACKUP_SERVICE));
12387                    if (bm != null) {
12388                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12389                                + " to BM for possible restore");
12390                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12391                        try {
12392                            // TODO: http://b/22388012
12393                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12394                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12395                            } else {
12396                                doRestore = false;
12397                            }
12398                        } catch (RemoteException e) {
12399                            // can't happen; the backup manager is local
12400                        } catch (Exception e) {
12401                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12402                            doRestore = false;
12403                        }
12404                    } else {
12405                        Slog.e(TAG, "Backup Manager not found!");
12406                        doRestore = false;
12407                    }
12408                }
12409
12410                if (!doRestore) {
12411                    // No restore possible, or the Backup Manager was mysteriously not
12412                    // available -- just fire the post-install work request directly.
12413                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12414
12415                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12416
12417                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12418                    mHandler.sendMessage(msg);
12419                }
12420            }
12421        });
12422    }
12423
12424    /**
12425     * Callback from PackageSettings whenever an app is first transitioned out of the
12426     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12427     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12428     * here whether the app is the target of an ongoing install, and only send the
12429     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12430     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12431     * handling.
12432     */
12433    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12434        // Serialize this with the rest of the install-process message chain.  In the
12435        // restore-at-install case, this Runnable will necessarily run before the
12436        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12437        // are coherent.  In the non-restore case, the app has already completed install
12438        // and been launched through some other means, so it is not in a problematic
12439        // state for observers to see the FIRST_LAUNCH signal.
12440        mHandler.post(new Runnable() {
12441            @Override
12442            public void run() {
12443                for (int i = 0; i < mRunningInstalls.size(); i++) {
12444                    final PostInstallData data = mRunningInstalls.valueAt(i);
12445                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12446                        // right package; but is it for the right user?
12447                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12448                            if (userId == data.res.newUsers[uIndex]) {
12449                                if (DEBUG_BACKUP) {
12450                                    Slog.i(TAG, "Package " + pkgName
12451                                            + " being restored so deferring FIRST_LAUNCH");
12452                                }
12453                                return;
12454                            }
12455                        }
12456                    }
12457                }
12458                // didn't find it, so not being restored
12459                if (DEBUG_BACKUP) {
12460                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12461                }
12462                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12463            }
12464        });
12465    }
12466
12467    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12468        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12469                installerPkg, null, userIds);
12470    }
12471
12472    private abstract class HandlerParams {
12473        private static final int MAX_RETRIES = 4;
12474
12475        /**
12476         * Number of times startCopy() has been attempted and had a non-fatal
12477         * error.
12478         */
12479        private int mRetries = 0;
12480
12481        /** User handle for the user requesting the information or installation. */
12482        private final UserHandle mUser;
12483        String traceMethod;
12484        int traceCookie;
12485
12486        HandlerParams(UserHandle user) {
12487            mUser = user;
12488        }
12489
12490        UserHandle getUser() {
12491            return mUser;
12492        }
12493
12494        HandlerParams setTraceMethod(String traceMethod) {
12495            this.traceMethod = traceMethod;
12496            return this;
12497        }
12498
12499        HandlerParams setTraceCookie(int traceCookie) {
12500            this.traceCookie = traceCookie;
12501            return this;
12502        }
12503
12504        final boolean startCopy() {
12505            boolean res;
12506            try {
12507                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12508
12509                if (++mRetries > MAX_RETRIES) {
12510                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12511                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12512                    handleServiceError();
12513                    return false;
12514                } else {
12515                    handleStartCopy();
12516                    res = true;
12517                }
12518            } catch (RemoteException e) {
12519                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12520                mHandler.sendEmptyMessage(MCS_RECONNECT);
12521                res = false;
12522            }
12523            handleReturnCode();
12524            return res;
12525        }
12526
12527        final void serviceError() {
12528            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12529            handleServiceError();
12530            handleReturnCode();
12531        }
12532
12533        abstract void handleStartCopy() throws RemoteException;
12534        abstract void handleServiceError();
12535        abstract void handleReturnCode();
12536    }
12537
12538    class MeasureParams extends HandlerParams {
12539        private final PackageStats mStats;
12540        private boolean mSuccess;
12541
12542        private final IPackageStatsObserver mObserver;
12543
12544        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12545            super(new UserHandle(stats.userHandle));
12546            mObserver = observer;
12547            mStats = stats;
12548        }
12549
12550        @Override
12551        public String toString() {
12552            return "MeasureParams{"
12553                + Integer.toHexString(System.identityHashCode(this))
12554                + " " + mStats.packageName + "}";
12555        }
12556
12557        @Override
12558        void handleStartCopy() throws RemoteException {
12559            synchronized (mInstallLock) {
12560                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12561            }
12562
12563            if (mSuccess) {
12564                boolean mounted = false;
12565                try {
12566                    final String status = Environment.getExternalStorageState();
12567                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12568                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12569                } catch (Exception e) {
12570                }
12571
12572                if (mounted) {
12573                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12574
12575                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12576                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12577
12578                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12579                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12580
12581                    // Always subtract cache size, since it's a subdirectory
12582                    mStats.externalDataSize -= mStats.externalCacheSize;
12583
12584                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12585                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12586
12587                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12588                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12589                }
12590            }
12591        }
12592
12593        @Override
12594        void handleReturnCode() {
12595            if (mObserver != null) {
12596                try {
12597                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12598                } catch (RemoteException e) {
12599                    Slog.i(TAG, "Observer no longer exists.");
12600                }
12601            }
12602        }
12603
12604        @Override
12605        void handleServiceError() {
12606            Slog.e(TAG, "Could not measure application " + mStats.packageName
12607                            + " external storage");
12608        }
12609    }
12610
12611    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12612            throws RemoteException {
12613        long result = 0;
12614        for (File path : paths) {
12615            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12616        }
12617        return result;
12618    }
12619
12620    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12621        for (File path : paths) {
12622            try {
12623                mcs.clearDirectory(path.getAbsolutePath());
12624            } catch (RemoteException e) {
12625            }
12626        }
12627    }
12628
12629    static class OriginInfo {
12630        /**
12631         * Location where install is coming from, before it has been
12632         * copied/renamed into place. This could be a single monolithic APK
12633         * file, or a cluster directory. This location may be untrusted.
12634         */
12635        final File file;
12636        final String cid;
12637
12638        /**
12639         * Flag indicating that {@link #file} or {@link #cid} has already been
12640         * staged, meaning downstream users don't need to defensively copy the
12641         * contents.
12642         */
12643        final boolean staged;
12644
12645        /**
12646         * Flag indicating that {@link #file} or {@link #cid} is an already
12647         * installed app that is being moved.
12648         */
12649        final boolean existing;
12650
12651        final String resolvedPath;
12652        final File resolvedFile;
12653
12654        static OriginInfo fromNothing() {
12655            return new OriginInfo(null, null, false, false);
12656        }
12657
12658        static OriginInfo fromUntrustedFile(File file) {
12659            return new OriginInfo(file, null, false, false);
12660        }
12661
12662        static OriginInfo fromExistingFile(File file) {
12663            return new OriginInfo(file, null, false, true);
12664        }
12665
12666        static OriginInfo fromStagedFile(File file) {
12667            return new OriginInfo(file, null, true, false);
12668        }
12669
12670        static OriginInfo fromStagedContainer(String cid) {
12671            return new OriginInfo(null, cid, true, false);
12672        }
12673
12674        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12675            this.file = file;
12676            this.cid = cid;
12677            this.staged = staged;
12678            this.existing = existing;
12679
12680            if (cid != null) {
12681                resolvedPath = PackageHelper.getSdDir(cid);
12682                resolvedFile = new File(resolvedPath);
12683            } else if (file != null) {
12684                resolvedPath = file.getAbsolutePath();
12685                resolvedFile = file;
12686            } else {
12687                resolvedPath = null;
12688                resolvedFile = null;
12689            }
12690        }
12691    }
12692
12693    static class MoveInfo {
12694        final int moveId;
12695        final String fromUuid;
12696        final String toUuid;
12697        final String packageName;
12698        final String dataAppName;
12699        final int appId;
12700        final String seinfo;
12701        final int targetSdkVersion;
12702
12703        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12704                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12705            this.moveId = moveId;
12706            this.fromUuid = fromUuid;
12707            this.toUuid = toUuid;
12708            this.packageName = packageName;
12709            this.dataAppName = dataAppName;
12710            this.appId = appId;
12711            this.seinfo = seinfo;
12712            this.targetSdkVersion = targetSdkVersion;
12713        }
12714    }
12715
12716    static class VerificationInfo {
12717        /** A constant used to indicate that a uid value is not present. */
12718        public static final int NO_UID = -1;
12719
12720        /** URI referencing where the package was downloaded from. */
12721        final Uri originatingUri;
12722
12723        /** HTTP referrer URI associated with the originatingURI. */
12724        final Uri referrer;
12725
12726        /** UID of the application that the install request originated from. */
12727        final int originatingUid;
12728
12729        /** UID of application requesting the install */
12730        final int installerUid;
12731
12732        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12733            this.originatingUri = originatingUri;
12734            this.referrer = referrer;
12735            this.originatingUid = originatingUid;
12736            this.installerUid = installerUid;
12737        }
12738    }
12739
12740    class InstallParams extends HandlerParams {
12741        final OriginInfo origin;
12742        final MoveInfo move;
12743        final IPackageInstallObserver2 observer;
12744        int installFlags;
12745        final String installerPackageName;
12746        final String volumeUuid;
12747        private InstallArgs mArgs;
12748        private int mRet;
12749        final String packageAbiOverride;
12750        final String[] grantedRuntimePermissions;
12751        final VerificationInfo verificationInfo;
12752        final Certificate[][] certificates;
12753
12754        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12755                int installFlags, String installerPackageName, String volumeUuid,
12756                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12757                String[] grantedPermissions, Certificate[][] certificates) {
12758            super(user);
12759            this.origin = origin;
12760            this.move = move;
12761            this.observer = observer;
12762            this.installFlags = installFlags;
12763            this.installerPackageName = installerPackageName;
12764            this.volumeUuid = volumeUuid;
12765            this.verificationInfo = verificationInfo;
12766            this.packageAbiOverride = packageAbiOverride;
12767            this.grantedRuntimePermissions = grantedPermissions;
12768            this.certificates = certificates;
12769        }
12770
12771        @Override
12772        public String toString() {
12773            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12774                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12775        }
12776
12777        private int installLocationPolicy(PackageInfoLite pkgLite) {
12778            String packageName = pkgLite.packageName;
12779            int installLocation = pkgLite.installLocation;
12780            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12781            // reader
12782            synchronized (mPackages) {
12783                // Currently installed package which the new package is attempting to replace or
12784                // null if no such package is installed.
12785                PackageParser.Package installedPkg = mPackages.get(packageName);
12786                // Package which currently owns the data which the new package will own if installed.
12787                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12788                // will be null whereas dataOwnerPkg will contain information about the package
12789                // which was uninstalled while keeping its data.
12790                PackageParser.Package dataOwnerPkg = installedPkg;
12791                if (dataOwnerPkg  == null) {
12792                    PackageSetting ps = mSettings.mPackages.get(packageName);
12793                    if (ps != null) {
12794                        dataOwnerPkg = ps.pkg;
12795                    }
12796                }
12797
12798                if (dataOwnerPkg != null) {
12799                    // If installed, the package will get access to data left on the device by its
12800                    // predecessor. As a security measure, this is permited only if this is not a
12801                    // version downgrade or if the predecessor package is marked as debuggable and
12802                    // a downgrade is explicitly requested.
12803                    //
12804                    // On debuggable platform builds, downgrades are permitted even for
12805                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12806                    // not offer security guarantees and thus it's OK to disable some security
12807                    // mechanisms to make debugging/testing easier on those builds. However, even on
12808                    // debuggable builds downgrades of packages are permitted only if requested via
12809                    // installFlags. This is because we aim to keep the behavior of debuggable
12810                    // platform builds as close as possible to the behavior of non-debuggable
12811                    // platform builds.
12812                    final boolean downgradeRequested =
12813                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12814                    final boolean packageDebuggable =
12815                                (dataOwnerPkg.applicationInfo.flags
12816                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12817                    final boolean downgradePermitted =
12818                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12819                    if (!downgradePermitted) {
12820                        try {
12821                            checkDowngrade(dataOwnerPkg, pkgLite);
12822                        } catch (PackageManagerException e) {
12823                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12824                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12825                        }
12826                    }
12827                }
12828
12829                if (installedPkg != null) {
12830                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12831                        // Check for updated system application.
12832                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12833                            if (onSd) {
12834                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12835                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12836                            }
12837                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12838                        } else {
12839                            if (onSd) {
12840                                // Install flag overrides everything.
12841                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12842                            }
12843                            // If current upgrade specifies particular preference
12844                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12845                                // Application explicitly specified internal.
12846                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12847                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12848                                // App explictly prefers external. Let policy decide
12849                            } else {
12850                                // Prefer previous location
12851                                if (isExternal(installedPkg)) {
12852                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12853                                }
12854                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12855                            }
12856                        }
12857                    } else {
12858                        // Invalid install. Return error code
12859                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12860                    }
12861                }
12862            }
12863            // All the special cases have been taken care of.
12864            // Return result based on recommended install location.
12865            if (onSd) {
12866                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12867            }
12868            return pkgLite.recommendedInstallLocation;
12869        }
12870
12871        /*
12872         * Invoke remote method to get package information and install
12873         * location values. Override install location based on default
12874         * policy if needed and then create install arguments based
12875         * on the install location.
12876         */
12877        public void handleStartCopy() throws RemoteException {
12878            int ret = PackageManager.INSTALL_SUCCEEDED;
12879
12880            // If we're already staged, we've firmly committed to an install location
12881            if (origin.staged) {
12882                if (origin.file != null) {
12883                    installFlags |= PackageManager.INSTALL_INTERNAL;
12884                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12885                } else if (origin.cid != null) {
12886                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12887                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12888                } else {
12889                    throw new IllegalStateException("Invalid stage location");
12890                }
12891            }
12892
12893            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12894            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12895            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12896            PackageInfoLite pkgLite = null;
12897
12898            if (onInt && onSd) {
12899                // Check if both bits are set.
12900                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12901                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12902            } else if (onSd && ephemeral) {
12903                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12904                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12905            } else {
12906                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12907                        packageAbiOverride);
12908
12909                if (DEBUG_EPHEMERAL && ephemeral) {
12910                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12911                }
12912
12913                /*
12914                 * If we have too little free space, try to free cache
12915                 * before giving up.
12916                 */
12917                if (!origin.staged && pkgLite.recommendedInstallLocation
12918                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12919                    // TODO: focus freeing disk space on the target device
12920                    final StorageManager storage = StorageManager.from(mContext);
12921                    final long lowThreshold = storage.getStorageLowBytes(
12922                            Environment.getDataDirectory());
12923
12924                    final long sizeBytes = mContainerService.calculateInstalledSize(
12925                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12926
12927                    try {
12928                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12929                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12930                                installFlags, packageAbiOverride);
12931                    } catch (InstallerException e) {
12932                        Slog.w(TAG, "Failed to free cache", e);
12933                    }
12934
12935                    /*
12936                     * The cache free must have deleted the file we
12937                     * downloaded to install.
12938                     *
12939                     * TODO: fix the "freeCache" call to not delete
12940                     *       the file we care about.
12941                     */
12942                    if (pkgLite.recommendedInstallLocation
12943                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12944                        pkgLite.recommendedInstallLocation
12945                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12946                    }
12947                }
12948            }
12949
12950            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12951                int loc = pkgLite.recommendedInstallLocation;
12952                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12953                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12954                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12955                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12956                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12957                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12958                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12959                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12960                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12961                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12962                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12963                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12964                } else {
12965                    // Override with defaults if needed.
12966                    loc = installLocationPolicy(pkgLite);
12967                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12968                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12969                    } else if (!onSd && !onInt) {
12970                        // Override install location with flags
12971                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12972                            // Set the flag to install on external media.
12973                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12974                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12975                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12976                            if (DEBUG_EPHEMERAL) {
12977                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12978                            }
12979                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12980                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12981                                    |PackageManager.INSTALL_INTERNAL);
12982                        } else {
12983                            // Make sure the flag for installing on external
12984                            // media is unset
12985                            installFlags |= PackageManager.INSTALL_INTERNAL;
12986                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12987                        }
12988                    }
12989                }
12990            }
12991
12992            final InstallArgs args = createInstallArgs(this);
12993            mArgs = args;
12994
12995            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12996                // TODO: http://b/22976637
12997                // Apps installed for "all" users use the device owner to verify the app
12998                UserHandle verifierUser = getUser();
12999                if (verifierUser == UserHandle.ALL) {
13000                    verifierUser = UserHandle.SYSTEM;
13001                }
13002
13003                /*
13004                 * Determine if we have any installed package verifiers. If we
13005                 * do, then we'll defer to them to verify the packages.
13006                 */
13007                final int requiredUid = mRequiredVerifierPackage == null ? -1
13008                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13009                                verifierUser.getIdentifier());
13010                if (!origin.existing && requiredUid != -1
13011                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13012                    final Intent verification = new Intent(
13013                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13014                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13015                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13016                            PACKAGE_MIME_TYPE);
13017                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13018
13019                    // Query all live verifiers based on current user state
13020                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13021                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13022
13023                    if (DEBUG_VERIFY) {
13024                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13025                                + verification.toString() + " with " + pkgLite.verifiers.length
13026                                + " optional verifiers");
13027                    }
13028
13029                    final int verificationId = mPendingVerificationToken++;
13030
13031                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13032
13033                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13034                            installerPackageName);
13035
13036                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13037                            installFlags);
13038
13039                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13040                            pkgLite.packageName);
13041
13042                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13043                            pkgLite.versionCode);
13044
13045                    if (verificationInfo != null) {
13046                        if (verificationInfo.originatingUri != null) {
13047                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13048                                    verificationInfo.originatingUri);
13049                        }
13050                        if (verificationInfo.referrer != null) {
13051                            verification.putExtra(Intent.EXTRA_REFERRER,
13052                                    verificationInfo.referrer);
13053                        }
13054                        if (verificationInfo.originatingUid >= 0) {
13055                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13056                                    verificationInfo.originatingUid);
13057                        }
13058                        if (verificationInfo.installerUid >= 0) {
13059                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13060                                    verificationInfo.installerUid);
13061                        }
13062                    }
13063
13064                    final PackageVerificationState verificationState = new PackageVerificationState(
13065                            requiredUid, args);
13066
13067                    mPendingVerification.append(verificationId, verificationState);
13068
13069                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13070                            receivers, verificationState);
13071
13072                    /*
13073                     * If any sufficient verifiers were listed in the package
13074                     * manifest, attempt to ask them.
13075                     */
13076                    if (sufficientVerifiers != null) {
13077                        final int N = sufficientVerifiers.size();
13078                        if (N == 0) {
13079                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13080                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13081                        } else {
13082                            for (int i = 0; i < N; i++) {
13083                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13084
13085                                final Intent sufficientIntent = new Intent(verification);
13086                                sufficientIntent.setComponent(verifierComponent);
13087                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13088                            }
13089                        }
13090                    }
13091
13092                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13093                            mRequiredVerifierPackage, receivers);
13094                    if (ret == PackageManager.INSTALL_SUCCEEDED
13095                            && mRequiredVerifierPackage != null) {
13096                        Trace.asyncTraceBegin(
13097                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13098                        /*
13099                         * Send the intent to the required verification agent,
13100                         * but only start the verification timeout after the
13101                         * target BroadcastReceivers have run.
13102                         */
13103                        verification.setComponent(requiredVerifierComponent);
13104                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13105                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13106                                new BroadcastReceiver() {
13107                                    @Override
13108                                    public void onReceive(Context context, Intent intent) {
13109                                        final Message msg = mHandler
13110                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13111                                        msg.arg1 = verificationId;
13112                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13113                                    }
13114                                }, null, 0, null, null);
13115
13116                        /*
13117                         * We don't want the copy to proceed until verification
13118                         * succeeds, so null out this field.
13119                         */
13120                        mArgs = null;
13121                    }
13122                } else {
13123                    /*
13124                     * No package verification is enabled, so immediately start
13125                     * the remote call to initiate copy using temporary file.
13126                     */
13127                    ret = args.copyApk(mContainerService, true);
13128                }
13129            }
13130
13131            mRet = ret;
13132        }
13133
13134        @Override
13135        void handleReturnCode() {
13136            // If mArgs is null, then MCS couldn't be reached. When it
13137            // reconnects, it will try again to install. At that point, this
13138            // will succeed.
13139            if (mArgs != null) {
13140                processPendingInstall(mArgs, mRet);
13141            }
13142        }
13143
13144        @Override
13145        void handleServiceError() {
13146            mArgs = createInstallArgs(this);
13147            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13148        }
13149
13150        public boolean isForwardLocked() {
13151            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13152        }
13153    }
13154
13155    /**
13156     * Used during creation of InstallArgs
13157     *
13158     * @param installFlags package installation flags
13159     * @return true if should be installed on external storage
13160     */
13161    private static boolean installOnExternalAsec(int installFlags) {
13162        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13163            return false;
13164        }
13165        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13166            return true;
13167        }
13168        return false;
13169    }
13170
13171    /**
13172     * Used during creation of InstallArgs
13173     *
13174     * @param installFlags package installation flags
13175     * @return true if should be installed as forward locked
13176     */
13177    private static boolean installForwardLocked(int installFlags) {
13178        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13179    }
13180
13181    private InstallArgs createInstallArgs(InstallParams params) {
13182        if (params.move != null) {
13183            return new MoveInstallArgs(params);
13184        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13185            return new AsecInstallArgs(params);
13186        } else {
13187            return new FileInstallArgs(params);
13188        }
13189    }
13190
13191    /**
13192     * Create args that describe an existing installed package. Typically used
13193     * when cleaning up old installs, or used as a move source.
13194     */
13195    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13196            String resourcePath, String[] instructionSets) {
13197        final boolean isInAsec;
13198        if (installOnExternalAsec(installFlags)) {
13199            /* Apps on SD card are always in ASEC containers. */
13200            isInAsec = true;
13201        } else if (installForwardLocked(installFlags)
13202                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13203            /*
13204             * Forward-locked apps are only in ASEC containers if they're the
13205             * new style
13206             */
13207            isInAsec = true;
13208        } else {
13209            isInAsec = false;
13210        }
13211
13212        if (isInAsec) {
13213            return new AsecInstallArgs(codePath, instructionSets,
13214                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13215        } else {
13216            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13217        }
13218    }
13219
13220    static abstract class InstallArgs {
13221        /** @see InstallParams#origin */
13222        final OriginInfo origin;
13223        /** @see InstallParams#move */
13224        final MoveInfo move;
13225
13226        final IPackageInstallObserver2 observer;
13227        // Always refers to PackageManager flags only
13228        final int installFlags;
13229        final String installerPackageName;
13230        final String volumeUuid;
13231        final UserHandle user;
13232        final String abiOverride;
13233        final String[] installGrantPermissions;
13234        /** If non-null, drop an async trace when the install completes */
13235        final String traceMethod;
13236        final int traceCookie;
13237        final Certificate[][] certificates;
13238
13239        // The list of instruction sets supported by this app. This is currently
13240        // only used during the rmdex() phase to clean up resources. We can get rid of this
13241        // if we move dex files under the common app path.
13242        /* nullable */ String[] instructionSets;
13243
13244        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13245                int installFlags, String installerPackageName, String volumeUuid,
13246                UserHandle user, String[] instructionSets,
13247                String abiOverride, String[] installGrantPermissions,
13248                String traceMethod, int traceCookie, Certificate[][] certificates) {
13249            this.origin = origin;
13250            this.move = move;
13251            this.installFlags = installFlags;
13252            this.observer = observer;
13253            this.installerPackageName = installerPackageName;
13254            this.volumeUuid = volumeUuid;
13255            this.user = user;
13256            this.instructionSets = instructionSets;
13257            this.abiOverride = abiOverride;
13258            this.installGrantPermissions = installGrantPermissions;
13259            this.traceMethod = traceMethod;
13260            this.traceCookie = traceCookie;
13261            this.certificates = certificates;
13262        }
13263
13264        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13265        abstract int doPreInstall(int status);
13266
13267        /**
13268         * Rename package into final resting place. All paths on the given
13269         * scanned package should be updated to reflect the rename.
13270         */
13271        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13272        abstract int doPostInstall(int status, int uid);
13273
13274        /** @see PackageSettingBase#codePathString */
13275        abstract String getCodePath();
13276        /** @see PackageSettingBase#resourcePathString */
13277        abstract String getResourcePath();
13278
13279        // Need installer lock especially for dex file removal.
13280        abstract void cleanUpResourcesLI();
13281        abstract boolean doPostDeleteLI(boolean delete);
13282
13283        /**
13284         * Called before the source arguments are copied. This is used mostly
13285         * for MoveParams when it needs to read the source file to put it in the
13286         * destination.
13287         */
13288        int doPreCopy() {
13289            return PackageManager.INSTALL_SUCCEEDED;
13290        }
13291
13292        /**
13293         * Called after the source arguments are copied. This is used mostly for
13294         * MoveParams when it needs to read the source file to put it in the
13295         * destination.
13296         */
13297        int doPostCopy(int uid) {
13298            return PackageManager.INSTALL_SUCCEEDED;
13299        }
13300
13301        protected boolean isFwdLocked() {
13302            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13303        }
13304
13305        protected boolean isExternalAsec() {
13306            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13307        }
13308
13309        protected boolean isEphemeral() {
13310            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13311        }
13312
13313        UserHandle getUser() {
13314            return user;
13315        }
13316    }
13317
13318    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13319        if (!allCodePaths.isEmpty()) {
13320            if (instructionSets == null) {
13321                throw new IllegalStateException("instructionSet == null");
13322            }
13323            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13324            for (String codePath : allCodePaths) {
13325                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13326                    try {
13327                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13328                    } catch (InstallerException ignored) {
13329                    }
13330                }
13331            }
13332        }
13333    }
13334
13335    /**
13336     * Logic to handle installation of non-ASEC applications, including copying
13337     * and renaming logic.
13338     */
13339    class FileInstallArgs extends InstallArgs {
13340        private File codeFile;
13341        private File resourceFile;
13342
13343        // Example topology:
13344        // /data/app/com.example/base.apk
13345        // /data/app/com.example/split_foo.apk
13346        // /data/app/com.example/lib/arm/libfoo.so
13347        // /data/app/com.example/lib/arm64/libfoo.so
13348        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13349
13350        /** New install */
13351        FileInstallArgs(InstallParams params) {
13352            super(params.origin, params.move, params.observer, params.installFlags,
13353                    params.installerPackageName, params.volumeUuid,
13354                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13355                    params.grantedRuntimePermissions,
13356                    params.traceMethod, params.traceCookie, params.certificates);
13357            if (isFwdLocked()) {
13358                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13359            }
13360        }
13361
13362        /** Existing install */
13363        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13364            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13365                    null, null, null, 0, null /*certificates*/);
13366            this.codeFile = (codePath != null) ? new File(codePath) : null;
13367            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13368        }
13369
13370        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13371            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13372            try {
13373                return doCopyApk(imcs, temp);
13374            } finally {
13375                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13376            }
13377        }
13378
13379        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13380            if (origin.staged) {
13381                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13382                codeFile = origin.file;
13383                resourceFile = origin.file;
13384                return PackageManager.INSTALL_SUCCEEDED;
13385            }
13386
13387            try {
13388                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13389                final File tempDir =
13390                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13391                codeFile = tempDir;
13392                resourceFile = tempDir;
13393            } catch (IOException e) {
13394                Slog.w(TAG, "Failed to create copy file: " + e);
13395                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13396            }
13397
13398            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13399                @Override
13400                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13401                    if (!FileUtils.isValidExtFilename(name)) {
13402                        throw new IllegalArgumentException("Invalid filename: " + name);
13403                    }
13404                    try {
13405                        final File file = new File(codeFile, name);
13406                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13407                                O_RDWR | O_CREAT, 0644);
13408                        Os.chmod(file.getAbsolutePath(), 0644);
13409                        return new ParcelFileDescriptor(fd);
13410                    } catch (ErrnoException e) {
13411                        throw new RemoteException("Failed to open: " + e.getMessage());
13412                    }
13413                }
13414            };
13415
13416            int ret = PackageManager.INSTALL_SUCCEEDED;
13417            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13418            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13419                Slog.e(TAG, "Failed to copy package");
13420                return ret;
13421            }
13422
13423            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13424            NativeLibraryHelper.Handle handle = null;
13425            try {
13426                handle = NativeLibraryHelper.Handle.create(codeFile);
13427                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13428                        abiOverride);
13429            } catch (IOException e) {
13430                Slog.e(TAG, "Copying native libraries failed", e);
13431                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13432            } finally {
13433                IoUtils.closeQuietly(handle);
13434            }
13435
13436            return ret;
13437        }
13438
13439        int doPreInstall(int status) {
13440            if (status != PackageManager.INSTALL_SUCCEEDED) {
13441                cleanUp();
13442            }
13443            return status;
13444        }
13445
13446        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13447            if (status != PackageManager.INSTALL_SUCCEEDED) {
13448                cleanUp();
13449                return false;
13450            }
13451
13452            final File targetDir = codeFile.getParentFile();
13453            final File beforeCodeFile = codeFile;
13454            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13455
13456            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13457            try {
13458                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13459            } catch (ErrnoException e) {
13460                Slog.w(TAG, "Failed to rename", e);
13461                return false;
13462            }
13463
13464            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13465                Slog.w(TAG, "Failed to restorecon");
13466                return false;
13467            }
13468
13469            // Reflect the rename internally
13470            codeFile = afterCodeFile;
13471            resourceFile = afterCodeFile;
13472
13473            // Reflect the rename in scanned details
13474            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13475            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13476                    afterCodeFile, pkg.baseCodePath));
13477            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13478                    afterCodeFile, pkg.splitCodePaths));
13479
13480            // Reflect the rename in app info
13481            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13482            pkg.setApplicationInfoCodePath(pkg.codePath);
13483            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13484            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13485            pkg.setApplicationInfoResourcePath(pkg.codePath);
13486            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13487            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13488
13489            return true;
13490        }
13491
13492        int doPostInstall(int status, int uid) {
13493            if (status != PackageManager.INSTALL_SUCCEEDED) {
13494                cleanUp();
13495            }
13496            return status;
13497        }
13498
13499        @Override
13500        String getCodePath() {
13501            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13502        }
13503
13504        @Override
13505        String getResourcePath() {
13506            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13507        }
13508
13509        private boolean cleanUp() {
13510            if (codeFile == null || !codeFile.exists()) {
13511                return false;
13512            }
13513
13514            removeCodePathLI(codeFile);
13515
13516            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13517                resourceFile.delete();
13518            }
13519
13520            return true;
13521        }
13522
13523        void cleanUpResourcesLI() {
13524            // Try enumerating all code paths before deleting
13525            List<String> allCodePaths = Collections.EMPTY_LIST;
13526            if (codeFile != null && codeFile.exists()) {
13527                try {
13528                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13529                    allCodePaths = pkg.getAllCodePaths();
13530                } catch (PackageParserException e) {
13531                    // Ignored; we tried our best
13532                }
13533            }
13534
13535            cleanUp();
13536            removeDexFiles(allCodePaths, instructionSets);
13537        }
13538
13539        boolean doPostDeleteLI(boolean delete) {
13540            // XXX err, shouldn't we respect the delete flag?
13541            cleanUpResourcesLI();
13542            return true;
13543        }
13544    }
13545
13546    private boolean isAsecExternal(String cid) {
13547        final String asecPath = PackageHelper.getSdFilesystem(cid);
13548        return !asecPath.startsWith(mAsecInternalPath);
13549    }
13550
13551    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13552            PackageManagerException {
13553        if (copyRet < 0) {
13554            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13555                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13556                throw new PackageManagerException(copyRet, message);
13557            }
13558        }
13559    }
13560
13561    /**
13562     * Extract the MountService "container ID" from the full code path of an
13563     * .apk.
13564     */
13565    static String cidFromCodePath(String fullCodePath) {
13566        int eidx = fullCodePath.lastIndexOf("/");
13567        String subStr1 = fullCodePath.substring(0, eidx);
13568        int sidx = subStr1.lastIndexOf("/");
13569        return subStr1.substring(sidx+1, eidx);
13570    }
13571
13572    /**
13573     * Logic to handle installation of ASEC applications, including copying and
13574     * renaming logic.
13575     */
13576    class AsecInstallArgs extends InstallArgs {
13577        static final String RES_FILE_NAME = "pkg.apk";
13578        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13579
13580        String cid;
13581        String packagePath;
13582        String resourcePath;
13583
13584        /** New install */
13585        AsecInstallArgs(InstallParams params) {
13586            super(params.origin, params.move, params.observer, params.installFlags,
13587                    params.installerPackageName, params.volumeUuid,
13588                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13589                    params.grantedRuntimePermissions,
13590                    params.traceMethod, params.traceCookie, params.certificates);
13591        }
13592
13593        /** Existing install */
13594        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13595                        boolean isExternal, boolean isForwardLocked) {
13596            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13597              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13598                    instructionSets, null, null, null, 0, null /*certificates*/);
13599            // Hackily pretend we're still looking at a full code path
13600            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13601                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13602            }
13603
13604            // Extract cid from fullCodePath
13605            int eidx = fullCodePath.lastIndexOf("/");
13606            String subStr1 = fullCodePath.substring(0, eidx);
13607            int sidx = subStr1.lastIndexOf("/");
13608            cid = subStr1.substring(sidx+1, eidx);
13609            setMountPath(subStr1);
13610        }
13611
13612        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13613            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13614              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13615                    instructionSets, null, null, null, 0, null /*certificates*/);
13616            this.cid = cid;
13617            setMountPath(PackageHelper.getSdDir(cid));
13618        }
13619
13620        void createCopyFile() {
13621            cid = mInstallerService.allocateExternalStageCidLegacy();
13622        }
13623
13624        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13625            if (origin.staged && origin.cid != null) {
13626                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13627                cid = origin.cid;
13628                setMountPath(PackageHelper.getSdDir(cid));
13629                return PackageManager.INSTALL_SUCCEEDED;
13630            }
13631
13632            if (temp) {
13633                createCopyFile();
13634            } else {
13635                /*
13636                 * Pre-emptively destroy the container since it's destroyed if
13637                 * copying fails due to it existing anyway.
13638                 */
13639                PackageHelper.destroySdDir(cid);
13640            }
13641
13642            final String newMountPath = imcs.copyPackageToContainer(
13643                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13644                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13645
13646            if (newMountPath != null) {
13647                setMountPath(newMountPath);
13648                return PackageManager.INSTALL_SUCCEEDED;
13649            } else {
13650                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13651            }
13652        }
13653
13654        @Override
13655        String getCodePath() {
13656            return packagePath;
13657        }
13658
13659        @Override
13660        String getResourcePath() {
13661            return resourcePath;
13662        }
13663
13664        int doPreInstall(int status) {
13665            if (status != PackageManager.INSTALL_SUCCEEDED) {
13666                // Destroy container
13667                PackageHelper.destroySdDir(cid);
13668            } else {
13669                boolean mounted = PackageHelper.isContainerMounted(cid);
13670                if (!mounted) {
13671                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13672                            Process.SYSTEM_UID);
13673                    if (newMountPath != null) {
13674                        setMountPath(newMountPath);
13675                    } else {
13676                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13677                    }
13678                }
13679            }
13680            return status;
13681        }
13682
13683        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13684            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13685            String newMountPath = null;
13686            if (PackageHelper.isContainerMounted(cid)) {
13687                // Unmount the container
13688                if (!PackageHelper.unMountSdDir(cid)) {
13689                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13690                    return false;
13691                }
13692            }
13693            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13694                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13695                        " which might be stale. Will try to clean up.");
13696                // Clean up the stale container and proceed to recreate.
13697                if (!PackageHelper.destroySdDir(newCacheId)) {
13698                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13699                    return false;
13700                }
13701                // Successfully cleaned up stale container. Try to rename again.
13702                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13703                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13704                            + " inspite of cleaning it up.");
13705                    return false;
13706                }
13707            }
13708            if (!PackageHelper.isContainerMounted(newCacheId)) {
13709                Slog.w(TAG, "Mounting container " + newCacheId);
13710                newMountPath = PackageHelper.mountSdDir(newCacheId,
13711                        getEncryptKey(), Process.SYSTEM_UID);
13712            } else {
13713                newMountPath = PackageHelper.getSdDir(newCacheId);
13714            }
13715            if (newMountPath == null) {
13716                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13717                return false;
13718            }
13719            Log.i(TAG, "Succesfully renamed " + cid +
13720                    " to " + newCacheId +
13721                    " at new path: " + newMountPath);
13722            cid = newCacheId;
13723
13724            final File beforeCodeFile = new File(packagePath);
13725            setMountPath(newMountPath);
13726            final File afterCodeFile = new File(packagePath);
13727
13728            // Reflect the rename in scanned details
13729            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13730            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13731                    afterCodeFile, pkg.baseCodePath));
13732            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13733                    afterCodeFile, pkg.splitCodePaths));
13734
13735            // Reflect the rename in app info
13736            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13737            pkg.setApplicationInfoCodePath(pkg.codePath);
13738            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13739            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13740            pkg.setApplicationInfoResourcePath(pkg.codePath);
13741            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13742            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13743
13744            return true;
13745        }
13746
13747        private void setMountPath(String mountPath) {
13748            final File mountFile = new File(mountPath);
13749
13750            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13751            if (monolithicFile.exists()) {
13752                packagePath = monolithicFile.getAbsolutePath();
13753                if (isFwdLocked()) {
13754                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13755                } else {
13756                    resourcePath = packagePath;
13757                }
13758            } else {
13759                packagePath = mountFile.getAbsolutePath();
13760                resourcePath = packagePath;
13761            }
13762        }
13763
13764        int doPostInstall(int status, int uid) {
13765            if (status != PackageManager.INSTALL_SUCCEEDED) {
13766                cleanUp();
13767            } else {
13768                final int groupOwner;
13769                final String protectedFile;
13770                if (isFwdLocked()) {
13771                    groupOwner = UserHandle.getSharedAppGid(uid);
13772                    protectedFile = RES_FILE_NAME;
13773                } else {
13774                    groupOwner = -1;
13775                    protectedFile = null;
13776                }
13777
13778                if (uid < Process.FIRST_APPLICATION_UID
13779                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13780                    Slog.e(TAG, "Failed to finalize " + cid);
13781                    PackageHelper.destroySdDir(cid);
13782                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13783                }
13784
13785                boolean mounted = PackageHelper.isContainerMounted(cid);
13786                if (!mounted) {
13787                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13788                }
13789            }
13790            return status;
13791        }
13792
13793        private void cleanUp() {
13794            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13795
13796            // Destroy secure container
13797            PackageHelper.destroySdDir(cid);
13798        }
13799
13800        private List<String> getAllCodePaths() {
13801            final File codeFile = new File(getCodePath());
13802            if (codeFile != null && codeFile.exists()) {
13803                try {
13804                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13805                    return pkg.getAllCodePaths();
13806                } catch (PackageParserException e) {
13807                    // Ignored; we tried our best
13808                }
13809            }
13810            return Collections.EMPTY_LIST;
13811        }
13812
13813        void cleanUpResourcesLI() {
13814            // Enumerate all code paths before deleting
13815            cleanUpResourcesLI(getAllCodePaths());
13816        }
13817
13818        private void cleanUpResourcesLI(List<String> allCodePaths) {
13819            cleanUp();
13820            removeDexFiles(allCodePaths, instructionSets);
13821        }
13822
13823        String getPackageName() {
13824            return getAsecPackageName(cid);
13825        }
13826
13827        boolean doPostDeleteLI(boolean delete) {
13828            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13829            final List<String> allCodePaths = getAllCodePaths();
13830            boolean mounted = PackageHelper.isContainerMounted(cid);
13831            if (mounted) {
13832                // Unmount first
13833                if (PackageHelper.unMountSdDir(cid)) {
13834                    mounted = false;
13835                }
13836            }
13837            if (!mounted && delete) {
13838                cleanUpResourcesLI(allCodePaths);
13839            }
13840            return !mounted;
13841        }
13842
13843        @Override
13844        int doPreCopy() {
13845            if (isFwdLocked()) {
13846                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13847                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13848                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13849                }
13850            }
13851
13852            return PackageManager.INSTALL_SUCCEEDED;
13853        }
13854
13855        @Override
13856        int doPostCopy(int uid) {
13857            if (isFwdLocked()) {
13858                if (uid < Process.FIRST_APPLICATION_UID
13859                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13860                                RES_FILE_NAME)) {
13861                    Slog.e(TAG, "Failed to finalize " + cid);
13862                    PackageHelper.destroySdDir(cid);
13863                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13864                }
13865            }
13866
13867            return PackageManager.INSTALL_SUCCEEDED;
13868        }
13869    }
13870
13871    /**
13872     * Logic to handle movement of existing installed applications.
13873     */
13874    class MoveInstallArgs extends InstallArgs {
13875        private File codeFile;
13876        private File resourceFile;
13877
13878        /** New install */
13879        MoveInstallArgs(InstallParams params) {
13880            super(params.origin, params.move, params.observer, params.installFlags,
13881                    params.installerPackageName, params.volumeUuid,
13882                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13883                    params.grantedRuntimePermissions,
13884                    params.traceMethod, params.traceCookie, params.certificates);
13885        }
13886
13887        int copyApk(IMediaContainerService imcs, boolean temp) {
13888            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13889                    + move.fromUuid + " to " + move.toUuid);
13890            synchronized (mInstaller) {
13891                try {
13892                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13893                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13894                } catch (InstallerException e) {
13895                    Slog.w(TAG, "Failed to move app", e);
13896                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13897                }
13898            }
13899
13900            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13901            resourceFile = codeFile;
13902            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13903
13904            return PackageManager.INSTALL_SUCCEEDED;
13905        }
13906
13907        int doPreInstall(int status) {
13908            if (status != PackageManager.INSTALL_SUCCEEDED) {
13909                cleanUp(move.toUuid);
13910            }
13911            return status;
13912        }
13913
13914        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13915            if (status != PackageManager.INSTALL_SUCCEEDED) {
13916                cleanUp(move.toUuid);
13917                return false;
13918            }
13919
13920            // Reflect the move in app info
13921            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13922            pkg.setApplicationInfoCodePath(pkg.codePath);
13923            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13924            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13925            pkg.setApplicationInfoResourcePath(pkg.codePath);
13926            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13927            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13928
13929            return true;
13930        }
13931
13932        int doPostInstall(int status, int uid) {
13933            if (status == PackageManager.INSTALL_SUCCEEDED) {
13934                cleanUp(move.fromUuid);
13935            } else {
13936                cleanUp(move.toUuid);
13937            }
13938            return status;
13939        }
13940
13941        @Override
13942        String getCodePath() {
13943            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13944        }
13945
13946        @Override
13947        String getResourcePath() {
13948            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13949        }
13950
13951        private boolean cleanUp(String volumeUuid) {
13952            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13953                    move.dataAppName);
13954            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13955            final int[] userIds = sUserManager.getUserIds();
13956            synchronized (mInstallLock) {
13957                // Clean up both app data and code
13958                // All package moves are frozen until finished
13959                for (int userId : userIds) {
13960                    try {
13961                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13962                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13963                    } catch (InstallerException e) {
13964                        Slog.w(TAG, String.valueOf(e));
13965                    }
13966                }
13967                removeCodePathLI(codeFile);
13968            }
13969            return true;
13970        }
13971
13972        void cleanUpResourcesLI() {
13973            throw new UnsupportedOperationException();
13974        }
13975
13976        boolean doPostDeleteLI(boolean delete) {
13977            throw new UnsupportedOperationException();
13978        }
13979    }
13980
13981    static String getAsecPackageName(String packageCid) {
13982        int idx = packageCid.lastIndexOf("-");
13983        if (idx == -1) {
13984            return packageCid;
13985        }
13986        return packageCid.substring(0, idx);
13987    }
13988
13989    // Utility method used to create code paths based on package name and available index.
13990    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13991        String idxStr = "";
13992        int idx = 1;
13993        // Fall back to default value of idx=1 if prefix is not
13994        // part of oldCodePath
13995        if (oldCodePath != null) {
13996            String subStr = oldCodePath;
13997            // Drop the suffix right away
13998            if (suffix != null && subStr.endsWith(suffix)) {
13999                subStr = subStr.substring(0, subStr.length() - suffix.length());
14000            }
14001            // If oldCodePath already contains prefix find out the
14002            // ending index to either increment or decrement.
14003            int sidx = subStr.lastIndexOf(prefix);
14004            if (sidx != -1) {
14005                subStr = subStr.substring(sidx + prefix.length());
14006                if (subStr != null) {
14007                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14008                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14009                    }
14010                    try {
14011                        idx = Integer.parseInt(subStr);
14012                        if (idx <= 1) {
14013                            idx++;
14014                        } else {
14015                            idx--;
14016                        }
14017                    } catch(NumberFormatException e) {
14018                    }
14019                }
14020            }
14021        }
14022        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14023        return prefix + idxStr;
14024    }
14025
14026    private File getNextCodePath(File targetDir, String packageName) {
14027        int suffix = 1;
14028        File result;
14029        do {
14030            result = new File(targetDir, packageName + "-" + suffix);
14031            suffix++;
14032        } while (result.exists());
14033        return result;
14034    }
14035
14036    // Utility method that returns the relative package path with respect
14037    // to the installation directory. Like say for /data/data/com.test-1.apk
14038    // string com.test-1 is returned.
14039    static String deriveCodePathName(String codePath) {
14040        if (codePath == null) {
14041            return null;
14042        }
14043        final File codeFile = new File(codePath);
14044        final String name = codeFile.getName();
14045        if (codeFile.isDirectory()) {
14046            return name;
14047        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14048            final int lastDot = name.lastIndexOf('.');
14049            return name.substring(0, lastDot);
14050        } else {
14051            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14052            return null;
14053        }
14054    }
14055
14056    static class PackageInstalledInfo {
14057        String name;
14058        int uid;
14059        // The set of users that originally had this package installed.
14060        int[] origUsers;
14061        // The set of users that now have this package installed.
14062        int[] newUsers;
14063        PackageParser.Package pkg;
14064        int returnCode;
14065        String returnMsg;
14066        PackageRemovedInfo removedInfo;
14067        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14068
14069        public void setError(int code, String msg) {
14070            setReturnCode(code);
14071            setReturnMessage(msg);
14072            Slog.w(TAG, msg);
14073        }
14074
14075        public void setError(String msg, PackageParserException e) {
14076            setReturnCode(e.error);
14077            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14078            Slog.w(TAG, msg, e);
14079        }
14080
14081        public void setError(String msg, PackageManagerException e) {
14082            returnCode = e.error;
14083            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14084            Slog.w(TAG, msg, e);
14085        }
14086
14087        public void setReturnCode(int returnCode) {
14088            this.returnCode = returnCode;
14089            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14090            for (int i = 0; i < childCount; i++) {
14091                addedChildPackages.valueAt(i).returnCode = returnCode;
14092            }
14093        }
14094
14095        private void setReturnMessage(String returnMsg) {
14096            this.returnMsg = returnMsg;
14097            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14098            for (int i = 0; i < childCount; i++) {
14099                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14100            }
14101        }
14102
14103        // In some error cases we want to convey more info back to the observer
14104        String origPackage;
14105        String origPermission;
14106    }
14107
14108    /*
14109     * Install a non-existing package.
14110     */
14111    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14112            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14113            PackageInstalledInfo res) {
14114        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14115
14116        // Remember this for later, in case we need to rollback this install
14117        String pkgName = pkg.packageName;
14118
14119        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14120
14121        synchronized(mPackages) {
14122            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14123                // A package with the same name is already installed, though
14124                // it has been renamed to an older name.  The package we
14125                // are trying to install should be installed as an update to
14126                // the existing one, but that has not been requested, so bail.
14127                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14128                        + " without first uninstalling package running as "
14129                        + mSettings.mRenamedPackages.get(pkgName));
14130                return;
14131            }
14132            if (mPackages.containsKey(pkgName)) {
14133                // Don't allow installation over an existing package with the same name.
14134                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14135                        + " without first uninstalling.");
14136                return;
14137            }
14138        }
14139
14140        try {
14141            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14142                    System.currentTimeMillis(), user);
14143
14144            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14145
14146            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14147                prepareAppDataAfterInstallLIF(newPackage);
14148
14149            } else {
14150                // Remove package from internal structures, but keep around any
14151                // data that might have already existed
14152                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14153                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14154            }
14155        } catch (PackageManagerException e) {
14156            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14157        }
14158
14159        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14160    }
14161
14162    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14163        // Can't rotate keys during boot or if sharedUser.
14164        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14165                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14166            return false;
14167        }
14168        // app is using upgradeKeySets; make sure all are valid
14169        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14170        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14171        for (int i = 0; i < upgradeKeySets.length; i++) {
14172            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14173                Slog.wtf(TAG, "Package "
14174                         + (oldPs.name != null ? oldPs.name : "<null>")
14175                         + " contains upgrade-key-set reference to unknown key-set: "
14176                         + upgradeKeySets[i]
14177                         + " reverting to signatures check.");
14178                return false;
14179            }
14180        }
14181        return true;
14182    }
14183
14184    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14185        // Upgrade keysets are being used.  Determine if new package has a superset of the
14186        // required keys.
14187        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14188        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14189        for (int i = 0; i < upgradeKeySets.length; i++) {
14190            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14191            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14192                return true;
14193            }
14194        }
14195        return false;
14196    }
14197
14198    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14199        try (DigestInputStream digestStream =
14200                new DigestInputStream(new FileInputStream(file), digest)) {
14201            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14202        }
14203    }
14204
14205    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14206            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14207        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14208
14209        final PackageParser.Package oldPackage;
14210        final String pkgName = pkg.packageName;
14211        final int[] allUsers;
14212        final int[] installedUsers;
14213
14214        synchronized(mPackages) {
14215            oldPackage = mPackages.get(pkgName);
14216            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14217
14218            // don't allow upgrade to target a release SDK from a pre-release SDK
14219            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14220                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14221            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14222                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14223            if (oldTargetsPreRelease
14224                    && !newTargetsPreRelease
14225                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14226                Slog.w(TAG, "Can't install package targeting released sdk");
14227                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14228                return;
14229            }
14230
14231            // don't allow an upgrade from full to ephemeral
14232            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14233            if (isEphemeral && !oldIsEphemeral) {
14234                // can't downgrade from full to ephemeral
14235                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14236                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14237                return;
14238            }
14239
14240            // verify signatures are valid
14241            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14242            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14243                if (!checkUpgradeKeySetLP(ps, pkg)) {
14244                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14245                            "New package not signed by keys specified by upgrade-keysets: "
14246                                    + pkgName);
14247                    return;
14248                }
14249            } else {
14250                // default to original signature matching
14251                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14252                        != PackageManager.SIGNATURE_MATCH) {
14253                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14254                            "New package has a different signature: " + pkgName);
14255                    return;
14256                }
14257            }
14258
14259            // don't allow a system upgrade unless the upgrade hash matches
14260            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14261                byte[] digestBytes = null;
14262                try {
14263                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14264                    updateDigest(digest, new File(pkg.baseCodePath));
14265                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14266                        for (String path : pkg.splitCodePaths) {
14267                            updateDigest(digest, new File(path));
14268                        }
14269                    }
14270                    digestBytes = digest.digest();
14271                } catch (NoSuchAlgorithmException | IOException e) {
14272                    res.setError(INSTALL_FAILED_INVALID_APK,
14273                            "Could not compute hash: " + pkgName);
14274                    return;
14275                }
14276                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14277                    res.setError(INSTALL_FAILED_INVALID_APK,
14278                            "New package fails restrict-update check: " + pkgName);
14279                    return;
14280                }
14281                // retain upgrade restriction
14282                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14283            }
14284
14285            // Check for shared user id changes
14286            String invalidPackageName =
14287                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14288            if (invalidPackageName != null) {
14289                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14290                        "Package " + invalidPackageName + " tried to change user "
14291                                + oldPackage.mSharedUserId);
14292                return;
14293            }
14294
14295            // In case of rollback, remember per-user/profile install state
14296            allUsers = sUserManager.getUserIds();
14297            installedUsers = ps.queryInstalledUsers(allUsers, true);
14298        }
14299
14300        // Update what is removed
14301        res.removedInfo = new PackageRemovedInfo();
14302        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14303        res.removedInfo.removedPackage = oldPackage.packageName;
14304        res.removedInfo.isUpdate = true;
14305        res.removedInfo.origUsers = installedUsers;
14306        final int childCount = (oldPackage.childPackages != null)
14307                ? oldPackage.childPackages.size() : 0;
14308        for (int i = 0; i < childCount; i++) {
14309            boolean childPackageUpdated = false;
14310            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14311            if (res.addedChildPackages != null) {
14312                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14313                if (childRes != null) {
14314                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14315                    childRes.removedInfo.removedPackage = childPkg.packageName;
14316                    childRes.removedInfo.isUpdate = true;
14317                    childPackageUpdated = true;
14318                }
14319            }
14320            if (!childPackageUpdated) {
14321                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14322                childRemovedRes.removedPackage = childPkg.packageName;
14323                childRemovedRes.isUpdate = false;
14324                childRemovedRes.dataRemoved = true;
14325                synchronized (mPackages) {
14326                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14327                    if (childPs != null) {
14328                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14329                    }
14330                }
14331                if (res.removedInfo.removedChildPackages == null) {
14332                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14333                }
14334                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14335            }
14336        }
14337
14338        boolean sysPkg = (isSystemApp(oldPackage));
14339        if (sysPkg) {
14340            // Set the system/privileged flags as needed
14341            final boolean privileged =
14342                    (oldPackage.applicationInfo.privateFlags
14343                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14344            final int systemPolicyFlags = policyFlags
14345                    | PackageParser.PARSE_IS_SYSTEM
14346                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14347
14348            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14349                    user, allUsers, installerPackageName, res);
14350        } else {
14351            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14352                    user, allUsers, installerPackageName, res);
14353        }
14354    }
14355
14356    public List<String> getPreviousCodePaths(String packageName) {
14357        final PackageSetting ps = mSettings.mPackages.get(packageName);
14358        final List<String> result = new ArrayList<String>();
14359        if (ps != null && ps.oldCodePaths != null) {
14360            result.addAll(ps.oldCodePaths);
14361        }
14362        return result;
14363    }
14364
14365    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14366            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14367            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14368        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14369                + deletedPackage);
14370
14371        String pkgName = deletedPackage.packageName;
14372        boolean deletedPkg = true;
14373        boolean addedPkg = false;
14374        boolean updatedSettings = false;
14375        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14376        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14377                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14378
14379        final long origUpdateTime = (pkg.mExtras != null)
14380                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14381
14382        // First delete the existing package while retaining the data directory
14383        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14384                res.removedInfo, true, pkg)) {
14385            // If the existing package wasn't successfully deleted
14386            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14387            deletedPkg = false;
14388        } else {
14389            // Successfully deleted the old package; proceed with replace.
14390
14391            // If deleted package lived in a container, give users a chance to
14392            // relinquish resources before killing.
14393            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14394                if (DEBUG_INSTALL) {
14395                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14396                }
14397                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14398                final ArrayList<String> pkgList = new ArrayList<String>(1);
14399                pkgList.add(deletedPackage.applicationInfo.packageName);
14400                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14401            }
14402
14403            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14404                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14405            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14406
14407            try {
14408                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14409                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14410                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14411
14412                // Update the in-memory copy of the previous code paths.
14413                PackageSetting ps = mSettings.mPackages.get(pkgName);
14414                if (!killApp) {
14415                    if (ps.oldCodePaths == null) {
14416                        ps.oldCodePaths = new ArraySet<>();
14417                    }
14418                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14419                    if (deletedPackage.splitCodePaths != null) {
14420                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14421                    }
14422                } else {
14423                    ps.oldCodePaths = null;
14424                }
14425                if (ps.childPackageNames != null) {
14426                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14427                        final String childPkgName = ps.childPackageNames.get(i);
14428                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14429                        childPs.oldCodePaths = ps.oldCodePaths;
14430                    }
14431                }
14432                prepareAppDataAfterInstallLIF(newPackage);
14433                addedPkg = true;
14434            } catch (PackageManagerException e) {
14435                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14436            }
14437        }
14438
14439        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14440            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14441
14442            // Revert all internal state mutations and added folders for the failed install
14443            if (addedPkg) {
14444                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14445                        res.removedInfo, true, null);
14446            }
14447
14448            // Restore the old package
14449            if (deletedPkg) {
14450                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14451                File restoreFile = new File(deletedPackage.codePath);
14452                // Parse old package
14453                boolean oldExternal = isExternal(deletedPackage);
14454                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14455                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14456                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14457                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14458                try {
14459                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14460                            null);
14461                } catch (PackageManagerException e) {
14462                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14463                            + e.getMessage());
14464                    return;
14465                }
14466
14467                synchronized (mPackages) {
14468                    // Ensure the installer package name up to date
14469                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14470
14471                    // Update permissions for restored package
14472                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14473
14474                    mSettings.writeLPr();
14475                }
14476
14477                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14478            }
14479        } else {
14480            synchronized (mPackages) {
14481                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14482                if (ps != null) {
14483                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14484                    if (res.removedInfo.removedChildPackages != null) {
14485                        final int childCount = res.removedInfo.removedChildPackages.size();
14486                        // Iterate in reverse as we may modify the collection
14487                        for (int i = childCount - 1; i >= 0; i--) {
14488                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14489                            if (res.addedChildPackages.containsKey(childPackageName)) {
14490                                res.removedInfo.removedChildPackages.removeAt(i);
14491                            } else {
14492                                PackageRemovedInfo childInfo = res.removedInfo
14493                                        .removedChildPackages.valueAt(i);
14494                                childInfo.removedForAllUsers = mPackages.get(
14495                                        childInfo.removedPackage) == null;
14496                            }
14497                        }
14498                    }
14499                }
14500            }
14501        }
14502    }
14503
14504    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14505            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14506            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14507        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14508                + ", old=" + deletedPackage);
14509
14510        final boolean disabledSystem;
14511
14512        // Remove existing system package
14513        removePackageLI(deletedPackage, true);
14514
14515        synchronized (mPackages) {
14516            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14517        }
14518        if (!disabledSystem) {
14519            // We didn't need to disable the .apk as a current system package,
14520            // which means we are replacing another update that is already
14521            // installed.  We need to make sure to delete the older one's .apk.
14522            res.removedInfo.args = createInstallArgsForExisting(0,
14523                    deletedPackage.applicationInfo.getCodePath(),
14524                    deletedPackage.applicationInfo.getResourcePath(),
14525                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14526        } else {
14527            res.removedInfo.args = null;
14528        }
14529
14530        // Successfully disabled the old package. Now proceed with re-installation
14531        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14532                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14533        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14534
14535        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14536        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14537                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14538
14539        PackageParser.Package newPackage = null;
14540        try {
14541            // Add the package to the internal data structures
14542            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14543
14544            // Set the update and install times
14545            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14546            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14547                    System.currentTimeMillis());
14548
14549            // Update the package dynamic state if succeeded
14550            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14551                // Now that the install succeeded make sure we remove data
14552                // directories for any child package the update removed.
14553                final int deletedChildCount = (deletedPackage.childPackages != null)
14554                        ? deletedPackage.childPackages.size() : 0;
14555                final int newChildCount = (newPackage.childPackages != null)
14556                        ? newPackage.childPackages.size() : 0;
14557                for (int i = 0; i < deletedChildCount; i++) {
14558                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14559                    boolean childPackageDeleted = true;
14560                    for (int j = 0; j < newChildCount; j++) {
14561                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14562                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14563                            childPackageDeleted = false;
14564                            break;
14565                        }
14566                    }
14567                    if (childPackageDeleted) {
14568                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14569                                deletedChildPkg.packageName);
14570                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14571                            PackageRemovedInfo removedChildRes = res.removedInfo
14572                                    .removedChildPackages.get(deletedChildPkg.packageName);
14573                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14574                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14575                        }
14576                    }
14577                }
14578
14579                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14580                prepareAppDataAfterInstallLIF(newPackage);
14581            }
14582        } catch (PackageManagerException e) {
14583            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14584            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14585        }
14586
14587        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14588            // Re installation failed. Restore old information
14589            // Remove new pkg information
14590            if (newPackage != null) {
14591                removeInstalledPackageLI(newPackage, true);
14592            }
14593            // Add back the old system package
14594            try {
14595                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14596            } catch (PackageManagerException e) {
14597                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14598            }
14599
14600            synchronized (mPackages) {
14601                if (disabledSystem) {
14602                    enableSystemPackageLPw(deletedPackage);
14603                }
14604
14605                // Ensure the installer package name up to date
14606                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14607
14608                // Update permissions for restored package
14609                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14610
14611                mSettings.writeLPr();
14612            }
14613
14614            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14615                    + " after failed upgrade");
14616        }
14617    }
14618
14619    /**
14620     * Checks whether the parent or any of the child packages have a change shared
14621     * user. For a package to be a valid update the shred users of the parent and
14622     * the children should match. We may later support changing child shared users.
14623     * @param oldPkg The updated package.
14624     * @param newPkg The update package.
14625     * @return The shared user that change between the versions.
14626     */
14627    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14628            PackageParser.Package newPkg) {
14629        // Check parent shared user
14630        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14631            return newPkg.packageName;
14632        }
14633        // Check child shared users
14634        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14635        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14636        for (int i = 0; i < newChildCount; i++) {
14637            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14638            // If this child was present, did it have the same shared user?
14639            for (int j = 0; j < oldChildCount; j++) {
14640                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14641                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14642                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14643                    return newChildPkg.packageName;
14644                }
14645            }
14646        }
14647        return null;
14648    }
14649
14650    private void removeNativeBinariesLI(PackageSetting ps) {
14651        // Remove the lib path for the parent package
14652        if (ps != null) {
14653            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14654            // Remove the lib path for the child packages
14655            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14656            for (int i = 0; i < childCount; i++) {
14657                PackageSetting childPs = null;
14658                synchronized (mPackages) {
14659                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14660                }
14661                if (childPs != null) {
14662                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14663                            .legacyNativeLibraryPathString);
14664                }
14665            }
14666        }
14667    }
14668
14669    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14670        // Enable the parent package
14671        mSettings.enableSystemPackageLPw(pkg.packageName);
14672        // Enable the child packages
14673        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14674        for (int i = 0; i < childCount; i++) {
14675            PackageParser.Package childPkg = pkg.childPackages.get(i);
14676            mSettings.enableSystemPackageLPw(childPkg.packageName);
14677        }
14678    }
14679
14680    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14681            PackageParser.Package newPkg) {
14682        // Disable the parent package (parent always replaced)
14683        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14684        // Disable the child packages
14685        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14686        for (int i = 0; i < childCount; i++) {
14687            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14688            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14689            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14690        }
14691        return disabled;
14692    }
14693
14694    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14695            String installerPackageName) {
14696        // Enable the parent package
14697        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14698        // Enable the child packages
14699        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14700        for (int i = 0; i < childCount; i++) {
14701            PackageParser.Package childPkg = pkg.childPackages.get(i);
14702            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14703        }
14704    }
14705
14706    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14707        // Collect all used permissions in the UID
14708        ArraySet<String> usedPermissions = new ArraySet<>();
14709        final int packageCount = su.packages.size();
14710        for (int i = 0; i < packageCount; i++) {
14711            PackageSetting ps = su.packages.valueAt(i);
14712            if (ps.pkg == null) {
14713                continue;
14714            }
14715            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14716            for (int j = 0; j < requestedPermCount; j++) {
14717                String permission = ps.pkg.requestedPermissions.get(j);
14718                BasePermission bp = mSettings.mPermissions.get(permission);
14719                if (bp != null) {
14720                    usedPermissions.add(permission);
14721                }
14722            }
14723        }
14724
14725        PermissionsState permissionsState = su.getPermissionsState();
14726        // Prune install permissions
14727        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14728        final int installPermCount = installPermStates.size();
14729        for (int i = installPermCount - 1; i >= 0;  i--) {
14730            PermissionState permissionState = installPermStates.get(i);
14731            if (!usedPermissions.contains(permissionState.getName())) {
14732                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14733                if (bp != null) {
14734                    permissionsState.revokeInstallPermission(bp);
14735                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14736                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14737                }
14738            }
14739        }
14740
14741        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14742
14743        // Prune runtime permissions
14744        for (int userId : allUserIds) {
14745            List<PermissionState> runtimePermStates = permissionsState
14746                    .getRuntimePermissionStates(userId);
14747            final int runtimePermCount = runtimePermStates.size();
14748            for (int i = runtimePermCount - 1; i >= 0; i--) {
14749                PermissionState permissionState = runtimePermStates.get(i);
14750                if (!usedPermissions.contains(permissionState.getName())) {
14751                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14752                    if (bp != null) {
14753                        permissionsState.revokeRuntimePermission(bp, userId);
14754                        permissionsState.updatePermissionFlags(bp, userId,
14755                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14756                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14757                                runtimePermissionChangedUserIds, userId);
14758                    }
14759                }
14760            }
14761        }
14762
14763        return runtimePermissionChangedUserIds;
14764    }
14765
14766    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14767            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14768        // Update the parent package setting
14769        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14770                res, user);
14771        // Update the child packages setting
14772        final int childCount = (newPackage.childPackages != null)
14773                ? newPackage.childPackages.size() : 0;
14774        for (int i = 0; i < childCount; i++) {
14775            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14776            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14777            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14778                    childRes.origUsers, childRes, user);
14779        }
14780    }
14781
14782    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14783            String installerPackageName, int[] allUsers, int[] installedForUsers,
14784            PackageInstalledInfo res, UserHandle user) {
14785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14786
14787        String pkgName = newPackage.packageName;
14788        synchronized (mPackages) {
14789            //write settings. the installStatus will be incomplete at this stage.
14790            //note that the new package setting would have already been
14791            //added to mPackages. It hasn't been persisted yet.
14792            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14793            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14794            mSettings.writeLPr();
14795            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14796        }
14797
14798        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14799        synchronized (mPackages) {
14800            updatePermissionsLPw(newPackage.packageName, newPackage,
14801                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14802                            ? UPDATE_PERMISSIONS_ALL : 0));
14803            // For system-bundled packages, we assume that installing an upgraded version
14804            // of the package implies that the user actually wants to run that new code,
14805            // so we enable the package.
14806            PackageSetting ps = mSettings.mPackages.get(pkgName);
14807            final int userId = user.getIdentifier();
14808            if (ps != null) {
14809                if (isSystemApp(newPackage)) {
14810                    if (DEBUG_INSTALL) {
14811                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14812                    }
14813                    // Enable system package for requested users
14814                    if (res.origUsers != null) {
14815                        for (int origUserId : res.origUsers) {
14816                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14817                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14818                                        origUserId, installerPackageName);
14819                            }
14820                        }
14821                    }
14822                    // Also convey the prior install/uninstall state
14823                    if (allUsers != null && installedForUsers != null) {
14824                        for (int currentUserId : allUsers) {
14825                            final boolean installed = ArrayUtils.contains(
14826                                    installedForUsers, currentUserId);
14827                            if (DEBUG_INSTALL) {
14828                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14829                            }
14830                            ps.setInstalled(installed, currentUserId);
14831                        }
14832                        // these install state changes will be persisted in the
14833                        // upcoming call to mSettings.writeLPr().
14834                    }
14835                }
14836                // It's implied that when a user requests installation, they want the app to be
14837                // installed and enabled.
14838                if (userId != UserHandle.USER_ALL) {
14839                    ps.setInstalled(true, userId);
14840                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14841                }
14842            }
14843            res.name = pkgName;
14844            res.uid = newPackage.applicationInfo.uid;
14845            res.pkg = newPackage;
14846            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14847            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14848            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14849            //to update install status
14850            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14851            mSettings.writeLPr();
14852            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14853        }
14854
14855        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14856    }
14857
14858    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14859        try {
14860            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14861            installPackageLI(args, res);
14862        } finally {
14863            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14864        }
14865    }
14866
14867    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14868        final int installFlags = args.installFlags;
14869        final String installerPackageName = args.installerPackageName;
14870        final String volumeUuid = args.volumeUuid;
14871        final File tmpPackageFile = new File(args.getCodePath());
14872        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14873        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14874                || (args.volumeUuid != null));
14875        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14876        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14877        boolean replace = false;
14878        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14879        if (args.move != null) {
14880            // moving a complete application; perform an initial scan on the new install location
14881            scanFlags |= SCAN_INITIAL;
14882        }
14883        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14884            scanFlags |= SCAN_DONT_KILL_APP;
14885        }
14886
14887        // Result object to be returned
14888        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14889
14890        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14891
14892        // Sanity check
14893        if (ephemeral && (forwardLocked || onExternal)) {
14894            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14895                    + " external=" + onExternal);
14896            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14897            return;
14898        }
14899
14900        // Retrieve PackageSettings and parse package
14901        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14902                | PackageParser.PARSE_ENFORCE_CODE
14903                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14904                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14905                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14906                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14907        PackageParser pp = new PackageParser();
14908        pp.setSeparateProcesses(mSeparateProcesses);
14909        pp.setDisplayMetrics(mMetrics);
14910
14911        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14912        final PackageParser.Package pkg;
14913        try {
14914            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14915        } catch (PackageParserException e) {
14916            res.setError("Failed parse during installPackageLI", e);
14917            return;
14918        } finally {
14919            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14920        }
14921
14922        // If we are installing a clustered package add results for the children
14923        if (pkg.childPackages != null) {
14924            synchronized (mPackages) {
14925                final int childCount = pkg.childPackages.size();
14926                for (int i = 0; i < childCount; i++) {
14927                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14928                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14929                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14930                    childRes.pkg = childPkg;
14931                    childRes.name = childPkg.packageName;
14932                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14933                    if (childPs != null) {
14934                        childRes.origUsers = childPs.queryInstalledUsers(
14935                                sUserManager.getUserIds(), true);
14936                    }
14937                    if ((mPackages.containsKey(childPkg.packageName))) {
14938                        childRes.removedInfo = new PackageRemovedInfo();
14939                        childRes.removedInfo.removedPackage = childPkg.packageName;
14940                    }
14941                    if (res.addedChildPackages == null) {
14942                        res.addedChildPackages = new ArrayMap<>();
14943                    }
14944                    res.addedChildPackages.put(childPkg.packageName, childRes);
14945                }
14946            }
14947        }
14948
14949        // If package doesn't declare API override, mark that we have an install
14950        // time CPU ABI override.
14951        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14952            pkg.cpuAbiOverride = args.abiOverride;
14953        }
14954
14955        String pkgName = res.name = pkg.packageName;
14956        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14957            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14958                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14959                return;
14960            }
14961        }
14962
14963        try {
14964            // either use what we've been given or parse directly from the APK
14965            if (args.certificates != null) {
14966                try {
14967                    PackageParser.populateCertificates(pkg, args.certificates);
14968                } catch (PackageParserException e) {
14969                    // there was something wrong with the certificates we were given;
14970                    // try to pull them from the APK
14971                    PackageParser.collectCertificates(pkg, parseFlags);
14972                }
14973            } else {
14974                PackageParser.collectCertificates(pkg, parseFlags);
14975            }
14976        } catch (PackageParserException e) {
14977            res.setError("Failed collect during installPackageLI", e);
14978            return;
14979        }
14980
14981        // Get rid of all references to package scan path via parser.
14982        pp = null;
14983        String oldCodePath = null;
14984        boolean systemApp = false;
14985        synchronized (mPackages) {
14986            // Check if installing already existing package
14987            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14988                String oldName = mSettings.mRenamedPackages.get(pkgName);
14989                if (pkg.mOriginalPackages != null
14990                        && pkg.mOriginalPackages.contains(oldName)
14991                        && mPackages.containsKey(oldName)) {
14992                    // This package is derived from an original package,
14993                    // and this device has been updating from that original
14994                    // name.  We must continue using the original name, so
14995                    // rename the new package here.
14996                    pkg.setPackageName(oldName);
14997                    pkgName = pkg.packageName;
14998                    replace = true;
14999                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15000                            + oldName + " pkgName=" + pkgName);
15001                } else if (mPackages.containsKey(pkgName)) {
15002                    // This package, under its official name, already exists
15003                    // on the device; we should replace it.
15004                    replace = true;
15005                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15006                }
15007
15008                // Child packages are installed through the parent package
15009                if (pkg.parentPackage != null) {
15010                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15011                            "Package " + pkg.packageName + " is child of package "
15012                                    + pkg.parentPackage.parentPackage + ". Child packages "
15013                                    + "can be updated only through the parent package.");
15014                    return;
15015                }
15016
15017                if (replace) {
15018                    // Prevent apps opting out from runtime permissions
15019                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15020                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15021                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15022                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15023                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15024                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15025                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15026                                        + " doesn't support runtime permissions but the old"
15027                                        + " target SDK " + oldTargetSdk + " does.");
15028                        return;
15029                    }
15030
15031                    // Prevent installing of child packages
15032                    if (oldPackage.parentPackage != null) {
15033                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15034                                "Package " + pkg.packageName + " is child of package "
15035                                        + oldPackage.parentPackage + ". Child packages "
15036                                        + "can be updated only through the parent package.");
15037                        return;
15038                    }
15039                }
15040            }
15041
15042            PackageSetting ps = mSettings.mPackages.get(pkgName);
15043            if (ps != null) {
15044                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15045
15046                // Quick sanity check that we're signed correctly if updating;
15047                // we'll check this again later when scanning, but we want to
15048                // bail early here before tripping over redefined permissions.
15049                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15050                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15051                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15052                                + pkg.packageName + " upgrade keys do not match the "
15053                                + "previously installed version");
15054                        return;
15055                    }
15056                } else {
15057                    try {
15058                        verifySignaturesLP(ps, pkg);
15059                    } catch (PackageManagerException e) {
15060                        res.setError(e.error, e.getMessage());
15061                        return;
15062                    }
15063                }
15064
15065                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15066                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15067                    systemApp = (ps.pkg.applicationInfo.flags &
15068                            ApplicationInfo.FLAG_SYSTEM) != 0;
15069                }
15070                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15071            }
15072
15073            // Check whether the newly-scanned package wants to define an already-defined perm
15074            int N = pkg.permissions.size();
15075            for (int i = N-1; i >= 0; i--) {
15076                PackageParser.Permission perm = pkg.permissions.get(i);
15077                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15078                if (bp != null) {
15079                    // If the defining package is signed with our cert, it's okay.  This
15080                    // also includes the "updating the same package" case, of course.
15081                    // "updating same package" could also involve key-rotation.
15082                    final boolean sigsOk;
15083                    if (bp.sourcePackage.equals(pkg.packageName)
15084                            && (bp.packageSetting instanceof PackageSetting)
15085                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15086                                    scanFlags))) {
15087                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15088                    } else {
15089                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15090                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15091                    }
15092                    if (!sigsOk) {
15093                        // If the owning package is the system itself, we log but allow
15094                        // install to proceed; we fail the install on all other permission
15095                        // redefinitions.
15096                        if (!bp.sourcePackage.equals("android")) {
15097                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15098                                    + pkg.packageName + " attempting to redeclare permission "
15099                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15100                            res.origPermission = perm.info.name;
15101                            res.origPackage = bp.sourcePackage;
15102                            return;
15103                        } else {
15104                            Slog.w(TAG, "Package " + pkg.packageName
15105                                    + " attempting to redeclare system permission "
15106                                    + perm.info.name + "; ignoring new declaration");
15107                            pkg.permissions.remove(i);
15108                        }
15109                    }
15110                }
15111            }
15112        }
15113
15114        if (systemApp) {
15115            if (onExternal) {
15116                // Abort update; system app can't be replaced with app on sdcard
15117                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15118                        "Cannot install updates to system apps on sdcard");
15119                return;
15120            } else if (ephemeral) {
15121                // Abort update; system app can't be replaced with an ephemeral app
15122                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15123                        "Cannot update a system app with an ephemeral app");
15124                return;
15125            }
15126        }
15127
15128        if (args.move != null) {
15129            // We did an in-place move, so dex is ready to roll
15130            scanFlags |= SCAN_NO_DEX;
15131            scanFlags |= SCAN_MOVE;
15132
15133            synchronized (mPackages) {
15134                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15135                if (ps == null) {
15136                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15137                            "Missing settings for moved package " + pkgName);
15138                }
15139
15140                // We moved the entire application as-is, so bring over the
15141                // previously derived ABI information.
15142                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15143                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15144            }
15145
15146        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15147            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15148            scanFlags |= SCAN_NO_DEX;
15149
15150            try {
15151                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15152                    args.abiOverride : pkg.cpuAbiOverride);
15153                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15154                        true /* extract libs */);
15155            } catch (PackageManagerException pme) {
15156                Slog.e(TAG, "Error deriving application ABI", pme);
15157                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15158                return;
15159            }
15160
15161            // Shared libraries for the package need to be updated.
15162            synchronized (mPackages) {
15163                try {
15164                    updateSharedLibrariesLPw(pkg, null);
15165                } catch (PackageManagerException e) {
15166                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15167                }
15168            }
15169            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15170            // Do not run PackageDexOptimizer through the local performDexOpt
15171            // method because `pkg` may not be in `mPackages` yet.
15172            //
15173            // Also, don't fail application installs if the dexopt step fails.
15174            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15175                    null /* instructionSets */, false /* checkProfiles */,
15176                    getCompilerFilterForReason(REASON_INSTALL));
15177            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15178
15179            // Notify BackgroundDexOptService that the package has been changed.
15180            // If this is an update of a package which used to fail to compile,
15181            // BDOS will remove it from its blacklist.
15182            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15183        }
15184
15185        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15186            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15187            return;
15188        }
15189
15190        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15191
15192        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15193                "installPackageLI")) {
15194            if (replace) {
15195                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15196                        installerPackageName, res);
15197            } else {
15198                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15199                        args.user, installerPackageName, volumeUuid, res);
15200            }
15201        }
15202        synchronized (mPackages) {
15203            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15204            if (ps != null) {
15205                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15206            }
15207
15208            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15209            for (int i = 0; i < childCount; i++) {
15210                PackageParser.Package childPkg = pkg.childPackages.get(i);
15211                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15212                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15213                if (childPs != null) {
15214                    childRes.newUsers = childPs.queryInstalledUsers(
15215                            sUserManager.getUserIds(), true);
15216                }
15217            }
15218        }
15219    }
15220
15221    private void startIntentFilterVerifications(int userId, boolean replacing,
15222            PackageParser.Package pkg) {
15223        if (mIntentFilterVerifierComponent == null) {
15224            Slog.w(TAG, "No IntentFilter verification will not be done as "
15225                    + "there is no IntentFilterVerifier available!");
15226            return;
15227        }
15228
15229        final int verifierUid = getPackageUid(
15230                mIntentFilterVerifierComponent.getPackageName(),
15231                MATCH_DEBUG_TRIAGED_MISSING,
15232                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15233
15234        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15235        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15236        mHandler.sendMessage(msg);
15237
15238        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15239        for (int i = 0; i < childCount; i++) {
15240            PackageParser.Package childPkg = pkg.childPackages.get(i);
15241            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15242            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15243            mHandler.sendMessage(msg);
15244        }
15245    }
15246
15247    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15248            PackageParser.Package pkg) {
15249        int size = pkg.activities.size();
15250        if (size == 0) {
15251            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15252                    "No activity, so no need to verify any IntentFilter!");
15253            return;
15254        }
15255
15256        final boolean hasDomainURLs = hasDomainURLs(pkg);
15257        if (!hasDomainURLs) {
15258            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15259                    "No domain URLs, so no need to verify any IntentFilter!");
15260            return;
15261        }
15262
15263        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15264                + " if any IntentFilter from the " + size
15265                + " Activities needs verification ...");
15266
15267        int count = 0;
15268        final String packageName = pkg.packageName;
15269
15270        synchronized (mPackages) {
15271            // If this is a new install and we see that we've already run verification for this
15272            // package, we have nothing to do: it means the state was restored from backup.
15273            if (!replacing) {
15274                IntentFilterVerificationInfo ivi =
15275                        mSettings.getIntentFilterVerificationLPr(packageName);
15276                if (ivi != null) {
15277                    if (DEBUG_DOMAIN_VERIFICATION) {
15278                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15279                                + ivi.getStatusString());
15280                    }
15281                    return;
15282                }
15283            }
15284
15285            // If any filters need to be verified, then all need to be.
15286            boolean needToVerify = false;
15287            for (PackageParser.Activity a : pkg.activities) {
15288                for (ActivityIntentInfo filter : a.intents) {
15289                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15290                        if (DEBUG_DOMAIN_VERIFICATION) {
15291                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15292                        }
15293                        needToVerify = true;
15294                        break;
15295                    }
15296                }
15297            }
15298
15299            if (needToVerify) {
15300                final int verificationId = mIntentFilterVerificationToken++;
15301                for (PackageParser.Activity a : pkg.activities) {
15302                    for (ActivityIntentInfo filter : a.intents) {
15303                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15304                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15305                                    "Verification needed for IntentFilter:" + filter.toString());
15306                            mIntentFilterVerifier.addOneIntentFilterVerification(
15307                                    verifierUid, userId, verificationId, filter, packageName);
15308                            count++;
15309                        }
15310                    }
15311                }
15312            }
15313        }
15314
15315        if (count > 0) {
15316            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15317                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15318                    +  " for userId:" + userId);
15319            mIntentFilterVerifier.startVerifications(userId);
15320        } else {
15321            if (DEBUG_DOMAIN_VERIFICATION) {
15322                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15323            }
15324        }
15325    }
15326
15327    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15328        final ComponentName cn  = filter.activity.getComponentName();
15329        final String packageName = cn.getPackageName();
15330
15331        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15332                packageName);
15333        if (ivi == null) {
15334            return true;
15335        }
15336        int status = ivi.getStatus();
15337        switch (status) {
15338            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15339            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15340                return true;
15341
15342            default:
15343                // Nothing to do
15344                return false;
15345        }
15346    }
15347
15348    private static boolean isMultiArch(ApplicationInfo info) {
15349        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15350    }
15351
15352    private static boolean isExternal(PackageParser.Package pkg) {
15353        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15354    }
15355
15356    private static boolean isExternal(PackageSetting ps) {
15357        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15358    }
15359
15360    private static boolean isEphemeral(PackageParser.Package pkg) {
15361        return pkg.applicationInfo.isEphemeralApp();
15362    }
15363
15364    private static boolean isEphemeral(PackageSetting ps) {
15365        return ps.pkg != null && isEphemeral(ps.pkg);
15366    }
15367
15368    private static boolean isSystemApp(PackageParser.Package pkg) {
15369        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15370    }
15371
15372    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15373        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15374    }
15375
15376    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15377        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15378    }
15379
15380    private static boolean isSystemApp(PackageSetting ps) {
15381        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15382    }
15383
15384    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15385        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15386    }
15387
15388    private int packageFlagsToInstallFlags(PackageSetting ps) {
15389        int installFlags = 0;
15390        if (isEphemeral(ps)) {
15391            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15392        }
15393        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15394            // This existing package was an external ASEC install when we have
15395            // the external flag without a UUID
15396            installFlags |= PackageManager.INSTALL_EXTERNAL;
15397        }
15398        if (ps.isForwardLocked()) {
15399            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15400        }
15401        return installFlags;
15402    }
15403
15404    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15405        if (isExternal(pkg)) {
15406            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15407                return StorageManager.UUID_PRIMARY_PHYSICAL;
15408            } else {
15409                return pkg.volumeUuid;
15410            }
15411        } else {
15412            return StorageManager.UUID_PRIVATE_INTERNAL;
15413        }
15414    }
15415
15416    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15417        if (isExternal(pkg)) {
15418            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15419                return mSettings.getExternalVersion();
15420            } else {
15421                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15422            }
15423        } else {
15424            return mSettings.getInternalVersion();
15425        }
15426    }
15427
15428    private void deleteTempPackageFiles() {
15429        final FilenameFilter filter = new FilenameFilter() {
15430            public boolean accept(File dir, String name) {
15431                return name.startsWith("vmdl") && name.endsWith(".tmp");
15432            }
15433        };
15434        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15435            file.delete();
15436        }
15437    }
15438
15439    @Override
15440    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15441            int flags) {
15442        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15443                flags);
15444    }
15445
15446    @Override
15447    public void deletePackage(final String packageName,
15448            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15449        mContext.enforceCallingOrSelfPermission(
15450                android.Manifest.permission.DELETE_PACKAGES, null);
15451        Preconditions.checkNotNull(packageName);
15452        Preconditions.checkNotNull(observer);
15453        final int uid = Binder.getCallingUid();
15454        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15455        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15456        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15457            mContext.enforceCallingOrSelfPermission(
15458                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15459                    "deletePackage for user " + userId);
15460        }
15461
15462        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15463            try {
15464                observer.onPackageDeleted(packageName,
15465                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15466            } catch (RemoteException re) {
15467            }
15468            return;
15469        }
15470
15471        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15472            try {
15473                observer.onPackageDeleted(packageName,
15474                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15475            } catch (RemoteException re) {
15476            }
15477            return;
15478        }
15479
15480        if (DEBUG_REMOVE) {
15481            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15482                    + " deleteAllUsers: " + deleteAllUsers );
15483        }
15484        // Queue up an async operation since the package deletion may take a little while.
15485        mHandler.post(new Runnable() {
15486            public void run() {
15487                mHandler.removeCallbacks(this);
15488                int returnCode;
15489                if (!deleteAllUsers) {
15490                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15491                } else {
15492                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15493                    // If nobody is blocking uninstall, proceed with delete for all users
15494                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15495                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15496                    } else {
15497                        // Otherwise uninstall individually for users with blockUninstalls=false
15498                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15499                        for (int userId : users) {
15500                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15501                                returnCode = deletePackageX(packageName, userId, userFlags);
15502                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15503                                    Slog.w(TAG, "Package delete failed for user " + userId
15504                                            + ", returnCode " + returnCode);
15505                                }
15506                            }
15507                        }
15508                        // The app has only been marked uninstalled for certain users.
15509                        // We still need to report that delete was blocked
15510                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15511                    }
15512                }
15513                try {
15514                    observer.onPackageDeleted(packageName, returnCode, null);
15515                } catch (RemoteException e) {
15516                    Log.i(TAG, "Observer no longer exists.");
15517                } //end catch
15518            } //end run
15519        });
15520    }
15521
15522    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15523        int[] result = EMPTY_INT_ARRAY;
15524        for (int userId : userIds) {
15525            if (getBlockUninstallForUser(packageName, userId)) {
15526                result = ArrayUtils.appendInt(result, userId);
15527            }
15528        }
15529        return result;
15530    }
15531
15532    @Override
15533    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15534        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15535    }
15536
15537    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15538        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15539                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15540        try {
15541            if (dpm != null) {
15542                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15543                        /* callingUserOnly =*/ false);
15544                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15545                        : deviceOwnerComponentName.getPackageName();
15546                // Does the package contains the device owner?
15547                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15548                // this check is probably not needed, since DO should be registered as a device
15549                // admin on some user too. (Original bug for this: b/17657954)
15550                if (packageName.equals(deviceOwnerPackageName)) {
15551                    return true;
15552                }
15553                // Does it contain a device admin for any user?
15554                int[] users;
15555                if (userId == UserHandle.USER_ALL) {
15556                    users = sUserManager.getUserIds();
15557                } else {
15558                    users = new int[]{userId};
15559                }
15560                for (int i = 0; i < users.length; ++i) {
15561                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15562                        return true;
15563                    }
15564                }
15565            }
15566        } catch (RemoteException e) {
15567        }
15568        return false;
15569    }
15570
15571    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15572        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15573    }
15574
15575    /**
15576     *  This method is an internal method that could be get invoked either
15577     *  to delete an installed package or to clean up a failed installation.
15578     *  After deleting an installed package, a broadcast is sent to notify any
15579     *  listeners that the package has been removed. For cleaning up a failed
15580     *  installation, the broadcast is not necessary since the package's
15581     *  installation wouldn't have sent the initial broadcast either
15582     *  The key steps in deleting a package are
15583     *  deleting the package information in internal structures like mPackages,
15584     *  deleting the packages base directories through installd
15585     *  updating mSettings to reflect current status
15586     *  persisting settings for later use
15587     *  sending a broadcast if necessary
15588     */
15589    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15590        final PackageRemovedInfo info = new PackageRemovedInfo();
15591        final boolean res;
15592
15593        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15594                ? UserHandle.USER_ALL : userId;
15595
15596        if (isPackageDeviceAdmin(packageName, removeUser)) {
15597            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15598            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15599        }
15600
15601        PackageSetting uninstalledPs = null;
15602
15603        // for the uninstall-updates case and restricted profiles, remember the per-
15604        // user handle installed state
15605        int[] allUsers;
15606        synchronized (mPackages) {
15607            uninstalledPs = mSettings.mPackages.get(packageName);
15608            if (uninstalledPs == null) {
15609                Slog.w(TAG, "Not removing non-existent package " + packageName);
15610                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15611            }
15612            allUsers = sUserManager.getUserIds();
15613            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15614        }
15615
15616        final int freezeUser;
15617        if (isUpdatedSystemApp(uninstalledPs)
15618                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15619            // We're downgrading a system app, which will apply to all users, so
15620            // freeze them all during the downgrade
15621            freezeUser = UserHandle.USER_ALL;
15622        } else {
15623            freezeUser = removeUser;
15624        }
15625
15626        synchronized (mInstallLock) {
15627            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15628            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15629                    deleteFlags, "deletePackageX")) {
15630                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15631                        deleteFlags | REMOVE_CHATTY, info, true, null);
15632            }
15633            synchronized (mPackages) {
15634                if (res) {
15635                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15636                }
15637            }
15638        }
15639
15640        if (res) {
15641            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15642            info.sendPackageRemovedBroadcasts(killApp);
15643            info.sendSystemPackageUpdatedBroadcasts();
15644            info.sendSystemPackageAppearedBroadcasts();
15645        }
15646        // Force a gc here.
15647        Runtime.getRuntime().gc();
15648        // Delete the resources here after sending the broadcast to let
15649        // other processes clean up before deleting resources.
15650        if (info.args != null) {
15651            synchronized (mInstallLock) {
15652                info.args.doPostDeleteLI(true);
15653            }
15654        }
15655
15656        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15657    }
15658
15659    class PackageRemovedInfo {
15660        String removedPackage;
15661        int uid = -1;
15662        int removedAppId = -1;
15663        int[] origUsers;
15664        int[] removedUsers = null;
15665        boolean isRemovedPackageSystemUpdate = false;
15666        boolean isUpdate;
15667        boolean dataRemoved;
15668        boolean removedForAllUsers;
15669        // Clean up resources deleted packages.
15670        InstallArgs args = null;
15671        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15672        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15673
15674        void sendPackageRemovedBroadcasts(boolean killApp) {
15675            sendPackageRemovedBroadcastInternal(killApp);
15676            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15677            for (int i = 0; i < childCount; i++) {
15678                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15679                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15680            }
15681        }
15682
15683        void sendSystemPackageUpdatedBroadcasts() {
15684            if (isRemovedPackageSystemUpdate) {
15685                sendSystemPackageUpdatedBroadcastsInternal();
15686                final int childCount = (removedChildPackages != null)
15687                        ? removedChildPackages.size() : 0;
15688                for (int i = 0; i < childCount; i++) {
15689                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15690                    if (childInfo.isRemovedPackageSystemUpdate) {
15691                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15692                    }
15693                }
15694            }
15695        }
15696
15697        void sendSystemPackageAppearedBroadcasts() {
15698            final int packageCount = (appearedChildPackages != null)
15699                    ? appearedChildPackages.size() : 0;
15700            for (int i = 0; i < packageCount; i++) {
15701                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15702                for (int userId : installedInfo.newUsers) {
15703                    sendPackageAddedForUser(installedInfo.name, true,
15704                            UserHandle.getAppId(installedInfo.uid), userId);
15705                }
15706            }
15707        }
15708
15709        private void sendSystemPackageUpdatedBroadcastsInternal() {
15710            Bundle extras = new Bundle(2);
15711            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15712            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15713            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15714                    extras, 0, null, null, null);
15715            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15716                    extras, 0, null, null, null);
15717            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15718                    null, 0, removedPackage, null, null);
15719        }
15720
15721        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15722            Bundle extras = new Bundle(2);
15723            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15724            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15725            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15726            if (isUpdate || isRemovedPackageSystemUpdate) {
15727                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15728            }
15729            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15730            if (removedPackage != null) {
15731                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15732                        extras, 0, null, null, removedUsers);
15733                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15734                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15735                            removedPackage, extras, 0, null, null, removedUsers);
15736                }
15737            }
15738            if (removedAppId >= 0) {
15739                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15740                        removedUsers);
15741            }
15742        }
15743    }
15744
15745    /*
15746     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15747     * flag is not set, the data directory is removed as well.
15748     * make sure this flag is set for partially installed apps. If not its meaningless to
15749     * delete a partially installed application.
15750     */
15751    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15752            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15753        String packageName = ps.name;
15754        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15755        // Retrieve object to delete permissions for shared user later on
15756        final PackageParser.Package deletedPkg;
15757        final PackageSetting deletedPs;
15758        // reader
15759        synchronized (mPackages) {
15760            deletedPkg = mPackages.get(packageName);
15761            deletedPs = mSettings.mPackages.get(packageName);
15762            if (outInfo != null) {
15763                outInfo.removedPackage = packageName;
15764                outInfo.removedUsers = deletedPs != null
15765                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15766                        : null;
15767            }
15768        }
15769
15770        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15771
15772        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15773            final PackageParser.Package resolvedPkg;
15774            if (deletedPkg != null) {
15775                resolvedPkg = deletedPkg;
15776            } else {
15777                // We don't have a parsed package when it lives on an ejected
15778                // adopted storage device, so fake something together
15779                resolvedPkg = new PackageParser.Package(ps.name);
15780                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15781            }
15782            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15783                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15784            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15785            if (outInfo != null) {
15786                outInfo.dataRemoved = true;
15787            }
15788            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15789        }
15790
15791        // writer
15792        synchronized (mPackages) {
15793            if (deletedPs != null) {
15794                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15795                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15796                    clearDefaultBrowserIfNeeded(packageName);
15797                    if (outInfo != null) {
15798                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15799                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15800                    }
15801                    updatePermissionsLPw(deletedPs.name, null, 0);
15802                    if (deletedPs.sharedUser != null) {
15803                        // Remove permissions associated with package. Since runtime
15804                        // permissions are per user we have to kill the removed package
15805                        // or packages running under the shared user of the removed
15806                        // package if revoking the permissions requested only by the removed
15807                        // package is successful and this causes a change in gids.
15808                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15809                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15810                                    userId);
15811                            if (userIdToKill == UserHandle.USER_ALL
15812                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15813                                // If gids changed for this user, kill all affected packages.
15814                                mHandler.post(new Runnable() {
15815                                    @Override
15816                                    public void run() {
15817                                        // This has to happen with no lock held.
15818                                        killApplication(deletedPs.name, deletedPs.appId,
15819                                                KILL_APP_REASON_GIDS_CHANGED);
15820                                    }
15821                                });
15822                                break;
15823                            }
15824                        }
15825                    }
15826                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15827                }
15828                // make sure to preserve per-user disabled state if this removal was just
15829                // a downgrade of a system app to the factory package
15830                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15831                    if (DEBUG_REMOVE) {
15832                        Slog.d(TAG, "Propagating install state across downgrade");
15833                    }
15834                    for (int userId : allUserHandles) {
15835                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15836                        if (DEBUG_REMOVE) {
15837                            Slog.d(TAG, "    user " + userId + " => " + installed);
15838                        }
15839                        ps.setInstalled(installed, userId);
15840                    }
15841                }
15842            }
15843            // can downgrade to reader
15844            if (writeSettings) {
15845                // Save settings now
15846                mSettings.writeLPr();
15847            }
15848        }
15849        if (outInfo != null) {
15850            // A user ID was deleted here. Go through all users and remove it
15851            // from KeyStore.
15852            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15853        }
15854    }
15855
15856    static boolean locationIsPrivileged(File path) {
15857        try {
15858            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15859                    .getCanonicalPath();
15860            return path.getCanonicalPath().startsWith(privilegedAppDir);
15861        } catch (IOException e) {
15862            Slog.e(TAG, "Unable to access code path " + path);
15863        }
15864        return false;
15865    }
15866
15867    /*
15868     * Tries to delete system package.
15869     */
15870    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15871            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15872            boolean writeSettings) {
15873        if (deletedPs.parentPackageName != null) {
15874            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15875            return false;
15876        }
15877
15878        final boolean applyUserRestrictions
15879                = (allUserHandles != null) && (outInfo.origUsers != null);
15880        final PackageSetting disabledPs;
15881        // Confirm if the system package has been updated
15882        // An updated system app can be deleted. This will also have to restore
15883        // the system pkg from system partition
15884        // reader
15885        synchronized (mPackages) {
15886            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15887        }
15888
15889        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15890                + " disabledPs=" + disabledPs);
15891
15892        if (disabledPs == null) {
15893            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15894            return false;
15895        } else if (DEBUG_REMOVE) {
15896            Slog.d(TAG, "Deleting system pkg from data partition");
15897        }
15898
15899        if (DEBUG_REMOVE) {
15900            if (applyUserRestrictions) {
15901                Slog.d(TAG, "Remembering install states:");
15902                for (int userId : allUserHandles) {
15903                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15904                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15905                }
15906            }
15907        }
15908
15909        // Delete the updated package
15910        outInfo.isRemovedPackageSystemUpdate = true;
15911        if (outInfo.removedChildPackages != null) {
15912            final int childCount = (deletedPs.childPackageNames != null)
15913                    ? deletedPs.childPackageNames.size() : 0;
15914            for (int i = 0; i < childCount; i++) {
15915                String childPackageName = deletedPs.childPackageNames.get(i);
15916                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15917                        .contains(childPackageName)) {
15918                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15919                            childPackageName);
15920                    if (childInfo != null) {
15921                        childInfo.isRemovedPackageSystemUpdate = true;
15922                    }
15923                }
15924            }
15925        }
15926
15927        if (disabledPs.versionCode < deletedPs.versionCode) {
15928            // Delete data for downgrades
15929            flags &= ~PackageManager.DELETE_KEEP_DATA;
15930        } else {
15931            // Preserve data by setting flag
15932            flags |= PackageManager.DELETE_KEEP_DATA;
15933        }
15934
15935        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15936                outInfo, writeSettings, disabledPs.pkg);
15937        if (!ret) {
15938            return false;
15939        }
15940
15941        // writer
15942        synchronized (mPackages) {
15943            // Reinstate the old system package
15944            enableSystemPackageLPw(disabledPs.pkg);
15945            // Remove any native libraries from the upgraded package.
15946            removeNativeBinariesLI(deletedPs);
15947        }
15948
15949        // Install the system package
15950        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15951        int parseFlags = mDefParseFlags
15952                | PackageParser.PARSE_MUST_BE_APK
15953                | PackageParser.PARSE_IS_SYSTEM
15954                | PackageParser.PARSE_IS_SYSTEM_DIR;
15955        if (locationIsPrivileged(disabledPs.codePath)) {
15956            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15957        }
15958
15959        final PackageParser.Package newPkg;
15960        try {
15961            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15962        } catch (PackageManagerException e) {
15963            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15964                    + e.getMessage());
15965            return false;
15966        }
15967
15968        prepareAppDataAfterInstallLIF(newPkg);
15969
15970        // writer
15971        synchronized (mPackages) {
15972            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15973
15974            // Propagate the permissions state as we do not want to drop on the floor
15975            // runtime permissions. The update permissions method below will take
15976            // care of removing obsolete permissions and grant install permissions.
15977            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15978            updatePermissionsLPw(newPkg.packageName, newPkg,
15979                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15980
15981            if (applyUserRestrictions) {
15982                if (DEBUG_REMOVE) {
15983                    Slog.d(TAG, "Propagating install state across reinstall");
15984                }
15985                for (int userId : allUserHandles) {
15986                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15987                    if (DEBUG_REMOVE) {
15988                        Slog.d(TAG, "    user " + userId + " => " + installed);
15989                    }
15990                    ps.setInstalled(installed, userId);
15991
15992                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15993                }
15994                // Regardless of writeSettings we need to ensure that this restriction
15995                // state propagation is persisted
15996                mSettings.writeAllUsersPackageRestrictionsLPr();
15997            }
15998            // can downgrade to reader here
15999            if (writeSettings) {
16000                mSettings.writeLPr();
16001            }
16002        }
16003        return true;
16004    }
16005
16006    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16007            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16008            PackageRemovedInfo outInfo, boolean writeSettings,
16009            PackageParser.Package replacingPackage) {
16010        synchronized (mPackages) {
16011            if (outInfo != null) {
16012                outInfo.uid = ps.appId;
16013            }
16014
16015            if (outInfo != null && outInfo.removedChildPackages != null) {
16016                final int childCount = (ps.childPackageNames != null)
16017                        ? ps.childPackageNames.size() : 0;
16018                for (int i = 0; i < childCount; i++) {
16019                    String childPackageName = ps.childPackageNames.get(i);
16020                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16021                    if (childPs == null) {
16022                        return false;
16023                    }
16024                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16025                            childPackageName);
16026                    if (childInfo != null) {
16027                        childInfo.uid = childPs.appId;
16028                    }
16029                }
16030            }
16031        }
16032
16033        // Delete package data from internal structures and also remove data if flag is set
16034        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16035
16036        // Delete the child packages data
16037        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16038        for (int i = 0; i < childCount; i++) {
16039            PackageSetting childPs;
16040            synchronized (mPackages) {
16041                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16042            }
16043            if (childPs != null) {
16044                PackageRemovedInfo childOutInfo = (outInfo != null
16045                        && outInfo.removedChildPackages != null)
16046                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16047                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16048                        && (replacingPackage != null
16049                        && !replacingPackage.hasChildPackage(childPs.name))
16050                        ? flags & ~DELETE_KEEP_DATA : flags;
16051                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16052                        deleteFlags, writeSettings);
16053            }
16054        }
16055
16056        // Delete application code and resources only for parent packages
16057        if (ps.parentPackageName == null) {
16058            if (deleteCodeAndResources && (outInfo != null)) {
16059                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16060                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16061                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16062            }
16063        }
16064
16065        return true;
16066    }
16067
16068    @Override
16069    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16070            int userId) {
16071        mContext.enforceCallingOrSelfPermission(
16072                android.Manifest.permission.DELETE_PACKAGES, null);
16073        synchronized (mPackages) {
16074            PackageSetting ps = mSettings.mPackages.get(packageName);
16075            if (ps == null) {
16076                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16077                return false;
16078            }
16079            if (!ps.getInstalled(userId)) {
16080                // Can't block uninstall for an app that is not installed or enabled.
16081                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16082                return false;
16083            }
16084            ps.setBlockUninstall(blockUninstall, userId);
16085            mSettings.writePackageRestrictionsLPr(userId);
16086        }
16087        return true;
16088    }
16089
16090    @Override
16091    public boolean getBlockUninstallForUser(String packageName, int userId) {
16092        synchronized (mPackages) {
16093            PackageSetting ps = mSettings.mPackages.get(packageName);
16094            if (ps == null) {
16095                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16096                return false;
16097            }
16098            return ps.getBlockUninstall(userId);
16099        }
16100    }
16101
16102    @Override
16103    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16104        int callingUid = Binder.getCallingUid();
16105        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16106            throw new SecurityException(
16107                    "setRequiredForSystemUser can only be run by the system or root");
16108        }
16109        synchronized (mPackages) {
16110            PackageSetting ps = mSettings.mPackages.get(packageName);
16111            if (ps == null) {
16112                Log.w(TAG, "Package doesn't exist: " + packageName);
16113                return false;
16114            }
16115            if (systemUserApp) {
16116                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16117            } else {
16118                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16119            }
16120            mSettings.writeLPr();
16121        }
16122        return true;
16123    }
16124
16125    /*
16126     * This method handles package deletion in general
16127     */
16128    private boolean deletePackageLIF(String packageName, UserHandle user,
16129            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16130            PackageRemovedInfo outInfo, boolean writeSettings,
16131            PackageParser.Package replacingPackage) {
16132        if (packageName == null) {
16133            Slog.w(TAG, "Attempt to delete null packageName.");
16134            return false;
16135        }
16136
16137        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16138
16139        PackageSetting ps;
16140
16141        synchronized (mPackages) {
16142            ps = mSettings.mPackages.get(packageName);
16143            if (ps == null) {
16144                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16145                return false;
16146            }
16147
16148            if (ps.parentPackageName != null && (!isSystemApp(ps)
16149                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16150                if (DEBUG_REMOVE) {
16151                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16152                            + ((user == null) ? UserHandle.USER_ALL : user));
16153                }
16154                final int removedUserId = (user != null) ? user.getIdentifier()
16155                        : UserHandle.USER_ALL;
16156                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16157                    return false;
16158                }
16159                markPackageUninstalledForUserLPw(ps, user);
16160                scheduleWritePackageRestrictionsLocked(user);
16161                return true;
16162            }
16163        }
16164
16165        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16166                && user.getIdentifier() != UserHandle.USER_ALL)) {
16167            // The caller is asking that the package only be deleted for a single
16168            // user.  To do this, we just mark its uninstalled state and delete
16169            // its data. If this is a system app, we only allow this to happen if
16170            // they have set the special DELETE_SYSTEM_APP which requests different
16171            // semantics than normal for uninstalling system apps.
16172            markPackageUninstalledForUserLPw(ps, user);
16173
16174            if (!isSystemApp(ps)) {
16175                // Do not uninstall the APK if an app should be cached
16176                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16177                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16178                    // Other user still have this package installed, so all
16179                    // we need to do is clear this user's data and save that
16180                    // it is uninstalled.
16181                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16182                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16183                        return false;
16184                    }
16185                    scheduleWritePackageRestrictionsLocked(user);
16186                    return true;
16187                } else {
16188                    // We need to set it back to 'installed' so the uninstall
16189                    // broadcasts will be sent correctly.
16190                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16191                    ps.setInstalled(true, user.getIdentifier());
16192                }
16193            } else {
16194                // This is a system app, so we assume that the
16195                // other users still have this package installed, so all
16196                // we need to do is clear this user's data and save that
16197                // it is uninstalled.
16198                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16199                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16200                    return false;
16201                }
16202                scheduleWritePackageRestrictionsLocked(user);
16203                return true;
16204            }
16205        }
16206
16207        // If we are deleting a composite package for all users, keep track
16208        // of result for each child.
16209        if (ps.childPackageNames != null && outInfo != null) {
16210            synchronized (mPackages) {
16211                final int childCount = ps.childPackageNames.size();
16212                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16213                for (int i = 0; i < childCount; i++) {
16214                    String childPackageName = ps.childPackageNames.get(i);
16215                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16216                    childInfo.removedPackage = childPackageName;
16217                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16218                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16219                    if (childPs != null) {
16220                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16221                    }
16222                }
16223            }
16224        }
16225
16226        boolean ret = false;
16227        if (isSystemApp(ps)) {
16228            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16229            // When an updated system application is deleted we delete the existing resources
16230            // as well and fall back to existing code in system partition
16231            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16232        } else {
16233            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16234            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16235                    outInfo, writeSettings, replacingPackage);
16236        }
16237
16238        // Take a note whether we deleted the package for all users
16239        if (outInfo != null) {
16240            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16241            if (outInfo.removedChildPackages != null) {
16242                synchronized (mPackages) {
16243                    final int childCount = outInfo.removedChildPackages.size();
16244                    for (int i = 0; i < childCount; i++) {
16245                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16246                        if (childInfo != null) {
16247                            childInfo.removedForAllUsers = mPackages.get(
16248                                    childInfo.removedPackage) == null;
16249                        }
16250                    }
16251                }
16252            }
16253            // If we uninstalled an update to a system app there may be some
16254            // child packages that appeared as they are declared in the system
16255            // app but were not declared in the update.
16256            if (isSystemApp(ps)) {
16257                synchronized (mPackages) {
16258                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16259                    final int childCount = (updatedPs.childPackageNames != null)
16260                            ? updatedPs.childPackageNames.size() : 0;
16261                    for (int i = 0; i < childCount; i++) {
16262                        String childPackageName = updatedPs.childPackageNames.get(i);
16263                        if (outInfo.removedChildPackages == null
16264                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16265                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16266                            if (childPs == null) {
16267                                continue;
16268                            }
16269                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16270                            installRes.name = childPackageName;
16271                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16272                            installRes.pkg = mPackages.get(childPackageName);
16273                            installRes.uid = childPs.pkg.applicationInfo.uid;
16274                            if (outInfo.appearedChildPackages == null) {
16275                                outInfo.appearedChildPackages = new ArrayMap<>();
16276                            }
16277                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16278                        }
16279                    }
16280                }
16281            }
16282        }
16283
16284        return ret;
16285    }
16286
16287    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16288        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16289                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16290        for (int nextUserId : userIds) {
16291            if (DEBUG_REMOVE) {
16292                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16293            }
16294            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16295                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16296                    false /*hidden*/, false /*suspended*/, null, null, null,
16297                    false /*blockUninstall*/,
16298                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16299        }
16300    }
16301
16302    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16303            PackageRemovedInfo outInfo) {
16304        final PackageParser.Package pkg;
16305        synchronized (mPackages) {
16306            pkg = mPackages.get(ps.name);
16307        }
16308
16309        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16310                : new int[] {userId};
16311        for (int nextUserId : userIds) {
16312            if (DEBUG_REMOVE) {
16313                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16314                        + nextUserId);
16315            }
16316
16317            destroyAppDataLIF(pkg, userId,
16318                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16319            destroyAppProfilesLIF(pkg, userId);
16320            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16321            schedulePackageCleaning(ps.name, nextUserId, false);
16322            synchronized (mPackages) {
16323                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16324                    scheduleWritePackageRestrictionsLocked(nextUserId);
16325                }
16326                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16327            }
16328        }
16329
16330        if (outInfo != null) {
16331            outInfo.removedPackage = ps.name;
16332            outInfo.removedAppId = ps.appId;
16333            outInfo.removedUsers = userIds;
16334        }
16335
16336        return true;
16337    }
16338
16339    private final class ClearStorageConnection implements ServiceConnection {
16340        IMediaContainerService mContainerService;
16341
16342        @Override
16343        public void onServiceConnected(ComponentName name, IBinder service) {
16344            synchronized (this) {
16345                mContainerService = IMediaContainerService.Stub.asInterface(service);
16346                notifyAll();
16347            }
16348        }
16349
16350        @Override
16351        public void onServiceDisconnected(ComponentName name) {
16352        }
16353    }
16354
16355    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16356        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16357
16358        final boolean mounted;
16359        if (Environment.isExternalStorageEmulated()) {
16360            mounted = true;
16361        } else {
16362            final String status = Environment.getExternalStorageState();
16363
16364            mounted = status.equals(Environment.MEDIA_MOUNTED)
16365                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16366        }
16367
16368        if (!mounted) {
16369            return;
16370        }
16371
16372        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16373        int[] users;
16374        if (userId == UserHandle.USER_ALL) {
16375            users = sUserManager.getUserIds();
16376        } else {
16377            users = new int[] { userId };
16378        }
16379        final ClearStorageConnection conn = new ClearStorageConnection();
16380        if (mContext.bindServiceAsUser(
16381                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16382            try {
16383                for (int curUser : users) {
16384                    long timeout = SystemClock.uptimeMillis() + 5000;
16385                    synchronized (conn) {
16386                        long now;
16387                        while (conn.mContainerService == null &&
16388                                (now = SystemClock.uptimeMillis()) < timeout) {
16389                            try {
16390                                conn.wait(timeout - now);
16391                            } catch (InterruptedException e) {
16392                            }
16393                        }
16394                    }
16395                    if (conn.mContainerService == null) {
16396                        return;
16397                    }
16398
16399                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16400                    clearDirectory(conn.mContainerService,
16401                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16402                    if (allData) {
16403                        clearDirectory(conn.mContainerService,
16404                                userEnv.buildExternalStorageAppDataDirs(packageName));
16405                        clearDirectory(conn.mContainerService,
16406                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16407                    }
16408                }
16409            } finally {
16410                mContext.unbindService(conn);
16411            }
16412        }
16413    }
16414
16415    @Override
16416    public void clearApplicationProfileData(String packageName) {
16417        enforceSystemOrRoot("Only the system can clear all profile data");
16418
16419        final PackageParser.Package pkg;
16420        synchronized (mPackages) {
16421            pkg = mPackages.get(packageName);
16422        }
16423
16424        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16425            synchronized (mInstallLock) {
16426                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16427                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16428                        true /* removeBaseMarker */);
16429            }
16430        }
16431    }
16432
16433    @Override
16434    public void clearApplicationUserData(final String packageName,
16435            final IPackageDataObserver observer, final int userId) {
16436        mContext.enforceCallingOrSelfPermission(
16437                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16438
16439        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16440                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16441
16442        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16443            throw new SecurityException("Cannot clear data for a protected package: "
16444                    + packageName);
16445        }
16446        // Queue up an async operation since the package deletion may take a little while.
16447        mHandler.post(new Runnable() {
16448            public void run() {
16449                mHandler.removeCallbacks(this);
16450                final boolean succeeded;
16451                try (PackageFreezer freezer = freezePackage(packageName,
16452                        "clearApplicationUserData")) {
16453                    synchronized (mInstallLock) {
16454                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16455                    }
16456                    clearExternalStorageDataSync(packageName, userId, true);
16457                }
16458                if (succeeded) {
16459                    // invoke DeviceStorageMonitor's update method to clear any notifications
16460                    DeviceStorageMonitorInternal dsm = LocalServices
16461                            .getService(DeviceStorageMonitorInternal.class);
16462                    if (dsm != null) {
16463                        dsm.checkMemory();
16464                    }
16465                }
16466                if(observer != null) {
16467                    try {
16468                        observer.onRemoveCompleted(packageName, succeeded);
16469                    } catch (RemoteException e) {
16470                        Log.i(TAG, "Observer no longer exists.");
16471                    }
16472                } //end if observer
16473            } //end run
16474        });
16475    }
16476
16477    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16478        if (packageName == null) {
16479            Slog.w(TAG, "Attempt to delete null packageName.");
16480            return false;
16481        }
16482
16483        // Try finding details about the requested package
16484        PackageParser.Package pkg;
16485        synchronized (mPackages) {
16486            pkg = mPackages.get(packageName);
16487            if (pkg == null) {
16488                final PackageSetting ps = mSettings.mPackages.get(packageName);
16489                if (ps != null) {
16490                    pkg = ps.pkg;
16491                }
16492            }
16493
16494            if (pkg == null) {
16495                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16496                return false;
16497            }
16498
16499            PackageSetting ps = (PackageSetting) pkg.mExtras;
16500            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16501        }
16502
16503        clearAppDataLIF(pkg, userId,
16504                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16505
16506        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16507        removeKeystoreDataIfNeeded(userId, appId);
16508
16509        UserManagerInternal umInternal = getUserManagerInternal();
16510        final int flags;
16511        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16512            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16513        } else if (umInternal.isUserRunning(userId)) {
16514            flags = StorageManager.FLAG_STORAGE_DE;
16515        } else {
16516            flags = 0;
16517        }
16518        prepareAppDataContentsLIF(pkg, userId, flags);
16519
16520        return true;
16521    }
16522
16523    /**
16524     * Reverts user permission state changes (permissions and flags) in
16525     * all packages for a given user.
16526     *
16527     * @param userId The device user for which to do a reset.
16528     */
16529    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16530        final int packageCount = mPackages.size();
16531        for (int i = 0; i < packageCount; i++) {
16532            PackageParser.Package pkg = mPackages.valueAt(i);
16533            PackageSetting ps = (PackageSetting) pkg.mExtras;
16534            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16535        }
16536    }
16537
16538    private void resetNetworkPolicies(int userId) {
16539        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16540    }
16541
16542    /**
16543     * Reverts user permission state changes (permissions and flags).
16544     *
16545     * @param ps The package for which to reset.
16546     * @param userId The device user for which to do a reset.
16547     */
16548    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16549            final PackageSetting ps, final int userId) {
16550        if (ps.pkg == null) {
16551            return;
16552        }
16553
16554        // These are flags that can change base on user actions.
16555        final int userSettableMask = FLAG_PERMISSION_USER_SET
16556                | FLAG_PERMISSION_USER_FIXED
16557                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16558                | FLAG_PERMISSION_REVIEW_REQUIRED;
16559
16560        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16561                | FLAG_PERMISSION_POLICY_FIXED;
16562
16563        boolean writeInstallPermissions = false;
16564        boolean writeRuntimePermissions = false;
16565
16566        final int permissionCount = ps.pkg.requestedPermissions.size();
16567        for (int i = 0; i < permissionCount; i++) {
16568            String permission = ps.pkg.requestedPermissions.get(i);
16569
16570            BasePermission bp = mSettings.mPermissions.get(permission);
16571            if (bp == null) {
16572                continue;
16573            }
16574
16575            // If shared user we just reset the state to which only this app contributed.
16576            if (ps.sharedUser != null) {
16577                boolean used = false;
16578                final int packageCount = ps.sharedUser.packages.size();
16579                for (int j = 0; j < packageCount; j++) {
16580                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16581                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16582                            && pkg.pkg.requestedPermissions.contains(permission)) {
16583                        used = true;
16584                        break;
16585                    }
16586                }
16587                if (used) {
16588                    continue;
16589                }
16590            }
16591
16592            PermissionsState permissionsState = ps.getPermissionsState();
16593
16594            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16595
16596            // Always clear the user settable flags.
16597            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16598                    bp.name) != null;
16599            // If permission review is enabled and this is a legacy app, mark the
16600            // permission as requiring a review as this is the initial state.
16601            int flags = 0;
16602            if (Build.PERMISSIONS_REVIEW_REQUIRED
16603                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16604                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16605            }
16606            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16607                if (hasInstallState) {
16608                    writeInstallPermissions = true;
16609                } else {
16610                    writeRuntimePermissions = true;
16611                }
16612            }
16613
16614            // Below is only runtime permission handling.
16615            if (!bp.isRuntime()) {
16616                continue;
16617            }
16618
16619            // Never clobber system or policy.
16620            if ((oldFlags & policyOrSystemFlags) != 0) {
16621                continue;
16622            }
16623
16624            // If this permission was granted by default, make sure it is.
16625            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16626                if (permissionsState.grantRuntimePermission(bp, userId)
16627                        != PERMISSION_OPERATION_FAILURE) {
16628                    writeRuntimePermissions = true;
16629                }
16630            // If permission review is enabled the permissions for a legacy apps
16631            // are represented as constantly granted runtime ones, so don't revoke.
16632            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16633                // Otherwise, reset the permission.
16634                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16635                switch (revokeResult) {
16636                    case PERMISSION_OPERATION_SUCCESS:
16637                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16638                        writeRuntimePermissions = true;
16639                        final int appId = ps.appId;
16640                        mHandler.post(new Runnable() {
16641                            @Override
16642                            public void run() {
16643                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16644                            }
16645                        });
16646                    } break;
16647                }
16648            }
16649        }
16650
16651        // Synchronously write as we are taking permissions away.
16652        if (writeRuntimePermissions) {
16653            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16654        }
16655
16656        // Synchronously write as we are taking permissions away.
16657        if (writeInstallPermissions) {
16658            mSettings.writeLPr();
16659        }
16660    }
16661
16662    /**
16663     * Remove entries from the keystore daemon. Will only remove it if the
16664     * {@code appId} is valid.
16665     */
16666    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16667        if (appId < 0) {
16668            return;
16669        }
16670
16671        final KeyStore keyStore = KeyStore.getInstance();
16672        if (keyStore != null) {
16673            if (userId == UserHandle.USER_ALL) {
16674                for (final int individual : sUserManager.getUserIds()) {
16675                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16676                }
16677            } else {
16678                keyStore.clearUid(UserHandle.getUid(userId, appId));
16679            }
16680        } else {
16681            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16682        }
16683    }
16684
16685    @Override
16686    public void deleteApplicationCacheFiles(final String packageName,
16687            final IPackageDataObserver observer) {
16688        final int userId = UserHandle.getCallingUserId();
16689        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16690    }
16691
16692    @Override
16693    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16694            final IPackageDataObserver observer) {
16695        mContext.enforceCallingOrSelfPermission(
16696                android.Manifest.permission.DELETE_CACHE_FILES, null);
16697        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16698                /* requireFullPermission= */ true, /* checkShell= */ false,
16699                "delete application cache files");
16700
16701        final PackageParser.Package pkg;
16702        synchronized (mPackages) {
16703            pkg = mPackages.get(packageName);
16704        }
16705
16706        // Queue up an async operation since the package deletion may take a little while.
16707        mHandler.post(new Runnable() {
16708            public void run() {
16709                synchronized (mInstallLock) {
16710                    final int flags = StorageManager.FLAG_STORAGE_DE
16711                            | StorageManager.FLAG_STORAGE_CE;
16712                    // We're only clearing cache files, so we don't care if the
16713                    // app is unfrozen and still able to run
16714                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16715                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16716                }
16717                clearExternalStorageDataSync(packageName, userId, false);
16718                if (observer != null) {
16719                    try {
16720                        observer.onRemoveCompleted(packageName, true);
16721                    } catch (RemoteException e) {
16722                        Log.i(TAG, "Observer no longer exists.");
16723                    }
16724                }
16725            }
16726        });
16727    }
16728
16729    @Override
16730    public void getPackageSizeInfo(final String packageName, int userHandle,
16731            final IPackageStatsObserver observer) {
16732        mContext.enforceCallingOrSelfPermission(
16733                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16734        if (packageName == null) {
16735            throw new IllegalArgumentException("Attempt to get size of null packageName");
16736        }
16737
16738        PackageStats stats = new PackageStats(packageName, userHandle);
16739
16740        /*
16741         * Queue up an async operation since the package measurement may take a
16742         * little while.
16743         */
16744        Message msg = mHandler.obtainMessage(INIT_COPY);
16745        msg.obj = new MeasureParams(stats, observer);
16746        mHandler.sendMessage(msg);
16747    }
16748
16749    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16750        final PackageSetting ps;
16751        synchronized (mPackages) {
16752            ps = mSettings.mPackages.get(packageName);
16753            if (ps == null) {
16754                Slog.w(TAG, "Failed to find settings for " + packageName);
16755                return false;
16756            }
16757        }
16758        try {
16759            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16760                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16761                    ps.getCeDataInode(userId), ps.codePathString, stats);
16762        } catch (InstallerException e) {
16763            Slog.w(TAG, String.valueOf(e));
16764            return false;
16765        }
16766
16767        // For now, ignore code size of packages on system partition
16768        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16769            stats.codeSize = 0;
16770        }
16771
16772        return true;
16773    }
16774
16775    private int getUidTargetSdkVersionLockedLPr(int uid) {
16776        Object obj = mSettings.getUserIdLPr(uid);
16777        if (obj instanceof SharedUserSetting) {
16778            final SharedUserSetting sus = (SharedUserSetting) obj;
16779            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16780            final Iterator<PackageSetting> it = sus.packages.iterator();
16781            while (it.hasNext()) {
16782                final PackageSetting ps = it.next();
16783                if (ps.pkg != null) {
16784                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16785                    if (v < vers) vers = v;
16786                }
16787            }
16788            return vers;
16789        } else if (obj instanceof PackageSetting) {
16790            final PackageSetting ps = (PackageSetting) obj;
16791            if (ps.pkg != null) {
16792                return ps.pkg.applicationInfo.targetSdkVersion;
16793            }
16794        }
16795        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16796    }
16797
16798    @Override
16799    public void addPreferredActivity(IntentFilter filter, int match,
16800            ComponentName[] set, ComponentName activity, int userId) {
16801        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16802                "Adding preferred");
16803    }
16804
16805    private void addPreferredActivityInternal(IntentFilter filter, int match,
16806            ComponentName[] set, ComponentName activity, boolean always, int userId,
16807            String opname) {
16808        // writer
16809        int callingUid = Binder.getCallingUid();
16810        enforceCrossUserPermission(callingUid, userId,
16811                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16812        if (filter.countActions() == 0) {
16813            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16814            return;
16815        }
16816        synchronized (mPackages) {
16817            if (mContext.checkCallingOrSelfPermission(
16818                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16819                    != PackageManager.PERMISSION_GRANTED) {
16820                if (getUidTargetSdkVersionLockedLPr(callingUid)
16821                        < Build.VERSION_CODES.FROYO) {
16822                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16823                            + callingUid);
16824                    return;
16825                }
16826                mContext.enforceCallingOrSelfPermission(
16827                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16828            }
16829
16830            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16831            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16832                    + userId + ":");
16833            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16834            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16835            scheduleWritePackageRestrictionsLocked(userId);
16836        }
16837    }
16838
16839    @Override
16840    public void replacePreferredActivity(IntentFilter filter, int match,
16841            ComponentName[] set, ComponentName activity, int userId) {
16842        if (filter.countActions() != 1) {
16843            throw new IllegalArgumentException(
16844                    "replacePreferredActivity expects filter to have only 1 action.");
16845        }
16846        if (filter.countDataAuthorities() != 0
16847                || filter.countDataPaths() != 0
16848                || filter.countDataSchemes() > 1
16849                || filter.countDataTypes() != 0) {
16850            throw new IllegalArgumentException(
16851                    "replacePreferredActivity expects filter to have no data authorities, " +
16852                    "paths, or types; and at most one scheme.");
16853        }
16854
16855        final int callingUid = Binder.getCallingUid();
16856        enforceCrossUserPermission(callingUid, userId,
16857                true /* requireFullPermission */, false /* checkShell */,
16858                "replace preferred activity");
16859        synchronized (mPackages) {
16860            if (mContext.checkCallingOrSelfPermission(
16861                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16862                    != PackageManager.PERMISSION_GRANTED) {
16863                if (getUidTargetSdkVersionLockedLPr(callingUid)
16864                        < Build.VERSION_CODES.FROYO) {
16865                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16866                            + Binder.getCallingUid());
16867                    return;
16868                }
16869                mContext.enforceCallingOrSelfPermission(
16870                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16871            }
16872
16873            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16874            if (pir != null) {
16875                // Get all of the existing entries that exactly match this filter.
16876                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16877                if (existing != null && existing.size() == 1) {
16878                    PreferredActivity cur = existing.get(0);
16879                    if (DEBUG_PREFERRED) {
16880                        Slog.i(TAG, "Checking replace of preferred:");
16881                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16882                        if (!cur.mPref.mAlways) {
16883                            Slog.i(TAG, "  -- CUR; not mAlways!");
16884                        } else {
16885                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16886                            Slog.i(TAG, "  -- CUR: mSet="
16887                                    + Arrays.toString(cur.mPref.mSetComponents));
16888                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16889                            Slog.i(TAG, "  -- NEW: mMatch="
16890                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16891                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16892                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16893                        }
16894                    }
16895                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16896                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16897                            && cur.mPref.sameSet(set)) {
16898                        // Setting the preferred activity to what it happens to be already
16899                        if (DEBUG_PREFERRED) {
16900                            Slog.i(TAG, "Replacing with same preferred activity "
16901                                    + cur.mPref.mShortComponent + " for user "
16902                                    + userId + ":");
16903                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16904                        }
16905                        return;
16906                    }
16907                }
16908
16909                if (existing != null) {
16910                    if (DEBUG_PREFERRED) {
16911                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16912                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16913                    }
16914                    for (int i = 0; i < existing.size(); i++) {
16915                        PreferredActivity pa = existing.get(i);
16916                        if (DEBUG_PREFERRED) {
16917                            Slog.i(TAG, "Removing existing preferred activity "
16918                                    + pa.mPref.mComponent + ":");
16919                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16920                        }
16921                        pir.removeFilter(pa);
16922                    }
16923                }
16924            }
16925            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16926                    "Replacing preferred");
16927        }
16928    }
16929
16930    @Override
16931    public void clearPackagePreferredActivities(String packageName) {
16932        final int uid = Binder.getCallingUid();
16933        // writer
16934        synchronized (mPackages) {
16935            PackageParser.Package pkg = mPackages.get(packageName);
16936            if (pkg == null || pkg.applicationInfo.uid != uid) {
16937                if (mContext.checkCallingOrSelfPermission(
16938                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16939                        != PackageManager.PERMISSION_GRANTED) {
16940                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16941                            < Build.VERSION_CODES.FROYO) {
16942                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16943                                + Binder.getCallingUid());
16944                        return;
16945                    }
16946                    mContext.enforceCallingOrSelfPermission(
16947                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16948                }
16949            }
16950
16951            int user = UserHandle.getCallingUserId();
16952            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16953                scheduleWritePackageRestrictionsLocked(user);
16954            }
16955        }
16956    }
16957
16958    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16959    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16960        ArrayList<PreferredActivity> removed = null;
16961        boolean changed = false;
16962        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16963            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16964            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16965            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16966                continue;
16967            }
16968            Iterator<PreferredActivity> it = pir.filterIterator();
16969            while (it.hasNext()) {
16970                PreferredActivity pa = it.next();
16971                // Mark entry for removal only if it matches the package name
16972                // and the entry is of type "always".
16973                if (packageName == null ||
16974                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16975                                && pa.mPref.mAlways)) {
16976                    if (removed == null) {
16977                        removed = new ArrayList<PreferredActivity>();
16978                    }
16979                    removed.add(pa);
16980                }
16981            }
16982            if (removed != null) {
16983                for (int j=0; j<removed.size(); j++) {
16984                    PreferredActivity pa = removed.get(j);
16985                    pir.removeFilter(pa);
16986                }
16987                changed = true;
16988            }
16989        }
16990        return changed;
16991    }
16992
16993    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16994    private void clearIntentFilterVerificationsLPw(int userId) {
16995        final int packageCount = mPackages.size();
16996        for (int i = 0; i < packageCount; i++) {
16997            PackageParser.Package pkg = mPackages.valueAt(i);
16998            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16999        }
17000    }
17001
17002    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17003    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17004        if (userId == UserHandle.USER_ALL) {
17005            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17006                    sUserManager.getUserIds())) {
17007                for (int oneUserId : sUserManager.getUserIds()) {
17008                    scheduleWritePackageRestrictionsLocked(oneUserId);
17009                }
17010            }
17011        } else {
17012            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17013                scheduleWritePackageRestrictionsLocked(userId);
17014            }
17015        }
17016    }
17017
17018    void clearDefaultBrowserIfNeeded(String packageName) {
17019        for (int oneUserId : sUserManager.getUserIds()) {
17020            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17021            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17022            if (packageName.equals(defaultBrowserPackageName)) {
17023                setDefaultBrowserPackageName(null, oneUserId);
17024            }
17025        }
17026    }
17027
17028    @Override
17029    public void resetApplicationPreferences(int userId) {
17030        mContext.enforceCallingOrSelfPermission(
17031                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17032        final long identity = Binder.clearCallingIdentity();
17033        // writer
17034        try {
17035            synchronized (mPackages) {
17036                clearPackagePreferredActivitiesLPw(null, userId);
17037                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17038                // TODO: We have to reset the default SMS and Phone. This requires
17039                // significant refactoring to keep all default apps in the package
17040                // manager (cleaner but more work) or have the services provide
17041                // callbacks to the package manager to request a default app reset.
17042                applyFactoryDefaultBrowserLPw(userId);
17043                clearIntentFilterVerificationsLPw(userId);
17044                primeDomainVerificationsLPw(userId);
17045                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17046                scheduleWritePackageRestrictionsLocked(userId);
17047            }
17048            resetNetworkPolicies(userId);
17049        } finally {
17050            Binder.restoreCallingIdentity(identity);
17051        }
17052    }
17053
17054    @Override
17055    public int getPreferredActivities(List<IntentFilter> outFilters,
17056            List<ComponentName> outActivities, String packageName) {
17057
17058        int num = 0;
17059        final int userId = UserHandle.getCallingUserId();
17060        // reader
17061        synchronized (mPackages) {
17062            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17063            if (pir != null) {
17064                final Iterator<PreferredActivity> it = pir.filterIterator();
17065                while (it.hasNext()) {
17066                    final PreferredActivity pa = it.next();
17067                    if (packageName == null
17068                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17069                                    && pa.mPref.mAlways)) {
17070                        if (outFilters != null) {
17071                            outFilters.add(new IntentFilter(pa));
17072                        }
17073                        if (outActivities != null) {
17074                            outActivities.add(pa.mPref.mComponent);
17075                        }
17076                    }
17077                }
17078            }
17079        }
17080
17081        return num;
17082    }
17083
17084    @Override
17085    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17086            int userId) {
17087        int callingUid = Binder.getCallingUid();
17088        if (callingUid != Process.SYSTEM_UID) {
17089            throw new SecurityException(
17090                    "addPersistentPreferredActivity can only be run by the system");
17091        }
17092        if (filter.countActions() == 0) {
17093            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17094            return;
17095        }
17096        synchronized (mPackages) {
17097            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17098                    ":");
17099            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17100            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17101                    new PersistentPreferredActivity(filter, activity));
17102            scheduleWritePackageRestrictionsLocked(userId);
17103        }
17104    }
17105
17106    @Override
17107    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17108        int callingUid = Binder.getCallingUid();
17109        if (callingUid != Process.SYSTEM_UID) {
17110            throw new SecurityException(
17111                    "clearPackagePersistentPreferredActivities can only be run by the system");
17112        }
17113        ArrayList<PersistentPreferredActivity> removed = null;
17114        boolean changed = false;
17115        synchronized (mPackages) {
17116            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17117                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17118                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17119                        .valueAt(i);
17120                if (userId != thisUserId) {
17121                    continue;
17122                }
17123                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17124                while (it.hasNext()) {
17125                    PersistentPreferredActivity ppa = it.next();
17126                    // Mark entry for removal only if it matches the package name.
17127                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17128                        if (removed == null) {
17129                            removed = new ArrayList<PersistentPreferredActivity>();
17130                        }
17131                        removed.add(ppa);
17132                    }
17133                }
17134                if (removed != null) {
17135                    for (int j=0; j<removed.size(); j++) {
17136                        PersistentPreferredActivity ppa = removed.get(j);
17137                        ppir.removeFilter(ppa);
17138                    }
17139                    changed = true;
17140                }
17141            }
17142
17143            if (changed) {
17144                scheduleWritePackageRestrictionsLocked(userId);
17145            }
17146        }
17147    }
17148
17149    /**
17150     * Common machinery for picking apart a restored XML blob and passing
17151     * it to a caller-supplied functor to be applied to the running system.
17152     */
17153    private void restoreFromXml(XmlPullParser parser, int userId,
17154            String expectedStartTag, BlobXmlRestorer functor)
17155            throws IOException, XmlPullParserException {
17156        int type;
17157        while ((type = parser.next()) != XmlPullParser.START_TAG
17158                && type != XmlPullParser.END_DOCUMENT) {
17159        }
17160        if (type != XmlPullParser.START_TAG) {
17161            // oops didn't find a start tag?!
17162            if (DEBUG_BACKUP) {
17163                Slog.e(TAG, "Didn't find start tag during restore");
17164            }
17165            return;
17166        }
17167Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17168        // this is supposed to be TAG_PREFERRED_BACKUP
17169        if (!expectedStartTag.equals(parser.getName())) {
17170            if (DEBUG_BACKUP) {
17171                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17172            }
17173            return;
17174        }
17175
17176        // skip interfering stuff, then we're aligned with the backing implementation
17177        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17178Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17179        functor.apply(parser, userId);
17180    }
17181
17182    private interface BlobXmlRestorer {
17183        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17184    }
17185
17186    /**
17187     * Non-Binder method, support for the backup/restore mechanism: write the
17188     * full set of preferred activities in its canonical XML format.  Returns the
17189     * XML output as a byte array, or null if there is none.
17190     */
17191    @Override
17192    public byte[] getPreferredActivityBackup(int userId) {
17193        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17194            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17195        }
17196
17197        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17198        try {
17199            final XmlSerializer serializer = new FastXmlSerializer();
17200            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17201            serializer.startDocument(null, true);
17202            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17203
17204            synchronized (mPackages) {
17205                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17206            }
17207
17208            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17209            serializer.endDocument();
17210            serializer.flush();
17211        } catch (Exception e) {
17212            if (DEBUG_BACKUP) {
17213                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17214            }
17215            return null;
17216        }
17217
17218        return dataStream.toByteArray();
17219    }
17220
17221    @Override
17222    public void restorePreferredActivities(byte[] backup, int userId) {
17223        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17224            throw new SecurityException("Only the system may call restorePreferredActivities()");
17225        }
17226
17227        try {
17228            final XmlPullParser parser = Xml.newPullParser();
17229            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17230            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17231                    new BlobXmlRestorer() {
17232                        @Override
17233                        public void apply(XmlPullParser parser, int userId)
17234                                throws XmlPullParserException, IOException {
17235                            synchronized (mPackages) {
17236                                mSettings.readPreferredActivitiesLPw(parser, userId);
17237                            }
17238                        }
17239                    } );
17240        } catch (Exception e) {
17241            if (DEBUG_BACKUP) {
17242                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17243            }
17244        }
17245    }
17246
17247    /**
17248     * Non-Binder method, support for the backup/restore mechanism: write the
17249     * default browser (etc) settings in its canonical XML format.  Returns the default
17250     * browser XML representation as a byte array, or null if there is none.
17251     */
17252    @Override
17253    public byte[] getDefaultAppsBackup(int userId) {
17254        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17255            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17256        }
17257
17258        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17259        try {
17260            final XmlSerializer serializer = new FastXmlSerializer();
17261            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17262            serializer.startDocument(null, true);
17263            serializer.startTag(null, TAG_DEFAULT_APPS);
17264
17265            synchronized (mPackages) {
17266                mSettings.writeDefaultAppsLPr(serializer, userId);
17267            }
17268
17269            serializer.endTag(null, TAG_DEFAULT_APPS);
17270            serializer.endDocument();
17271            serializer.flush();
17272        } catch (Exception e) {
17273            if (DEBUG_BACKUP) {
17274                Slog.e(TAG, "Unable to write default apps for backup", e);
17275            }
17276            return null;
17277        }
17278
17279        return dataStream.toByteArray();
17280    }
17281
17282    @Override
17283    public void restoreDefaultApps(byte[] backup, int userId) {
17284        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17285            throw new SecurityException("Only the system may call restoreDefaultApps()");
17286        }
17287
17288        try {
17289            final XmlPullParser parser = Xml.newPullParser();
17290            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17291            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17292                    new BlobXmlRestorer() {
17293                        @Override
17294                        public void apply(XmlPullParser parser, int userId)
17295                                throws XmlPullParserException, IOException {
17296                            synchronized (mPackages) {
17297                                mSettings.readDefaultAppsLPw(parser, userId);
17298                            }
17299                        }
17300                    } );
17301        } catch (Exception e) {
17302            if (DEBUG_BACKUP) {
17303                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17304            }
17305        }
17306    }
17307
17308    @Override
17309    public byte[] getIntentFilterVerificationBackup(int userId) {
17310        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17311            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17312        }
17313
17314        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17315        try {
17316            final XmlSerializer serializer = new FastXmlSerializer();
17317            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17318            serializer.startDocument(null, true);
17319            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17320
17321            synchronized (mPackages) {
17322                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17323            }
17324
17325            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17326            serializer.endDocument();
17327            serializer.flush();
17328        } catch (Exception e) {
17329            if (DEBUG_BACKUP) {
17330                Slog.e(TAG, "Unable to write default apps for backup", e);
17331            }
17332            return null;
17333        }
17334
17335        return dataStream.toByteArray();
17336    }
17337
17338    @Override
17339    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17340        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17341            throw new SecurityException("Only the system may call restorePreferredActivities()");
17342        }
17343
17344        try {
17345            final XmlPullParser parser = Xml.newPullParser();
17346            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17347            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17348                    new BlobXmlRestorer() {
17349                        @Override
17350                        public void apply(XmlPullParser parser, int userId)
17351                                throws XmlPullParserException, IOException {
17352                            synchronized (mPackages) {
17353                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17354                                mSettings.writeLPr();
17355                            }
17356                        }
17357                    } );
17358        } catch (Exception e) {
17359            if (DEBUG_BACKUP) {
17360                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17361            }
17362        }
17363    }
17364
17365    @Override
17366    public byte[] getPermissionGrantBackup(int userId) {
17367        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17368            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17369        }
17370
17371        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17372        try {
17373            final XmlSerializer serializer = new FastXmlSerializer();
17374            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17375            serializer.startDocument(null, true);
17376            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17377
17378            synchronized (mPackages) {
17379                serializeRuntimePermissionGrantsLPr(serializer, userId);
17380            }
17381
17382            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17383            serializer.endDocument();
17384            serializer.flush();
17385        } catch (Exception e) {
17386            if (DEBUG_BACKUP) {
17387                Slog.e(TAG, "Unable to write default apps for backup", e);
17388            }
17389            return null;
17390        }
17391
17392        return dataStream.toByteArray();
17393    }
17394
17395    @Override
17396    public void restorePermissionGrants(byte[] backup, int userId) {
17397        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17398            throw new SecurityException("Only the system may call restorePermissionGrants()");
17399        }
17400
17401        try {
17402            final XmlPullParser parser = Xml.newPullParser();
17403            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17404            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17405                    new BlobXmlRestorer() {
17406                        @Override
17407                        public void apply(XmlPullParser parser, int userId)
17408                                throws XmlPullParserException, IOException {
17409                            synchronized (mPackages) {
17410                                processRestoredPermissionGrantsLPr(parser, userId);
17411                            }
17412                        }
17413                    } );
17414        } catch (Exception e) {
17415            if (DEBUG_BACKUP) {
17416                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17417            }
17418        }
17419    }
17420
17421    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17422            throws IOException {
17423        serializer.startTag(null, TAG_ALL_GRANTS);
17424
17425        final int N = mSettings.mPackages.size();
17426        for (int i = 0; i < N; i++) {
17427            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17428            boolean pkgGrantsKnown = false;
17429
17430            PermissionsState packagePerms = ps.getPermissionsState();
17431
17432            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17433                final int grantFlags = state.getFlags();
17434                // only look at grants that are not system/policy fixed
17435                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17436                    final boolean isGranted = state.isGranted();
17437                    // And only back up the user-twiddled state bits
17438                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17439                        final String packageName = mSettings.mPackages.keyAt(i);
17440                        if (!pkgGrantsKnown) {
17441                            serializer.startTag(null, TAG_GRANT);
17442                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17443                            pkgGrantsKnown = true;
17444                        }
17445
17446                        final boolean userSet =
17447                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17448                        final boolean userFixed =
17449                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17450                        final boolean revoke =
17451                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17452
17453                        serializer.startTag(null, TAG_PERMISSION);
17454                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17455                        if (isGranted) {
17456                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17457                        }
17458                        if (userSet) {
17459                            serializer.attribute(null, ATTR_USER_SET, "true");
17460                        }
17461                        if (userFixed) {
17462                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17463                        }
17464                        if (revoke) {
17465                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17466                        }
17467                        serializer.endTag(null, TAG_PERMISSION);
17468                    }
17469                }
17470            }
17471
17472            if (pkgGrantsKnown) {
17473                serializer.endTag(null, TAG_GRANT);
17474            }
17475        }
17476
17477        serializer.endTag(null, TAG_ALL_GRANTS);
17478    }
17479
17480    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17481            throws XmlPullParserException, IOException {
17482        String pkgName = null;
17483        int outerDepth = parser.getDepth();
17484        int type;
17485        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17486                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17487            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17488                continue;
17489            }
17490
17491            final String tagName = parser.getName();
17492            if (tagName.equals(TAG_GRANT)) {
17493                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17494                if (DEBUG_BACKUP) {
17495                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17496                }
17497            } else if (tagName.equals(TAG_PERMISSION)) {
17498
17499                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17500                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17501
17502                int newFlagSet = 0;
17503                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17504                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17505                }
17506                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17507                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17508                }
17509                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17510                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17511                }
17512                if (DEBUG_BACKUP) {
17513                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17514                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17515                }
17516                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17517                if (ps != null) {
17518                    // Already installed so we apply the grant immediately
17519                    if (DEBUG_BACKUP) {
17520                        Slog.v(TAG, "        + already installed; applying");
17521                    }
17522                    PermissionsState perms = ps.getPermissionsState();
17523                    BasePermission bp = mSettings.mPermissions.get(permName);
17524                    if (bp != null) {
17525                        if (isGranted) {
17526                            perms.grantRuntimePermission(bp, userId);
17527                        }
17528                        if (newFlagSet != 0) {
17529                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17530                        }
17531                    }
17532                } else {
17533                    // Need to wait for post-restore install to apply the grant
17534                    if (DEBUG_BACKUP) {
17535                        Slog.v(TAG, "        - not yet installed; saving for later");
17536                    }
17537                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17538                            isGranted, newFlagSet, userId);
17539                }
17540            } else {
17541                PackageManagerService.reportSettingsProblem(Log.WARN,
17542                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17543                XmlUtils.skipCurrentTag(parser);
17544            }
17545        }
17546
17547        scheduleWriteSettingsLocked();
17548        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17549    }
17550
17551    @Override
17552    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17553            int sourceUserId, int targetUserId, int flags) {
17554        mContext.enforceCallingOrSelfPermission(
17555                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17556        int callingUid = Binder.getCallingUid();
17557        enforceOwnerRights(ownerPackage, callingUid);
17558        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17559        if (intentFilter.countActions() == 0) {
17560            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17561            return;
17562        }
17563        synchronized (mPackages) {
17564            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17565                    ownerPackage, targetUserId, flags);
17566            CrossProfileIntentResolver resolver =
17567                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17568            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17569            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17570            if (existing != null) {
17571                int size = existing.size();
17572                for (int i = 0; i < size; i++) {
17573                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17574                        return;
17575                    }
17576                }
17577            }
17578            resolver.addFilter(newFilter);
17579            scheduleWritePackageRestrictionsLocked(sourceUserId);
17580        }
17581    }
17582
17583    @Override
17584    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17585        mContext.enforceCallingOrSelfPermission(
17586                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17587        int callingUid = Binder.getCallingUid();
17588        enforceOwnerRights(ownerPackage, callingUid);
17589        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17590        synchronized (mPackages) {
17591            CrossProfileIntentResolver resolver =
17592                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17593            ArraySet<CrossProfileIntentFilter> set =
17594                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17595            for (CrossProfileIntentFilter filter : set) {
17596                if (filter.getOwnerPackage().equals(ownerPackage)) {
17597                    resolver.removeFilter(filter);
17598                }
17599            }
17600            scheduleWritePackageRestrictionsLocked(sourceUserId);
17601        }
17602    }
17603
17604    // Enforcing that callingUid is owning pkg on userId
17605    private void enforceOwnerRights(String pkg, int callingUid) {
17606        // The system owns everything.
17607        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17608            return;
17609        }
17610        int callingUserId = UserHandle.getUserId(callingUid);
17611        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17612        if (pi == null) {
17613            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17614                    + callingUserId);
17615        }
17616        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17617            throw new SecurityException("Calling uid " + callingUid
17618                    + " does not own package " + pkg);
17619        }
17620    }
17621
17622    @Override
17623    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17624        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17625    }
17626
17627    private Intent getHomeIntent() {
17628        Intent intent = new Intent(Intent.ACTION_MAIN);
17629        intent.addCategory(Intent.CATEGORY_HOME);
17630        intent.addCategory(Intent.CATEGORY_DEFAULT);
17631        return intent;
17632    }
17633
17634    private IntentFilter getHomeFilter() {
17635        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17636        filter.addCategory(Intent.CATEGORY_HOME);
17637        filter.addCategory(Intent.CATEGORY_DEFAULT);
17638        return filter;
17639    }
17640
17641    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17642            int userId) {
17643        Intent intent  = getHomeIntent();
17644        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17645                PackageManager.GET_META_DATA, userId);
17646        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17647                true, false, false, userId);
17648
17649        allHomeCandidates.clear();
17650        if (list != null) {
17651            for (ResolveInfo ri : list) {
17652                allHomeCandidates.add(ri);
17653            }
17654        }
17655        return (preferred == null || preferred.activityInfo == null)
17656                ? null
17657                : new ComponentName(preferred.activityInfo.packageName,
17658                        preferred.activityInfo.name);
17659    }
17660
17661    @Override
17662    public void setHomeActivity(ComponentName comp, int userId) {
17663        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17664        getHomeActivitiesAsUser(homeActivities, userId);
17665
17666        boolean found = false;
17667
17668        final int size = homeActivities.size();
17669        final ComponentName[] set = new ComponentName[size];
17670        for (int i = 0; i < size; i++) {
17671            final ResolveInfo candidate = homeActivities.get(i);
17672            final ActivityInfo info = candidate.activityInfo;
17673            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17674            set[i] = activityName;
17675            if (!found && activityName.equals(comp)) {
17676                found = true;
17677            }
17678        }
17679        if (!found) {
17680            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17681                    + userId);
17682        }
17683        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17684                set, comp, userId);
17685    }
17686
17687    private @Nullable String getSetupWizardPackageName() {
17688        final Intent intent = new Intent(Intent.ACTION_MAIN);
17689        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17690
17691        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17692                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17693                        | MATCH_DISABLED_COMPONENTS,
17694                UserHandle.myUserId());
17695        if (matches.size() == 1) {
17696            return matches.get(0).getComponentInfo().packageName;
17697        } else {
17698            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17699                    + ": matches=" + matches);
17700            return null;
17701        }
17702    }
17703
17704    @Override
17705    public void setApplicationEnabledSetting(String appPackageName,
17706            int newState, int flags, int userId, String callingPackage) {
17707        if (!sUserManager.exists(userId)) return;
17708        if (callingPackage == null) {
17709            callingPackage = Integer.toString(Binder.getCallingUid());
17710        }
17711        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17712    }
17713
17714    @Override
17715    public void setComponentEnabledSetting(ComponentName componentName,
17716            int newState, int flags, int userId) {
17717        if (!sUserManager.exists(userId)) return;
17718        setEnabledSetting(componentName.getPackageName(),
17719                componentName.getClassName(), newState, flags, userId, null);
17720    }
17721
17722    private void setEnabledSetting(final String packageName, String className, int newState,
17723            final int flags, int userId, String callingPackage) {
17724        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17725              || newState == COMPONENT_ENABLED_STATE_ENABLED
17726              || newState == COMPONENT_ENABLED_STATE_DISABLED
17727              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17728              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17729            throw new IllegalArgumentException("Invalid new component state: "
17730                    + newState);
17731        }
17732        PackageSetting pkgSetting;
17733        final int uid = Binder.getCallingUid();
17734        final int permission;
17735        if (uid == Process.SYSTEM_UID) {
17736            permission = PackageManager.PERMISSION_GRANTED;
17737        } else {
17738            permission = mContext.checkCallingOrSelfPermission(
17739                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17740        }
17741        enforceCrossUserPermission(uid, userId,
17742                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17743        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17744        boolean sendNow = false;
17745        boolean isApp = (className == null);
17746        String componentName = isApp ? packageName : className;
17747        int packageUid = -1;
17748        ArrayList<String> components;
17749
17750        // writer
17751        synchronized (mPackages) {
17752            pkgSetting = mSettings.mPackages.get(packageName);
17753            if (pkgSetting == null) {
17754                if (className == null) {
17755                    throw new IllegalArgumentException("Unknown package: " + packageName);
17756                }
17757                throw new IllegalArgumentException(
17758                        "Unknown component: " + packageName + "/" + className);
17759            }
17760        }
17761
17762        // Limit who can change which apps
17763        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17764            // Don't allow apps that don't have permission to modify other apps
17765            if (!allowedByPermission) {
17766                throw new SecurityException(
17767                        "Permission Denial: attempt to change component state from pid="
17768                        + Binder.getCallingPid()
17769                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17770            }
17771            // Don't allow changing protected packages.
17772            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17773                throw new SecurityException("Cannot disable a protected package: " + packageName);
17774            }
17775        }
17776
17777        synchronized (mPackages) {
17778            if (uid == Process.SHELL_UID) {
17779                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17780                int oldState = pkgSetting.getEnabled(userId);
17781                if (className == null
17782                    &&
17783                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17784                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17785                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17786                    &&
17787                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17788                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17789                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17790                    // ok
17791                } else {
17792                    throw new SecurityException(
17793                            "Shell cannot change component state for " + packageName + "/"
17794                            + className + " to " + newState);
17795                }
17796            }
17797            if (className == null) {
17798                // We're dealing with an application/package level state change
17799                if (pkgSetting.getEnabled(userId) == newState) {
17800                    // Nothing to do
17801                    return;
17802                }
17803                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17804                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17805                    // Don't care about who enables an app.
17806                    callingPackage = null;
17807                }
17808                pkgSetting.setEnabled(newState, userId, callingPackage);
17809                // pkgSetting.pkg.mSetEnabled = newState;
17810            } else {
17811                // We're dealing with a component level state change
17812                // First, verify that this is a valid class name.
17813                PackageParser.Package pkg = pkgSetting.pkg;
17814                if (pkg == null || !pkg.hasComponentClassName(className)) {
17815                    if (pkg != null &&
17816                            pkg.applicationInfo.targetSdkVersion >=
17817                                    Build.VERSION_CODES.JELLY_BEAN) {
17818                        throw new IllegalArgumentException("Component class " + className
17819                                + " does not exist in " + packageName);
17820                    } else {
17821                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17822                                + className + " does not exist in " + packageName);
17823                    }
17824                }
17825                switch (newState) {
17826                case COMPONENT_ENABLED_STATE_ENABLED:
17827                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17828                        return;
17829                    }
17830                    break;
17831                case COMPONENT_ENABLED_STATE_DISABLED:
17832                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17833                        return;
17834                    }
17835                    break;
17836                case COMPONENT_ENABLED_STATE_DEFAULT:
17837                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17838                        return;
17839                    }
17840                    break;
17841                default:
17842                    Slog.e(TAG, "Invalid new component state: " + newState);
17843                    return;
17844                }
17845            }
17846            scheduleWritePackageRestrictionsLocked(userId);
17847            components = mPendingBroadcasts.get(userId, packageName);
17848            final boolean newPackage = components == null;
17849            if (newPackage) {
17850                components = new ArrayList<String>();
17851            }
17852            if (!components.contains(componentName)) {
17853                components.add(componentName);
17854            }
17855            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17856                sendNow = true;
17857                // Purge entry from pending broadcast list if another one exists already
17858                // since we are sending one right away.
17859                mPendingBroadcasts.remove(userId, packageName);
17860            } else {
17861                if (newPackage) {
17862                    mPendingBroadcasts.put(userId, packageName, components);
17863                }
17864                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17865                    // Schedule a message
17866                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17867                }
17868            }
17869        }
17870
17871        long callingId = Binder.clearCallingIdentity();
17872        try {
17873            if (sendNow) {
17874                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17875                sendPackageChangedBroadcast(packageName,
17876                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17877            }
17878        } finally {
17879            Binder.restoreCallingIdentity(callingId);
17880        }
17881    }
17882
17883    @Override
17884    public void flushPackageRestrictionsAsUser(int userId) {
17885        if (!sUserManager.exists(userId)) {
17886            return;
17887        }
17888        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17889                false /* checkShell */, "flushPackageRestrictions");
17890        synchronized (mPackages) {
17891            mSettings.writePackageRestrictionsLPr(userId);
17892            mDirtyUsers.remove(userId);
17893            if (mDirtyUsers.isEmpty()) {
17894                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17895            }
17896        }
17897    }
17898
17899    private void sendPackageChangedBroadcast(String packageName,
17900            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17901        if (DEBUG_INSTALL)
17902            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17903                    + componentNames);
17904        Bundle extras = new Bundle(4);
17905        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17906        String nameList[] = new String[componentNames.size()];
17907        componentNames.toArray(nameList);
17908        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17909        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17910        extras.putInt(Intent.EXTRA_UID, packageUid);
17911        // If this is not reporting a change of the overall package, then only send it
17912        // to registered receivers.  We don't want to launch a swath of apps for every
17913        // little component state change.
17914        final int flags = !componentNames.contains(packageName)
17915                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17916        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17917                new int[] {UserHandle.getUserId(packageUid)});
17918    }
17919
17920    @Override
17921    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17922        if (!sUserManager.exists(userId)) return;
17923        final int uid = Binder.getCallingUid();
17924        final int permission = mContext.checkCallingOrSelfPermission(
17925                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17926        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17927        enforceCrossUserPermission(uid, userId,
17928                true /* requireFullPermission */, true /* checkShell */, "stop package");
17929        // writer
17930        synchronized (mPackages) {
17931            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17932                    allowedByPermission, uid, userId)) {
17933                scheduleWritePackageRestrictionsLocked(userId);
17934            }
17935        }
17936    }
17937
17938    @Override
17939    public String getInstallerPackageName(String packageName) {
17940        // reader
17941        synchronized (mPackages) {
17942            return mSettings.getInstallerPackageNameLPr(packageName);
17943        }
17944    }
17945
17946    public boolean isOrphaned(String packageName) {
17947        // reader
17948        synchronized (mPackages) {
17949            return mSettings.isOrphaned(packageName);
17950        }
17951    }
17952
17953    @Override
17954    public int getApplicationEnabledSetting(String packageName, int userId) {
17955        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17956        int uid = Binder.getCallingUid();
17957        enforceCrossUserPermission(uid, userId,
17958                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17959        // reader
17960        synchronized (mPackages) {
17961            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17962        }
17963    }
17964
17965    @Override
17966    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17967        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17968        int uid = Binder.getCallingUid();
17969        enforceCrossUserPermission(uid, userId,
17970                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17971        // reader
17972        synchronized (mPackages) {
17973            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17974        }
17975    }
17976
17977    @Override
17978    public void enterSafeMode() {
17979        enforceSystemOrRoot("Only the system can request entering safe mode");
17980
17981        if (!mSystemReady) {
17982            mSafeMode = true;
17983        }
17984    }
17985
17986    @Override
17987    public void systemReady() {
17988        mSystemReady = true;
17989
17990        // Read the compatibilty setting when the system is ready.
17991        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17992                mContext.getContentResolver(),
17993                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17994        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17995        if (DEBUG_SETTINGS) {
17996            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17997        }
17998
17999        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18000
18001        synchronized (mPackages) {
18002            // Verify that all of the preferred activity components actually
18003            // exist.  It is possible for applications to be updated and at
18004            // that point remove a previously declared activity component that
18005            // had been set as a preferred activity.  We try to clean this up
18006            // the next time we encounter that preferred activity, but it is
18007            // possible for the user flow to never be able to return to that
18008            // situation so here we do a sanity check to make sure we haven't
18009            // left any junk around.
18010            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18011            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18012                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18013                removed.clear();
18014                for (PreferredActivity pa : pir.filterSet()) {
18015                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18016                        removed.add(pa);
18017                    }
18018                }
18019                if (removed.size() > 0) {
18020                    for (int r=0; r<removed.size(); r++) {
18021                        PreferredActivity pa = removed.get(r);
18022                        Slog.w(TAG, "Removing dangling preferred activity: "
18023                                + pa.mPref.mComponent);
18024                        pir.removeFilter(pa);
18025                    }
18026                    mSettings.writePackageRestrictionsLPr(
18027                            mSettings.mPreferredActivities.keyAt(i));
18028                }
18029            }
18030
18031            for (int userId : UserManagerService.getInstance().getUserIds()) {
18032                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18033                    grantPermissionsUserIds = ArrayUtils.appendInt(
18034                            grantPermissionsUserIds, userId);
18035                }
18036            }
18037        }
18038        sUserManager.systemReady();
18039
18040        // If we upgraded grant all default permissions before kicking off.
18041        for (int userId : grantPermissionsUserIds) {
18042            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18043        }
18044
18045        // Kick off any messages waiting for system ready
18046        if (mPostSystemReadyMessages != null) {
18047            for (Message msg : mPostSystemReadyMessages) {
18048                msg.sendToTarget();
18049            }
18050            mPostSystemReadyMessages = null;
18051        }
18052
18053        // Watch for external volumes that come and go over time
18054        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18055        storage.registerListener(mStorageListener);
18056
18057        mInstallerService.systemReady();
18058        mPackageDexOptimizer.systemReady();
18059
18060        MountServiceInternal mountServiceInternal = LocalServices.getService(
18061                MountServiceInternal.class);
18062        mountServiceInternal.addExternalStoragePolicy(
18063                new MountServiceInternal.ExternalStorageMountPolicy() {
18064            @Override
18065            public int getMountMode(int uid, String packageName) {
18066                if (Process.isIsolated(uid)) {
18067                    return Zygote.MOUNT_EXTERNAL_NONE;
18068                }
18069                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18070                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18071                }
18072                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18073                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18074                }
18075                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18076                    return Zygote.MOUNT_EXTERNAL_READ;
18077                }
18078                return Zygote.MOUNT_EXTERNAL_WRITE;
18079            }
18080
18081            @Override
18082            public boolean hasExternalStorage(int uid, String packageName) {
18083                return true;
18084            }
18085        });
18086
18087        // Now that we're mostly running, clean up stale users and apps
18088        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18089        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18090    }
18091
18092    @Override
18093    public boolean isSafeMode() {
18094        return mSafeMode;
18095    }
18096
18097    @Override
18098    public boolean hasSystemUidErrors() {
18099        return mHasSystemUidErrors;
18100    }
18101
18102    static String arrayToString(int[] array) {
18103        StringBuffer buf = new StringBuffer(128);
18104        buf.append('[');
18105        if (array != null) {
18106            for (int i=0; i<array.length; i++) {
18107                if (i > 0) buf.append(", ");
18108                buf.append(array[i]);
18109            }
18110        }
18111        buf.append(']');
18112        return buf.toString();
18113    }
18114
18115    static class DumpState {
18116        public static final int DUMP_LIBS = 1 << 0;
18117        public static final int DUMP_FEATURES = 1 << 1;
18118        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18119        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18120        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18121        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18122        public static final int DUMP_PERMISSIONS = 1 << 6;
18123        public static final int DUMP_PACKAGES = 1 << 7;
18124        public static final int DUMP_SHARED_USERS = 1 << 8;
18125        public static final int DUMP_MESSAGES = 1 << 9;
18126        public static final int DUMP_PROVIDERS = 1 << 10;
18127        public static final int DUMP_VERIFIERS = 1 << 11;
18128        public static final int DUMP_PREFERRED = 1 << 12;
18129        public static final int DUMP_PREFERRED_XML = 1 << 13;
18130        public static final int DUMP_KEYSETS = 1 << 14;
18131        public static final int DUMP_VERSION = 1 << 15;
18132        public static final int DUMP_INSTALLS = 1 << 16;
18133        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18134        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18135        public static final int DUMP_FROZEN = 1 << 19;
18136        public static final int DUMP_DEXOPT = 1 << 20;
18137
18138        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18139
18140        private int mTypes;
18141
18142        private int mOptions;
18143
18144        private boolean mTitlePrinted;
18145
18146        private SharedUserSetting mSharedUser;
18147
18148        public boolean isDumping(int type) {
18149            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18150                return true;
18151            }
18152
18153            return (mTypes & type) != 0;
18154        }
18155
18156        public void setDump(int type) {
18157            mTypes |= type;
18158        }
18159
18160        public boolean isOptionEnabled(int option) {
18161            return (mOptions & option) != 0;
18162        }
18163
18164        public void setOptionEnabled(int option) {
18165            mOptions |= option;
18166        }
18167
18168        public boolean onTitlePrinted() {
18169            final boolean printed = mTitlePrinted;
18170            mTitlePrinted = true;
18171            return printed;
18172        }
18173
18174        public boolean getTitlePrinted() {
18175            return mTitlePrinted;
18176        }
18177
18178        public void setTitlePrinted(boolean enabled) {
18179            mTitlePrinted = enabled;
18180        }
18181
18182        public SharedUserSetting getSharedUser() {
18183            return mSharedUser;
18184        }
18185
18186        public void setSharedUser(SharedUserSetting user) {
18187            mSharedUser = user;
18188        }
18189    }
18190
18191    @Override
18192    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18193            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18194        (new PackageManagerShellCommand(this)).exec(
18195                this, in, out, err, args, resultReceiver);
18196    }
18197
18198    @Override
18199    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18200        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18201                != PackageManager.PERMISSION_GRANTED) {
18202            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18203                    + Binder.getCallingPid()
18204                    + ", uid=" + Binder.getCallingUid()
18205                    + " without permission "
18206                    + android.Manifest.permission.DUMP);
18207            return;
18208        }
18209
18210        DumpState dumpState = new DumpState();
18211        boolean fullPreferred = false;
18212        boolean checkin = false;
18213
18214        String packageName = null;
18215        ArraySet<String> permissionNames = null;
18216
18217        int opti = 0;
18218        while (opti < args.length) {
18219            String opt = args[opti];
18220            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18221                break;
18222            }
18223            opti++;
18224
18225            if ("-a".equals(opt)) {
18226                // Right now we only know how to print all.
18227            } else if ("-h".equals(opt)) {
18228                pw.println("Package manager dump options:");
18229                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18230                pw.println("    --checkin: dump for a checkin");
18231                pw.println("    -f: print details of intent filters");
18232                pw.println("    -h: print this help");
18233                pw.println("  cmd may be one of:");
18234                pw.println("    l[ibraries]: list known shared libraries");
18235                pw.println("    f[eatures]: list device features");
18236                pw.println("    k[eysets]: print known keysets");
18237                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18238                pw.println("    perm[issions]: dump permissions");
18239                pw.println("    permission [name ...]: dump declaration and use of given permission");
18240                pw.println("    pref[erred]: print preferred package settings");
18241                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18242                pw.println("    prov[iders]: dump content providers");
18243                pw.println("    p[ackages]: dump installed packages");
18244                pw.println("    s[hared-users]: dump shared user IDs");
18245                pw.println("    m[essages]: print collected runtime messages");
18246                pw.println("    v[erifiers]: print package verifier info");
18247                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18248                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18249                pw.println("    version: print database version info");
18250                pw.println("    write: write current settings now");
18251                pw.println("    installs: details about install sessions");
18252                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18253                pw.println("    dexopt: dump dexopt state");
18254                pw.println("    <package.name>: info about given package");
18255                return;
18256            } else if ("--checkin".equals(opt)) {
18257                checkin = true;
18258            } else if ("-f".equals(opt)) {
18259                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18260            } else {
18261                pw.println("Unknown argument: " + opt + "; use -h for help");
18262            }
18263        }
18264
18265        // Is the caller requesting to dump a particular piece of data?
18266        if (opti < args.length) {
18267            String cmd = args[opti];
18268            opti++;
18269            // Is this a package name?
18270            if ("android".equals(cmd) || cmd.contains(".")) {
18271                packageName = cmd;
18272                // When dumping a single package, we always dump all of its
18273                // filter information since the amount of data will be reasonable.
18274                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18275            } else if ("check-permission".equals(cmd)) {
18276                if (opti >= args.length) {
18277                    pw.println("Error: check-permission missing permission argument");
18278                    return;
18279                }
18280                String perm = args[opti];
18281                opti++;
18282                if (opti >= args.length) {
18283                    pw.println("Error: check-permission missing package argument");
18284                    return;
18285                }
18286                String pkg = args[opti];
18287                opti++;
18288                int user = UserHandle.getUserId(Binder.getCallingUid());
18289                if (opti < args.length) {
18290                    try {
18291                        user = Integer.parseInt(args[opti]);
18292                    } catch (NumberFormatException e) {
18293                        pw.println("Error: check-permission user argument is not a number: "
18294                                + args[opti]);
18295                        return;
18296                    }
18297                }
18298                pw.println(checkPermission(perm, pkg, user));
18299                return;
18300            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18301                dumpState.setDump(DumpState.DUMP_LIBS);
18302            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18303                dumpState.setDump(DumpState.DUMP_FEATURES);
18304            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18305                if (opti >= args.length) {
18306                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18307                            | DumpState.DUMP_SERVICE_RESOLVERS
18308                            | DumpState.DUMP_RECEIVER_RESOLVERS
18309                            | DumpState.DUMP_CONTENT_RESOLVERS);
18310                } else {
18311                    while (opti < args.length) {
18312                        String name = args[opti];
18313                        if ("a".equals(name) || "activity".equals(name)) {
18314                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18315                        } else if ("s".equals(name) || "service".equals(name)) {
18316                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18317                        } else if ("r".equals(name) || "receiver".equals(name)) {
18318                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18319                        } else if ("c".equals(name) || "content".equals(name)) {
18320                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18321                        } else {
18322                            pw.println("Error: unknown resolver table type: " + name);
18323                            return;
18324                        }
18325                        opti++;
18326                    }
18327                }
18328            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18329                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18330            } else if ("permission".equals(cmd)) {
18331                if (opti >= args.length) {
18332                    pw.println("Error: permission requires permission name");
18333                    return;
18334                }
18335                permissionNames = new ArraySet<>();
18336                while (opti < args.length) {
18337                    permissionNames.add(args[opti]);
18338                    opti++;
18339                }
18340                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18341                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18342            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18343                dumpState.setDump(DumpState.DUMP_PREFERRED);
18344            } else if ("preferred-xml".equals(cmd)) {
18345                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18346                if (opti < args.length && "--full".equals(args[opti])) {
18347                    fullPreferred = true;
18348                    opti++;
18349                }
18350            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18351                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18352            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18353                dumpState.setDump(DumpState.DUMP_PACKAGES);
18354            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18355                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18356            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18357                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18358            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18359                dumpState.setDump(DumpState.DUMP_MESSAGES);
18360            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18361                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18362            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18363                    || "intent-filter-verifiers".equals(cmd)) {
18364                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18365            } else if ("version".equals(cmd)) {
18366                dumpState.setDump(DumpState.DUMP_VERSION);
18367            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18368                dumpState.setDump(DumpState.DUMP_KEYSETS);
18369            } else if ("installs".equals(cmd)) {
18370                dumpState.setDump(DumpState.DUMP_INSTALLS);
18371            } else if ("frozen".equals(cmd)) {
18372                dumpState.setDump(DumpState.DUMP_FROZEN);
18373            } else if ("dexopt".equals(cmd)) {
18374                dumpState.setDump(DumpState.DUMP_DEXOPT);
18375            } else if ("write".equals(cmd)) {
18376                synchronized (mPackages) {
18377                    mSettings.writeLPr();
18378                    pw.println("Settings written.");
18379                    return;
18380                }
18381            }
18382        }
18383
18384        if (checkin) {
18385            pw.println("vers,1");
18386        }
18387
18388        // reader
18389        synchronized (mPackages) {
18390            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18391                if (!checkin) {
18392                    if (dumpState.onTitlePrinted())
18393                        pw.println();
18394                    pw.println("Database versions:");
18395                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18396                }
18397            }
18398
18399            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18400                if (!checkin) {
18401                    if (dumpState.onTitlePrinted())
18402                        pw.println();
18403                    pw.println("Verifiers:");
18404                    pw.print("  Required: ");
18405                    pw.print(mRequiredVerifierPackage);
18406                    pw.print(" (uid=");
18407                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18408                            UserHandle.USER_SYSTEM));
18409                    pw.println(")");
18410                } else if (mRequiredVerifierPackage != null) {
18411                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18412                    pw.print(",");
18413                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18414                            UserHandle.USER_SYSTEM));
18415                }
18416            }
18417
18418            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18419                    packageName == null) {
18420                if (mIntentFilterVerifierComponent != null) {
18421                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18422                    if (!checkin) {
18423                        if (dumpState.onTitlePrinted())
18424                            pw.println();
18425                        pw.println("Intent Filter Verifier:");
18426                        pw.print("  Using: ");
18427                        pw.print(verifierPackageName);
18428                        pw.print(" (uid=");
18429                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18430                                UserHandle.USER_SYSTEM));
18431                        pw.println(")");
18432                    } else if (verifierPackageName != null) {
18433                        pw.print("ifv,"); pw.print(verifierPackageName);
18434                        pw.print(",");
18435                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18436                                UserHandle.USER_SYSTEM));
18437                    }
18438                } else {
18439                    pw.println();
18440                    pw.println("No Intent Filter Verifier available!");
18441                }
18442            }
18443
18444            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18445                boolean printedHeader = false;
18446                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18447                while (it.hasNext()) {
18448                    String name = it.next();
18449                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18450                    if (!checkin) {
18451                        if (!printedHeader) {
18452                            if (dumpState.onTitlePrinted())
18453                                pw.println();
18454                            pw.println("Libraries:");
18455                            printedHeader = true;
18456                        }
18457                        pw.print("  ");
18458                    } else {
18459                        pw.print("lib,");
18460                    }
18461                    pw.print(name);
18462                    if (!checkin) {
18463                        pw.print(" -> ");
18464                    }
18465                    if (ent.path != null) {
18466                        if (!checkin) {
18467                            pw.print("(jar) ");
18468                            pw.print(ent.path);
18469                        } else {
18470                            pw.print(",jar,");
18471                            pw.print(ent.path);
18472                        }
18473                    } else {
18474                        if (!checkin) {
18475                            pw.print("(apk) ");
18476                            pw.print(ent.apk);
18477                        } else {
18478                            pw.print(",apk,");
18479                            pw.print(ent.apk);
18480                        }
18481                    }
18482                    pw.println();
18483                }
18484            }
18485
18486            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18487                if (dumpState.onTitlePrinted())
18488                    pw.println();
18489                if (!checkin) {
18490                    pw.println("Features:");
18491                }
18492
18493                for (FeatureInfo feat : mAvailableFeatures.values()) {
18494                    if (checkin) {
18495                        pw.print("feat,");
18496                        pw.print(feat.name);
18497                        pw.print(",");
18498                        pw.println(feat.version);
18499                    } else {
18500                        pw.print("  ");
18501                        pw.print(feat.name);
18502                        if (feat.version > 0) {
18503                            pw.print(" version=");
18504                            pw.print(feat.version);
18505                        }
18506                        pw.println();
18507                    }
18508                }
18509            }
18510
18511            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18512                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18513                        : "Activity Resolver Table:", "  ", packageName,
18514                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18515                    dumpState.setTitlePrinted(true);
18516                }
18517            }
18518            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18519                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18520                        : "Receiver Resolver Table:", "  ", packageName,
18521                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18522                    dumpState.setTitlePrinted(true);
18523                }
18524            }
18525            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18526                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18527                        : "Service Resolver Table:", "  ", packageName,
18528                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18529                    dumpState.setTitlePrinted(true);
18530                }
18531            }
18532            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18533                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18534                        : "Provider Resolver Table:", "  ", packageName,
18535                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18536                    dumpState.setTitlePrinted(true);
18537                }
18538            }
18539
18540            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18541                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18542                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18543                    int user = mSettings.mPreferredActivities.keyAt(i);
18544                    if (pir.dump(pw,
18545                            dumpState.getTitlePrinted()
18546                                ? "\nPreferred Activities User " + user + ":"
18547                                : "Preferred Activities User " + user + ":", "  ",
18548                            packageName, true, false)) {
18549                        dumpState.setTitlePrinted(true);
18550                    }
18551                }
18552            }
18553
18554            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18555                pw.flush();
18556                FileOutputStream fout = new FileOutputStream(fd);
18557                BufferedOutputStream str = new BufferedOutputStream(fout);
18558                XmlSerializer serializer = new FastXmlSerializer();
18559                try {
18560                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18561                    serializer.startDocument(null, true);
18562                    serializer.setFeature(
18563                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18564                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18565                    serializer.endDocument();
18566                    serializer.flush();
18567                } catch (IllegalArgumentException e) {
18568                    pw.println("Failed writing: " + e);
18569                } catch (IllegalStateException e) {
18570                    pw.println("Failed writing: " + e);
18571                } catch (IOException e) {
18572                    pw.println("Failed writing: " + e);
18573                }
18574            }
18575
18576            if (!checkin
18577                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18578                    && packageName == null) {
18579                pw.println();
18580                int count = mSettings.mPackages.size();
18581                if (count == 0) {
18582                    pw.println("No applications!");
18583                    pw.println();
18584                } else {
18585                    final String prefix = "  ";
18586                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18587                    if (allPackageSettings.size() == 0) {
18588                        pw.println("No domain preferred apps!");
18589                        pw.println();
18590                    } else {
18591                        pw.println("App verification status:");
18592                        pw.println();
18593                        count = 0;
18594                        for (PackageSetting ps : allPackageSettings) {
18595                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18596                            if (ivi == null || ivi.getPackageName() == null) continue;
18597                            pw.println(prefix + "Package: " + ivi.getPackageName());
18598                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18599                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18600                            pw.println();
18601                            count++;
18602                        }
18603                        if (count == 0) {
18604                            pw.println(prefix + "No app verification established.");
18605                            pw.println();
18606                        }
18607                        for (int userId : sUserManager.getUserIds()) {
18608                            pw.println("App linkages for user " + userId + ":");
18609                            pw.println();
18610                            count = 0;
18611                            for (PackageSetting ps : allPackageSettings) {
18612                                final long status = ps.getDomainVerificationStatusForUser(userId);
18613                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18614                                    continue;
18615                                }
18616                                pw.println(prefix + "Package: " + ps.name);
18617                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18618                                String statusStr = IntentFilterVerificationInfo.
18619                                        getStatusStringFromValue(status);
18620                                pw.println(prefix + "Status:  " + statusStr);
18621                                pw.println();
18622                                count++;
18623                            }
18624                            if (count == 0) {
18625                                pw.println(prefix + "No configured app linkages.");
18626                                pw.println();
18627                            }
18628                        }
18629                    }
18630                }
18631            }
18632
18633            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18634                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18635                if (packageName == null && permissionNames == null) {
18636                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18637                        if (iperm == 0) {
18638                            if (dumpState.onTitlePrinted())
18639                                pw.println();
18640                            pw.println("AppOp Permissions:");
18641                        }
18642                        pw.print("  AppOp Permission ");
18643                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18644                        pw.println(":");
18645                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18646                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18647                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18648                        }
18649                    }
18650                }
18651            }
18652
18653            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18654                boolean printedSomething = false;
18655                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18656                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18657                        continue;
18658                    }
18659                    if (!printedSomething) {
18660                        if (dumpState.onTitlePrinted())
18661                            pw.println();
18662                        pw.println("Registered ContentProviders:");
18663                        printedSomething = true;
18664                    }
18665                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18666                    pw.print("    "); pw.println(p.toString());
18667                }
18668                printedSomething = false;
18669                for (Map.Entry<String, PackageParser.Provider> entry :
18670                        mProvidersByAuthority.entrySet()) {
18671                    PackageParser.Provider p = entry.getValue();
18672                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18673                        continue;
18674                    }
18675                    if (!printedSomething) {
18676                        if (dumpState.onTitlePrinted())
18677                            pw.println();
18678                        pw.println("ContentProvider Authorities:");
18679                        printedSomething = true;
18680                    }
18681                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18682                    pw.print("    "); pw.println(p.toString());
18683                    if (p.info != null && p.info.applicationInfo != null) {
18684                        final String appInfo = p.info.applicationInfo.toString();
18685                        pw.print("      applicationInfo="); pw.println(appInfo);
18686                    }
18687                }
18688            }
18689
18690            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18691                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18692            }
18693
18694            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18695                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18696            }
18697
18698            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18699                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18700            }
18701
18702            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18703                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18704            }
18705
18706            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18707                // XXX should handle packageName != null by dumping only install data that
18708                // the given package is involved with.
18709                if (dumpState.onTitlePrinted()) pw.println();
18710                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18711            }
18712
18713            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18714                // XXX should handle packageName != null by dumping only install data that
18715                // the given package is involved with.
18716                if (dumpState.onTitlePrinted()) pw.println();
18717
18718                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18719                ipw.println();
18720                ipw.println("Frozen packages:");
18721                ipw.increaseIndent();
18722                if (mFrozenPackages.size() == 0) {
18723                    ipw.println("(none)");
18724                } else {
18725                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18726                        ipw.println(mFrozenPackages.valueAt(i));
18727                    }
18728                }
18729                ipw.decreaseIndent();
18730            }
18731
18732            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18733                if (dumpState.onTitlePrinted()) pw.println();
18734                dumpDexoptStateLPr(pw, packageName);
18735            }
18736
18737            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18738                if (dumpState.onTitlePrinted()) pw.println();
18739                mSettings.dumpReadMessagesLPr(pw, dumpState);
18740
18741                pw.println();
18742                pw.println("Package warning messages:");
18743                BufferedReader in = null;
18744                String line = null;
18745                try {
18746                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18747                    while ((line = in.readLine()) != null) {
18748                        if (line.contains("ignored: updated version")) continue;
18749                        pw.println(line);
18750                    }
18751                } catch (IOException ignored) {
18752                } finally {
18753                    IoUtils.closeQuietly(in);
18754                }
18755            }
18756
18757            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18758                BufferedReader in = null;
18759                String line = null;
18760                try {
18761                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18762                    while ((line = in.readLine()) != null) {
18763                        if (line.contains("ignored: updated version")) continue;
18764                        pw.print("msg,");
18765                        pw.println(line);
18766                    }
18767                } catch (IOException ignored) {
18768                } finally {
18769                    IoUtils.closeQuietly(in);
18770                }
18771            }
18772        }
18773    }
18774
18775    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18776        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18777        ipw.println();
18778        ipw.println("Dexopt state:");
18779        ipw.increaseIndent();
18780        Collection<PackageParser.Package> packages = null;
18781        if (packageName != null) {
18782            PackageParser.Package targetPackage = mPackages.get(packageName);
18783            if (targetPackage != null) {
18784                packages = Collections.singletonList(targetPackage);
18785            } else {
18786                ipw.println("Unable to find package: " + packageName);
18787                return;
18788            }
18789        } else {
18790            packages = mPackages.values();
18791        }
18792
18793        for (PackageParser.Package pkg : packages) {
18794            ipw.println("[" + pkg.packageName + "]");
18795            ipw.increaseIndent();
18796            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18797            ipw.decreaseIndent();
18798        }
18799    }
18800
18801    private String dumpDomainString(String packageName) {
18802        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18803                .getList();
18804        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18805
18806        ArraySet<String> result = new ArraySet<>();
18807        if (iviList.size() > 0) {
18808            for (IntentFilterVerificationInfo ivi : iviList) {
18809                for (String host : ivi.getDomains()) {
18810                    result.add(host);
18811                }
18812            }
18813        }
18814        if (filters != null && filters.size() > 0) {
18815            for (IntentFilter filter : filters) {
18816                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18817                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18818                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18819                    result.addAll(filter.getHostsList());
18820                }
18821            }
18822        }
18823
18824        StringBuilder sb = new StringBuilder(result.size() * 16);
18825        for (String domain : result) {
18826            if (sb.length() > 0) sb.append(" ");
18827            sb.append(domain);
18828        }
18829        return sb.toString();
18830    }
18831
18832    // ------- apps on sdcard specific code -------
18833    static final boolean DEBUG_SD_INSTALL = false;
18834
18835    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18836
18837    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18838
18839    private boolean mMediaMounted = false;
18840
18841    static String getEncryptKey() {
18842        try {
18843            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18844                    SD_ENCRYPTION_KEYSTORE_NAME);
18845            if (sdEncKey == null) {
18846                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18847                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18848                if (sdEncKey == null) {
18849                    Slog.e(TAG, "Failed to create encryption keys");
18850                    return null;
18851                }
18852            }
18853            return sdEncKey;
18854        } catch (NoSuchAlgorithmException nsae) {
18855            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18856            return null;
18857        } catch (IOException ioe) {
18858            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18859            return null;
18860        }
18861    }
18862
18863    /*
18864     * Update media status on PackageManager.
18865     */
18866    @Override
18867    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18868        int callingUid = Binder.getCallingUid();
18869        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18870            throw new SecurityException("Media status can only be updated by the system");
18871        }
18872        // reader; this apparently protects mMediaMounted, but should probably
18873        // be a different lock in that case.
18874        synchronized (mPackages) {
18875            Log.i(TAG, "Updating external media status from "
18876                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18877                    + (mediaStatus ? "mounted" : "unmounted"));
18878            if (DEBUG_SD_INSTALL)
18879                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18880                        + ", mMediaMounted=" + mMediaMounted);
18881            if (mediaStatus == mMediaMounted) {
18882                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18883                        : 0, -1);
18884                mHandler.sendMessage(msg);
18885                return;
18886            }
18887            mMediaMounted = mediaStatus;
18888        }
18889        // Queue up an async operation since the package installation may take a
18890        // little while.
18891        mHandler.post(new Runnable() {
18892            public void run() {
18893                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18894            }
18895        });
18896    }
18897
18898    /**
18899     * Called by MountService when the initial ASECs to scan are available.
18900     * Should block until all the ASEC containers are finished being scanned.
18901     */
18902    public void scanAvailableAsecs() {
18903        updateExternalMediaStatusInner(true, false, false);
18904    }
18905
18906    /*
18907     * Collect information of applications on external media, map them against
18908     * existing containers and update information based on current mount status.
18909     * Please note that we always have to report status if reportStatus has been
18910     * set to true especially when unloading packages.
18911     */
18912    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18913            boolean externalStorage) {
18914        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18915        int[] uidArr = EmptyArray.INT;
18916
18917        final String[] list = PackageHelper.getSecureContainerList();
18918        if (ArrayUtils.isEmpty(list)) {
18919            Log.i(TAG, "No secure containers found");
18920        } else {
18921            // Process list of secure containers and categorize them
18922            // as active or stale based on their package internal state.
18923
18924            // reader
18925            synchronized (mPackages) {
18926                for (String cid : list) {
18927                    // Leave stages untouched for now; installer service owns them
18928                    if (PackageInstallerService.isStageName(cid)) continue;
18929
18930                    if (DEBUG_SD_INSTALL)
18931                        Log.i(TAG, "Processing container " + cid);
18932                    String pkgName = getAsecPackageName(cid);
18933                    if (pkgName == null) {
18934                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18935                        continue;
18936                    }
18937                    if (DEBUG_SD_INSTALL)
18938                        Log.i(TAG, "Looking for pkg : " + pkgName);
18939
18940                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18941                    if (ps == null) {
18942                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18943                        continue;
18944                    }
18945
18946                    /*
18947                     * Skip packages that are not external if we're unmounting
18948                     * external storage.
18949                     */
18950                    if (externalStorage && !isMounted && !isExternal(ps)) {
18951                        continue;
18952                    }
18953
18954                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18955                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18956                    // The package status is changed only if the code path
18957                    // matches between settings and the container id.
18958                    if (ps.codePathString != null
18959                            && ps.codePathString.startsWith(args.getCodePath())) {
18960                        if (DEBUG_SD_INSTALL) {
18961                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18962                                    + " at code path: " + ps.codePathString);
18963                        }
18964
18965                        // We do have a valid package installed on sdcard
18966                        processCids.put(args, ps.codePathString);
18967                        final int uid = ps.appId;
18968                        if (uid != -1) {
18969                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18970                        }
18971                    } else {
18972                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18973                                + ps.codePathString);
18974                    }
18975                }
18976            }
18977
18978            Arrays.sort(uidArr);
18979        }
18980
18981        // Process packages with valid entries.
18982        if (isMounted) {
18983            if (DEBUG_SD_INSTALL)
18984                Log.i(TAG, "Loading packages");
18985            loadMediaPackages(processCids, uidArr, externalStorage);
18986            startCleaningPackages();
18987            mInstallerService.onSecureContainersAvailable();
18988        } else {
18989            if (DEBUG_SD_INSTALL)
18990                Log.i(TAG, "Unloading packages");
18991            unloadMediaPackages(processCids, uidArr, reportStatus);
18992        }
18993    }
18994
18995    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18996            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18997        final int size = infos.size();
18998        final String[] packageNames = new String[size];
18999        final int[] packageUids = new int[size];
19000        for (int i = 0; i < size; i++) {
19001            final ApplicationInfo info = infos.get(i);
19002            packageNames[i] = info.packageName;
19003            packageUids[i] = info.uid;
19004        }
19005        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19006                finishedReceiver);
19007    }
19008
19009    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19010            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19011        sendResourcesChangedBroadcast(mediaStatus, replacing,
19012                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19013    }
19014
19015    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19016            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19017        int size = pkgList.length;
19018        if (size > 0) {
19019            // Send broadcasts here
19020            Bundle extras = new Bundle();
19021            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19022            if (uidArr != null) {
19023                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19024            }
19025            if (replacing) {
19026                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19027            }
19028            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19029                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19030            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19031        }
19032    }
19033
19034   /*
19035     * Look at potentially valid container ids from processCids If package
19036     * information doesn't match the one on record or package scanning fails,
19037     * the cid is added to list of removeCids. We currently don't delete stale
19038     * containers.
19039     */
19040    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19041            boolean externalStorage) {
19042        ArrayList<String> pkgList = new ArrayList<String>();
19043        Set<AsecInstallArgs> keys = processCids.keySet();
19044
19045        for (AsecInstallArgs args : keys) {
19046            String codePath = processCids.get(args);
19047            if (DEBUG_SD_INSTALL)
19048                Log.i(TAG, "Loading container : " + args.cid);
19049            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19050            try {
19051                // Make sure there are no container errors first.
19052                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19053                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19054                            + " when installing from sdcard");
19055                    continue;
19056                }
19057                // Check code path here.
19058                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19059                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19060                            + " does not match one in settings " + codePath);
19061                    continue;
19062                }
19063                // Parse package
19064                int parseFlags = mDefParseFlags;
19065                if (args.isExternalAsec()) {
19066                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19067                }
19068                if (args.isFwdLocked()) {
19069                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19070                }
19071
19072                synchronized (mInstallLock) {
19073                    PackageParser.Package pkg = null;
19074                    try {
19075                        // Sadly we don't know the package name yet to freeze it
19076                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19077                                SCAN_IGNORE_FROZEN, 0, null);
19078                    } catch (PackageManagerException e) {
19079                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19080                    }
19081                    // Scan the package
19082                    if (pkg != null) {
19083                        /*
19084                         * TODO why is the lock being held? doPostInstall is
19085                         * called in other places without the lock. This needs
19086                         * to be straightened out.
19087                         */
19088                        // writer
19089                        synchronized (mPackages) {
19090                            retCode = PackageManager.INSTALL_SUCCEEDED;
19091                            pkgList.add(pkg.packageName);
19092                            // Post process args
19093                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19094                                    pkg.applicationInfo.uid);
19095                        }
19096                    } else {
19097                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19098                    }
19099                }
19100
19101            } finally {
19102                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19103                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19104                }
19105            }
19106        }
19107        // writer
19108        synchronized (mPackages) {
19109            // If the platform SDK has changed since the last time we booted,
19110            // we need to re-grant app permission to catch any new ones that
19111            // appear. This is really a hack, and means that apps can in some
19112            // cases get permissions that the user didn't initially explicitly
19113            // allow... it would be nice to have some better way to handle
19114            // this situation.
19115            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19116                    : mSettings.getInternalVersion();
19117            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19118                    : StorageManager.UUID_PRIVATE_INTERNAL;
19119
19120            int updateFlags = UPDATE_PERMISSIONS_ALL;
19121            if (ver.sdkVersion != mSdkVersion) {
19122                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19123                        + mSdkVersion + "; regranting permissions for external");
19124                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19125            }
19126            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19127
19128            // Yay, everything is now upgraded
19129            ver.forceCurrent();
19130
19131            // can downgrade to reader
19132            // Persist settings
19133            mSettings.writeLPr();
19134        }
19135        // Send a broadcast to let everyone know we are done processing
19136        if (pkgList.size() > 0) {
19137            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19138        }
19139    }
19140
19141   /*
19142     * Utility method to unload a list of specified containers
19143     */
19144    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19145        // Just unmount all valid containers.
19146        for (AsecInstallArgs arg : cidArgs) {
19147            synchronized (mInstallLock) {
19148                arg.doPostDeleteLI(false);
19149           }
19150       }
19151   }
19152
19153    /*
19154     * Unload packages mounted on external media. This involves deleting package
19155     * data from internal structures, sending broadcasts about disabled packages,
19156     * gc'ing to free up references, unmounting all secure containers
19157     * corresponding to packages on external media, and posting a
19158     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19159     * that we always have to post this message if status has been requested no
19160     * matter what.
19161     */
19162    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19163            final boolean reportStatus) {
19164        if (DEBUG_SD_INSTALL)
19165            Log.i(TAG, "unloading media packages");
19166        ArrayList<String> pkgList = new ArrayList<String>();
19167        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19168        final Set<AsecInstallArgs> keys = processCids.keySet();
19169        for (AsecInstallArgs args : keys) {
19170            String pkgName = args.getPackageName();
19171            if (DEBUG_SD_INSTALL)
19172                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19173            // Delete package internally
19174            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19175            synchronized (mInstallLock) {
19176                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19177                final boolean res;
19178                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19179                        "unloadMediaPackages")) {
19180                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19181                            null);
19182                }
19183                if (res) {
19184                    pkgList.add(pkgName);
19185                } else {
19186                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19187                    failedList.add(args);
19188                }
19189            }
19190        }
19191
19192        // reader
19193        synchronized (mPackages) {
19194            // We didn't update the settings after removing each package;
19195            // write them now for all packages.
19196            mSettings.writeLPr();
19197        }
19198
19199        // We have to absolutely send UPDATED_MEDIA_STATUS only
19200        // after confirming that all the receivers processed the ordered
19201        // broadcast when packages get disabled, force a gc to clean things up.
19202        // and unload all the containers.
19203        if (pkgList.size() > 0) {
19204            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19205                    new IIntentReceiver.Stub() {
19206                public void performReceive(Intent intent, int resultCode, String data,
19207                        Bundle extras, boolean ordered, boolean sticky,
19208                        int sendingUser) throws RemoteException {
19209                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19210                            reportStatus ? 1 : 0, 1, keys);
19211                    mHandler.sendMessage(msg);
19212                }
19213            });
19214        } else {
19215            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19216                    keys);
19217            mHandler.sendMessage(msg);
19218        }
19219    }
19220
19221    private void loadPrivatePackages(final VolumeInfo vol) {
19222        mHandler.post(new Runnable() {
19223            @Override
19224            public void run() {
19225                loadPrivatePackagesInner(vol);
19226            }
19227        });
19228    }
19229
19230    private void loadPrivatePackagesInner(VolumeInfo vol) {
19231        final String volumeUuid = vol.fsUuid;
19232        if (TextUtils.isEmpty(volumeUuid)) {
19233            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19234            return;
19235        }
19236
19237        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19238        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19239        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19240
19241        final VersionInfo ver;
19242        final List<PackageSetting> packages;
19243        synchronized (mPackages) {
19244            ver = mSettings.findOrCreateVersion(volumeUuid);
19245            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19246        }
19247
19248        for (PackageSetting ps : packages) {
19249            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19250            synchronized (mInstallLock) {
19251                final PackageParser.Package pkg;
19252                try {
19253                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19254                    loaded.add(pkg.applicationInfo);
19255
19256                } catch (PackageManagerException e) {
19257                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19258                }
19259
19260                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19261                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19262                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19263                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19264                }
19265            }
19266        }
19267
19268        // Reconcile app data for all started/unlocked users
19269        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19270        final UserManager um = mContext.getSystemService(UserManager.class);
19271        UserManagerInternal umInternal = getUserManagerInternal();
19272        for (UserInfo user : um.getUsers()) {
19273            final int flags;
19274            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19275                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19276            } else if (umInternal.isUserRunning(user.id)) {
19277                flags = StorageManager.FLAG_STORAGE_DE;
19278            } else {
19279                continue;
19280            }
19281
19282            try {
19283                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19284                synchronized (mInstallLock) {
19285                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19286                }
19287            } catch (IllegalStateException e) {
19288                // Device was probably ejected, and we'll process that event momentarily
19289                Slog.w(TAG, "Failed to prepare storage: " + e);
19290            }
19291        }
19292
19293        synchronized (mPackages) {
19294            int updateFlags = UPDATE_PERMISSIONS_ALL;
19295            if (ver.sdkVersion != mSdkVersion) {
19296                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19297                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19298                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19299            }
19300            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19301
19302            // Yay, everything is now upgraded
19303            ver.forceCurrent();
19304
19305            mSettings.writeLPr();
19306        }
19307
19308        for (PackageFreezer freezer : freezers) {
19309            freezer.close();
19310        }
19311
19312        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19313        sendResourcesChangedBroadcast(true, false, loaded, null);
19314    }
19315
19316    private void unloadPrivatePackages(final VolumeInfo vol) {
19317        mHandler.post(new Runnable() {
19318            @Override
19319            public void run() {
19320                unloadPrivatePackagesInner(vol);
19321            }
19322        });
19323    }
19324
19325    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19326        final String volumeUuid = vol.fsUuid;
19327        if (TextUtils.isEmpty(volumeUuid)) {
19328            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19329            return;
19330        }
19331
19332        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19333        synchronized (mInstallLock) {
19334        synchronized (mPackages) {
19335            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19336            for (PackageSetting ps : packages) {
19337                if (ps.pkg == null) continue;
19338
19339                final ApplicationInfo info = ps.pkg.applicationInfo;
19340                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19341                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19342
19343                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19344                        "unloadPrivatePackagesInner")) {
19345                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19346                            false, null)) {
19347                        unloaded.add(info);
19348                    } else {
19349                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19350                    }
19351                }
19352
19353                // Try very hard to release any references to this package
19354                // so we don't risk the system server being killed due to
19355                // open FDs
19356                AttributeCache.instance().removePackage(ps.name);
19357            }
19358
19359            mSettings.writeLPr();
19360        }
19361        }
19362
19363        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19364        sendResourcesChangedBroadcast(false, false, unloaded, null);
19365
19366        // Try very hard to release any references to this path so we don't risk
19367        // the system server being killed due to open FDs
19368        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19369
19370        for (int i = 0; i < 3; i++) {
19371            System.gc();
19372            System.runFinalization();
19373        }
19374    }
19375
19376    /**
19377     * Prepare storage areas for given user on all mounted devices.
19378     */
19379    void prepareUserData(int userId, int userSerial, int flags) {
19380        synchronized (mInstallLock) {
19381            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19382            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19383                final String volumeUuid = vol.getFsUuid();
19384                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19385            }
19386        }
19387    }
19388
19389    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19390            boolean allowRecover) {
19391        // Prepare storage and verify that serial numbers are consistent; if
19392        // there's a mismatch we need to destroy to avoid leaking data
19393        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19394        try {
19395            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19396
19397            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19398                UserManagerService.enforceSerialNumber(
19399                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19400                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19401                    UserManagerService.enforceSerialNumber(
19402                            Environment.getDataSystemDeDirectory(userId), userSerial);
19403                }
19404            }
19405            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19406                UserManagerService.enforceSerialNumber(
19407                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19408                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19409                    UserManagerService.enforceSerialNumber(
19410                            Environment.getDataSystemCeDirectory(userId), userSerial);
19411                }
19412            }
19413
19414            synchronized (mInstallLock) {
19415                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19416            }
19417        } catch (Exception e) {
19418            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19419                    + " because we failed to prepare: " + e);
19420            destroyUserDataLI(volumeUuid, userId,
19421                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19422
19423            if (allowRecover) {
19424                // Try one last time; if we fail again we're really in trouble
19425                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19426            }
19427        }
19428    }
19429
19430    /**
19431     * Destroy storage areas for given user on all mounted devices.
19432     */
19433    void destroyUserData(int userId, int flags) {
19434        synchronized (mInstallLock) {
19435            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19436            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19437                final String volumeUuid = vol.getFsUuid();
19438                destroyUserDataLI(volumeUuid, userId, flags);
19439            }
19440        }
19441    }
19442
19443    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19444        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19445        try {
19446            // Clean up app data, profile data, and media data
19447            mInstaller.destroyUserData(volumeUuid, userId, flags);
19448
19449            // Clean up system data
19450            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19451                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19452                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19453                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19454                }
19455                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19456                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19457                }
19458            }
19459
19460            // Data with special labels is now gone, so finish the job
19461            storage.destroyUserStorage(volumeUuid, userId, flags);
19462
19463        } catch (Exception e) {
19464            logCriticalInfo(Log.WARN,
19465                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19466        }
19467    }
19468
19469    /**
19470     * Examine all users present on given mounted volume, and destroy data
19471     * belonging to users that are no longer valid, or whose user ID has been
19472     * recycled.
19473     */
19474    private void reconcileUsers(String volumeUuid) {
19475        final List<File> files = new ArrayList<>();
19476        Collections.addAll(files, FileUtils
19477                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19478        Collections.addAll(files, FileUtils
19479                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19480        Collections.addAll(files, FileUtils
19481                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19482        Collections.addAll(files, FileUtils
19483                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19484        for (File file : files) {
19485            if (!file.isDirectory()) continue;
19486
19487            final int userId;
19488            final UserInfo info;
19489            try {
19490                userId = Integer.parseInt(file.getName());
19491                info = sUserManager.getUserInfo(userId);
19492            } catch (NumberFormatException e) {
19493                Slog.w(TAG, "Invalid user directory " + file);
19494                continue;
19495            }
19496
19497            boolean destroyUser = false;
19498            if (info == null) {
19499                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19500                        + " because no matching user was found");
19501                destroyUser = true;
19502            } else if (!mOnlyCore) {
19503                try {
19504                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19505                } catch (IOException e) {
19506                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19507                            + " because we failed to enforce serial number: " + e);
19508                    destroyUser = true;
19509                }
19510            }
19511
19512            if (destroyUser) {
19513                synchronized (mInstallLock) {
19514                    destroyUserDataLI(volumeUuid, userId,
19515                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19516                }
19517            }
19518        }
19519    }
19520
19521    private void assertPackageKnown(String volumeUuid, String packageName)
19522            throws PackageManagerException {
19523        synchronized (mPackages) {
19524            final PackageSetting ps = mSettings.mPackages.get(packageName);
19525            if (ps == null) {
19526                throw new PackageManagerException("Package " + packageName + " is unknown");
19527            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19528                throw new PackageManagerException(
19529                        "Package " + packageName + " found on unknown volume " + volumeUuid
19530                                + "; expected volume " + ps.volumeUuid);
19531            }
19532        }
19533    }
19534
19535    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19536            throws PackageManagerException {
19537        synchronized (mPackages) {
19538            final PackageSetting ps = mSettings.mPackages.get(packageName);
19539            if (ps == null) {
19540                throw new PackageManagerException("Package " + packageName + " is unknown");
19541            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19542                throw new PackageManagerException(
19543                        "Package " + packageName + " found on unknown volume " + volumeUuid
19544                                + "; expected volume " + ps.volumeUuid);
19545            } else if (!ps.getInstalled(userId)) {
19546                throw new PackageManagerException(
19547                        "Package " + packageName + " not installed for user " + userId);
19548            }
19549        }
19550    }
19551
19552    /**
19553     * Examine all apps present on given mounted volume, and destroy apps that
19554     * aren't expected, either due to uninstallation or reinstallation on
19555     * another volume.
19556     */
19557    private void reconcileApps(String volumeUuid) {
19558        final File[] files = FileUtils
19559                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19560        for (File file : files) {
19561            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19562                    && !PackageInstallerService.isStageName(file.getName());
19563            if (!isPackage) {
19564                // Ignore entries which are not packages
19565                continue;
19566            }
19567
19568            try {
19569                final PackageLite pkg = PackageParser.parsePackageLite(file,
19570                        PackageParser.PARSE_MUST_BE_APK);
19571                assertPackageKnown(volumeUuid, pkg.packageName);
19572
19573            } catch (PackageParserException | PackageManagerException e) {
19574                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19575                synchronized (mInstallLock) {
19576                    removeCodePathLI(file);
19577                }
19578            }
19579        }
19580    }
19581
19582    /**
19583     * Reconcile all app data for the given user.
19584     * <p>
19585     * Verifies that directories exist and that ownership and labeling is
19586     * correct for all installed apps on all mounted volumes.
19587     */
19588    void reconcileAppsData(int userId, int flags) {
19589        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19590        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19591            final String volumeUuid = vol.getFsUuid();
19592            synchronized (mInstallLock) {
19593                reconcileAppsDataLI(volumeUuid, userId, flags);
19594            }
19595        }
19596    }
19597
19598    /**
19599     * Reconcile all app data on given mounted volume.
19600     * <p>
19601     * Destroys app data that isn't expected, either due to uninstallation or
19602     * reinstallation on another volume.
19603     * <p>
19604     * Verifies that directories exist and that ownership and labeling is
19605     * correct for all installed apps.
19606     */
19607    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19608        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19609                + Integer.toHexString(flags));
19610
19611        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19612        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19613
19614        boolean restoreconNeeded = false;
19615
19616        // First look for stale data that doesn't belong, and check if things
19617        // have changed since we did our last restorecon
19618        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19619            if (StorageManager.isFileEncryptedNativeOrEmulated()
19620                    && !StorageManager.isUserKeyUnlocked(userId)) {
19621                throw new RuntimeException(
19622                        "Yikes, someone asked us to reconcile CE storage while " + userId
19623                                + " was still locked; this would have caused massive data loss!");
19624            }
19625
19626            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19627
19628            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19629            for (File file : files) {
19630                final String packageName = file.getName();
19631                try {
19632                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19633                } catch (PackageManagerException e) {
19634                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19635                    try {
19636                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19637                                StorageManager.FLAG_STORAGE_CE, 0);
19638                    } catch (InstallerException e2) {
19639                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19640                    }
19641                }
19642            }
19643        }
19644        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19645            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19646
19647            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19648            for (File file : files) {
19649                final String packageName = file.getName();
19650                try {
19651                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19652                } catch (PackageManagerException e) {
19653                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19654                    try {
19655                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19656                                StorageManager.FLAG_STORAGE_DE, 0);
19657                    } catch (InstallerException e2) {
19658                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19659                    }
19660                }
19661            }
19662        }
19663
19664        // Ensure that data directories are ready to roll for all packages
19665        // installed for this volume and user
19666        final List<PackageSetting> packages;
19667        synchronized (mPackages) {
19668            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19669        }
19670        int preparedCount = 0;
19671        for (PackageSetting ps : packages) {
19672            final String packageName = ps.name;
19673            if (ps.pkg == null) {
19674                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19675                // TODO: might be due to legacy ASEC apps; we should circle back
19676                // and reconcile again once they're scanned
19677                continue;
19678            }
19679
19680            if (ps.getInstalled(userId)) {
19681                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19682
19683                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19684                    // We may have just shuffled around app data directories, so
19685                    // prepare them one more time
19686                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19687                }
19688
19689                preparedCount++;
19690            }
19691        }
19692
19693        if (restoreconNeeded) {
19694            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19695                SELinuxMMAC.setRestoreconDone(ceDir);
19696            }
19697            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19698                SELinuxMMAC.setRestoreconDone(deDir);
19699            }
19700        }
19701
19702        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19703                + " packages; restoreconNeeded was " + restoreconNeeded);
19704    }
19705
19706    /**
19707     * Prepare app data for the given app just after it was installed or
19708     * upgraded. This method carefully only touches users that it's installed
19709     * for, and it forces a restorecon to handle any seinfo changes.
19710     * <p>
19711     * Verifies that directories exist and that ownership and labeling is
19712     * correct for all installed apps. If there is an ownership mismatch, it
19713     * will try recovering system apps by wiping data; third-party app data is
19714     * left intact.
19715     * <p>
19716     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19717     */
19718    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19719        final PackageSetting ps;
19720        synchronized (mPackages) {
19721            ps = mSettings.mPackages.get(pkg.packageName);
19722            mSettings.writeKernelMappingLPr(ps);
19723        }
19724
19725        final UserManager um = mContext.getSystemService(UserManager.class);
19726        UserManagerInternal umInternal = getUserManagerInternal();
19727        for (UserInfo user : um.getUsers()) {
19728            final int flags;
19729            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19730                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19731            } else if (umInternal.isUserRunning(user.id)) {
19732                flags = StorageManager.FLAG_STORAGE_DE;
19733            } else {
19734                continue;
19735            }
19736
19737            if (ps.getInstalled(user.id)) {
19738                // Whenever an app changes, force a restorecon of its data
19739                // TODO: when user data is locked, mark that we're still dirty
19740                prepareAppDataLIF(pkg, user.id, flags, true);
19741            }
19742        }
19743    }
19744
19745    /**
19746     * Prepare app data for the given app.
19747     * <p>
19748     * Verifies that directories exist and that ownership and labeling is
19749     * correct for all installed apps. If there is an ownership mismatch, this
19750     * will try recovering system apps by wiping data; third-party app data is
19751     * left intact.
19752     */
19753    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19754            boolean restoreconNeeded) {
19755        if (pkg == null) {
19756            Slog.wtf(TAG, "Package was null!", new Throwable());
19757            return;
19758        }
19759        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19760        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19761        for (int i = 0; i < childCount; i++) {
19762            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19763        }
19764    }
19765
19766    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19767            boolean restoreconNeeded) {
19768        if (DEBUG_APP_DATA) {
19769            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19770                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19771        }
19772
19773        final String volumeUuid = pkg.volumeUuid;
19774        final String packageName = pkg.packageName;
19775        final ApplicationInfo app = pkg.applicationInfo;
19776        final int appId = UserHandle.getAppId(app.uid);
19777
19778        Preconditions.checkNotNull(app.seinfo);
19779
19780        try {
19781            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19782                    appId, app.seinfo, app.targetSdkVersion);
19783        } catch (InstallerException e) {
19784            if (app.isSystemApp()) {
19785                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19786                        + ", but trying to recover: " + e);
19787                destroyAppDataLeafLIF(pkg, userId, flags);
19788                try {
19789                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19790                            appId, app.seinfo, app.targetSdkVersion);
19791                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19792                } catch (InstallerException e2) {
19793                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19794                }
19795            } else {
19796                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19797            }
19798        }
19799
19800        if (restoreconNeeded) {
19801            try {
19802                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19803                        app.seinfo);
19804            } catch (InstallerException e) {
19805                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19806            }
19807        }
19808
19809        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19810            try {
19811                // CE storage is unlocked right now, so read out the inode and
19812                // remember for use later when it's locked
19813                // TODO: mark this structure as dirty so we persist it!
19814                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19815                        StorageManager.FLAG_STORAGE_CE);
19816                synchronized (mPackages) {
19817                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19818                    if (ps != null) {
19819                        ps.setCeDataInode(ceDataInode, userId);
19820                    }
19821                }
19822            } catch (InstallerException e) {
19823                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19824            }
19825        }
19826
19827        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19828    }
19829
19830    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19831        if (pkg == null) {
19832            Slog.wtf(TAG, "Package was null!", new Throwable());
19833            return;
19834        }
19835        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19836        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19837        for (int i = 0; i < childCount; i++) {
19838            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19839        }
19840    }
19841
19842    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19843        final String volumeUuid = pkg.volumeUuid;
19844        final String packageName = pkg.packageName;
19845        final ApplicationInfo app = pkg.applicationInfo;
19846
19847        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19848            // Create a native library symlink only if we have native libraries
19849            // and if the native libraries are 32 bit libraries. We do not provide
19850            // this symlink for 64 bit libraries.
19851            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19852                final String nativeLibPath = app.nativeLibraryDir;
19853                try {
19854                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19855                            nativeLibPath, userId);
19856                } catch (InstallerException e) {
19857                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19858                }
19859            }
19860        }
19861    }
19862
19863    /**
19864     * For system apps on non-FBE devices, this method migrates any existing
19865     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19866     * requested by the app.
19867     */
19868    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19869        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19870                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19871            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19872                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19873            try {
19874                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19875                        storageTarget);
19876            } catch (InstallerException e) {
19877                logCriticalInfo(Log.WARN,
19878                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19879            }
19880            return true;
19881        } else {
19882            return false;
19883        }
19884    }
19885
19886    public PackageFreezer freezePackage(String packageName, String killReason) {
19887        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19888    }
19889
19890    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19891        return new PackageFreezer(packageName, userId, killReason);
19892    }
19893
19894    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19895            String killReason) {
19896        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19897    }
19898
19899    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19900            String killReason) {
19901        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19902            return new PackageFreezer();
19903        } else {
19904            return freezePackage(packageName, userId, killReason);
19905        }
19906    }
19907
19908    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19909            String killReason) {
19910        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19911    }
19912
19913    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19914            String killReason) {
19915        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19916            return new PackageFreezer();
19917        } else {
19918            return freezePackage(packageName, userId, killReason);
19919        }
19920    }
19921
19922    /**
19923     * Class that freezes and kills the given package upon creation, and
19924     * unfreezes it upon closing. This is typically used when doing surgery on
19925     * app code/data to prevent the app from running while you're working.
19926     */
19927    private class PackageFreezer implements AutoCloseable {
19928        private final String mPackageName;
19929        private final PackageFreezer[] mChildren;
19930
19931        private final boolean mWeFroze;
19932
19933        private final AtomicBoolean mClosed = new AtomicBoolean();
19934        private final CloseGuard mCloseGuard = CloseGuard.get();
19935
19936        /**
19937         * Create and return a stub freezer that doesn't actually do anything,
19938         * typically used when someone requested
19939         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19940         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19941         */
19942        public PackageFreezer() {
19943            mPackageName = null;
19944            mChildren = null;
19945            mWeFroze = false;
19946            mCloseGuard.open("close");
19947        }
19948
19949        public PackageFreezer(String packageName, int userId, String killReason) {
19950            synchronized (mPackages) {
19951                mPackageName = packageName;
19952                mWeFroze = mFrozenPackages.add(mPackageName);
19953
19954                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19955                if (ps != null) {
19956                    killApplication(ps.name, ps.appId, userId, killReason);
19957                }
19958
19959                final PackageParser.Package p = mPackages.get(packageName);
19960                if (p != null && p.childPackages != null) {
19961                    final int N = p.childPackages.size();
19962                    mChildren = new PackageFreezer[N];
19963                    for (int i = 0; i < N; i++) {
19964                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19965                                userId, killReason);
19966                    }
19967                } else {
19968                    mChildren = null;
19969                }
19970            }
19971            mCloseGuard.open("close");
19972        }
19973
19974        @Override
19975        protected void finalize() throws Throwable {
19976            try {
19977                mCloseGuard.warnIfOpen();
19978                close();
19979            } finally {
19980                super.finalize();
19981            }
19982        }
19983
19984        @Override
19985        public void close() {
19986            mCloseGuard.close();
19987            if (mClosed.compareAndSet(false, true)) {
19988                synchronized (mPackages) {
19989                    if (mWeFroze) {
19990                        mFrozenPackages.remove(mPackageName);
19991                    }
19992
19993                    if (mChildren != null) {
19994                        for (PackageFreezer freezer : mChildren) {
19995                            freezer.close();
19996                        }
19997                    }
19998                }
19999            }
20000        }
20001    }
20002
20003    /**
20004     * Verify that given package is currently frozen.
20005     */
20006    private void checkPackageFrozen(String packageName) {
20007        synchronized (mPackages) {
20008            if (!mFrozenPackages.contains(packageName)) {
20009                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20010            }
20011        }
20012    }
20013
20014    @Override
20015    public int movePackage(final String packageName, final String volumeUuid) {
20016        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20017
20018        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20019        final int moveId = mNextMoveId.getAndIncrement();
20020        mHandler.post(new Runnable() {
20021            @Override
20022            public void run() {
20023                try {
20024                    movePackageInternal(packageName, volumeUuid, moveId, user);
20025                } catch (PackageManagerException e) {
20026                    Slog.w(TAG, "Failed to move " + packageName, e);
20027                    mMoveCallbacks.notifyStatusChanged(moveId,
20028                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20029                }
20030            }
20031        });
20032        return moveId;
20033    }
20034
20035    private void movePackageInternal(final String packageName, final String volumeUuid,
20036            final int moveId, UserHandle user) throws PackageManagerException {
20037        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20038        final PackageManager pm = mContext.getPackageManager();
20039
20040        final boolean currentAsec;
20041        final String currentVolumeUuid;
20042        final File codeFile;
20043        final String installerPackageName;
20044        final String packageAbiOverride;
20045        final int appId;
20046        final String seinfo;
20047        final String label;
20048        final int targetSdkVersion;
20049        final PackageFreezer freezer;
20050        final int[] installedUserIds;
20051
20052        // reader
20053        synchronized (mPackages) {
20054            final PackageParser.Package pkg = mPackages.get(packageName);
20055            final PackageSetting ps = mSettings.mPackages.get(packageName);
20056            if (pkg == null || ps == null) {
20057                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20058            }
20059
20060            if (pkg.applicationInfo.isSystemApp()) {
20061                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20062                        "Cannot move system application");
20063            }
20064
20065            if (pkg.applicationInfo.isExternalAsec()) {
20066                currentAsec = true;
20067                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20068            } else if (pkg.applicationInfo.isForwardLocked()) {
20069                currentAsec = true;
20070                currentVolumeUuid = "forward_locked";
20071            } else {
20072                currentAsec = false;
20073                currentVolumeUuid = ps.volumeUuid;
20074
20075                final File probe = new File(pkg.codePath);
20076                final File probeOat = new File(probe, "oat");
20077                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20078                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20079                            "Move only supported for modern cluster style installs");
20080                }
20081            }
20082
20083            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20084                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20085                        "Package already moved to " + volumeUuid);
20086            }
20087            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20088                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20089                        "Device admin cannot be moved");
20090            }
20091
20092            if (mFrozenPackages.contains(packageName)) {
20093                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20094                        "Failed to move already frozen package");
20095            }
20096
20097            codeFile = new File(pkg.codePath);
20098            installerPackageName = ps.installerPackageName;
20099            packageAbiOverride = ps.cpuAbiOverrideString;
20100            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20101            seinfo = pkg.applicationInfo.seinfo;
20102            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20103            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20104            freezer = freezePackage(packageName, "movePackageInternal");
20105            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20106        }
20107
20108        final Bundle extras = new Bundle();
20109        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20110        extras.putString(Intent.EXTRA_TITLE, label);
20111        mMoveCallbacks.notifyCreated(moveId, extras);
20112
20113        int installFlags;
20114        final boolean moveCompleteApp;
20115        final File measurePath;
20116
20117        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20118            installFlags = INSTALL_INTERNAL;
20119            moveCompleteApp = !currentAsec;
20120            measurePath = Environment.getDataAppDirectory(volumeUuid);
20121        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20122            installFlags = INSTALL_EXTERNAL;
20123            moveCompleteApp = false;
20124            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20125        } else {
20126            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20127            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20128                    || !volume.isMountedWritable()) {
20129                freezer.close();
20130                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20131                        "Move location not mounted private volume");
20132            }
20133
20134            Preconditions.checkState(!currentAsec);
20135
20136            installFlags = INSTALL_INTERNAL;
20137            moveCompleteApp = true;
20138            measurePath = Environment.getDataAppDirectory(volumeUuid);
20139        }
20140
20141        final PackageStats stats = new PackageStats(null, -1);
20142        synchronized (mInstaller) {
20143            for (int userId : installedUserIds) {
20144                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20145                    freezer.close();
20146                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20147                            "Failed to measure package size");
20148                }
20149            }
20150        }
20151
20152        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20153                + stats.dataSize);
20154
20155        final long startFreeBytes = measurePath.getFreeSpace();
20156        final long sizeBytes;
20157        if (moveCompleteApp) {
20158            sizeBytes = stats.codeSize + stats.dataSize;
20159        } else {
20160            sizeBytes = stats.codeSize;
20161        }
20162
20163        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20164            freezer.close();
20165            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20166                    "Not enough free space to move");
20167        }
20168
20169        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20170
20171        final CountDownLatch installedLatch = new CountDownLatch(1);
20172        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20173            @Override
20174            public void onUserActionRequired(Intent intent) throws RemoteException {
20175                throw new IllegalStateException();
20176            }
20177
20178            @Override
20179            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20180                    Bundle extras) throws RemoteException {
20181                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20182                        + PackageManager.installStatusToString(returnCode, msg));
20183
20184                installedLatch.countDown();
20185                freezer.close();
20186
20187                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20188                switch (status) {
20189                    case PackageInstaller.STATUS_SUCCESS:
20190                        mMoveCallbacks.notifyStatusChanged(moveId,
20191                                PackageManager.MOVE_SUCCEEDED);
20192                        break;
20193                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20194                        mMoveCallbacks.notifyStatusChanged(moveId,
20195                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20196                        break;
20197                    default:
20198                        mMoveCallbacks.notifyStatusChanged(moveId,
20199                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20200                        break;
20201                }
20202            }
20203        };
20204
20205        final MoveInfo move;
20206        if (moveCompleteApp) {
20207            // Kick off a thread to report progress estimates
20208            new Thread() {
20209                @Override
20210                public void run() {
20211                    while (true) {
20212                        try {
20213                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20214                                break;
20215                            }
20216                        } catch (InterruptedException ignored) {
20217                        }
20218
20219                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20220                        final int progress = 10 + (int) MathUtils.constrain(
20221                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20222                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20223                    }
20224                }
20225            }.start();
20226
20227            final String dataAppName = codeFile.getName();
20228            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20229                    dataAppName, appId, seinfo, targetSdkVersion);
20230        } else {
20231            move = null;
20232        }
20233
20234        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20235
20236        final Message msg = mHandler.obtainMessage(INIT_COPY);
20237        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20238        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20239                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20240                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20241        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20242        msg.obj = params;
20243
20244        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20245                System.identityHashCode(msg.obj));
20246        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20247                System.identityHashCode(msg.obj));
20248
20249        mHandler.sendMessage(msg);
20250    }
20251
20252    @Override
20253    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20254        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20255
20256        final int realMoveId = mNextMoveId.getAndIncrement();
20257        final Bundle extras = new Bundle();
20258        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20259        mMoveCallbacks.notifyCreated(realMoveId, extras);
20260
20261        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20262            @Override
20263            public void onCreated(int moveId, Bundle extras) {
20264                // Ignored
20265            }
20266
20267            @Override
20268            public void onStatusChanged(int moveId, int status, long estMillis) {
20269                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20270            }
20271        };
20272
20273        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20274        storage.setPrimaryStorageUuid(volumeUuid, callback);
20275        return realMoveId;
20276    }
20277
20278    @Override
20279    public int getMoveStatus(int moveId) {
20280        mContext.enforceCallingOrSelfPermission(
20281                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20282        return mMoveCallbacks.mLastStatus.get(moveId);
20283    }
20284
20285    @Override
20286    public void registerMoveCallback(IPackageMoveObserver callback) {
20287        mContext.enforceCallingOrSelfPermission(
20288                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20289        mMoveCallbacks.register(callback);
20290    }
20291
20292    @Override
20293    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20294        mContext.enforceCallingOrSelfPermission(
20295                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20296        mMoveCallbacks.unregister(callback);
20297    }
20298
20299    @Override
20300    public boolean setInstallLocation(int loc) {
20301        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20302                null);
20303        if (getInstallLocation() == loc) {
20304            return true;
20305        }
20306        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20307                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20308            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20309                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20310            return true;
20311        }
20312        return false;
20313   }
20314
20315    @Override
20316    public int getInstallLocation() {
20317        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20318                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20319                PackageHelper.APP_INSTALL_AUTO);
20320    }
20321
20322    /** Called by UserManagerService */
20323    void cleanUpUser(UserManagerService userManager, int userHandle) {
20324        synchronized (mPackages) {
20325            mDirtyUsers.remove(userHandle);
20326            mUserNeedsBadging.delete(userHandle);
20327            mSettings.removeUserLPw(userHandle);
20328            mPendingBroadcasts.remove(userHandle);
20329            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20330            removeUnusedPackagesLPw(userManager, userHandle);
20331        }
20332    }
20333
20334    /**
20335     * We're removing userHandle and would like to remove any downloaded packages
20336     * that are no longer in use by any other user.
20337     * @param userHandle the user being removed
20338     */
20339    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20340        final boolean DEBUG_CLEAN_APKS = false;
20341        int [] users = userManager.getUserIds();
20342        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20343        while (psit.hasNext()) {
20344            PackageSetting ps = psit.next();
20345            if (ps.pkg == null) {
20346                continue;
20347            }
20348            final String packageName = ps.pkg.packageName;
20349            // Skip over if system app
20350            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20351                continue;
20352            }
20353            if (DEBUG_CLEAN_APKS) {
20354                Slog.i(TAG, "Checking package " + packageName);
20355            }
20356            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20357            if (keep) {
20358                if (DEBUG_CLEAN_APKS) {
20359                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20360                }
20361            } else {
20362                for (int i = 0; i < users.length; i++) {
20363                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20364                        keep = true;
20365                        if (DEBUG_CLEAN_APKS) {
20366                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20367                                    + users[i]);
20368                        }
20369                        break;
20370                    }
20371                }
20372            }
20373            if (!keep) {
20374                if (DEBUG_CLEAN_APKS) {
20375                    Slog.i(TAG, "  Removing package " + packageName);
20376                }
20377                mHandler.post(new Runnable() {
20378                    public void run() {
20379                        deletePackageX(packageName, userHandle, 0);
20380                    } //end run
20381                });
20382            }
20383        }
20384    }
20385
20386    /** Called by UserManagerService */
20387    void createNewUser(int userId) {
20388        synchronized (mInstallLock) {
20389            mSettings.createNewUserLI(this, mInstaller, userId);
20390        }
20391        synchronized (mPackages) {
20392            scheduleWritePackageRestrictionsLocked(userId);
20393            scheduleWritePackageListLocked(userId);
20394            applyFactoryDefaultBrowserLPw(userId);
20395            primeDomainVerificationsLPw(userId);
20396        }
20397    }
20398
20399    void onBeforeUserStartUninitialized(final int userId) {
20400        synchronized (mPackages) {
20401            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20402                return;
20403            }
20404        }
20405        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20406        // If permission review for legacy apps is required, we represent
20407        // dagerous permissions for such apps as always granted runtime
20408        // permissions to keep per user flag state whether review is needed.
20409        // Hence, if a new user is added we have to propagate dangerous
20410        // permission grants for these legacy apps.
20411        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20412            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20413                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20414        }
20415    }
20416
20417    @Override
20418    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20419        mContext.enforceCallingOrSelfPermission(
20420                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20421                "Only package verification agents can read the verifier device identity");
20422
20423        synchronized (mPackages) {
20424            return mSettings.getVerifierDeviceIdentityLPw();
20425        }
20426    }
20427
20428    @Override
20429    public void setPermissionEnforced(String permission, boolean enforced) {
20430        // TODO: Now that we no longer change GID for storage, this should to away.
20431        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20432                "setPermissionEnforced");
20433        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20434            synchronized (mPackages) {
20435                if (mSettings.mReadExternalStorageEnforced == null
20436                        || mSettings.mReadExternalStorageEnforced != enforced) {
20437                    mSettings.mReadExternalStorageEnforced = enforced;
20438                    mSettings.writeLPr();
20439                }
20440            }
20441            // kill any non-foreground processes so we restart them and
20442            // grant/revoke the GID.
20443            final IActivityManager am = ActivityManagerNative.getDefault();
20444            if (am != null) {
20445                final long token = Binder.clearCallingIdentity();
20446                try {
20447                    am.killProcessesBelowForeground("setPermissionEnforcement");
20448                } catch (RemoteException e) {
20449                } finally {
20450                    Binder.restoreCallingIdentity(token);
20451                }
20452            }
20453        } else {
20454            throw new IllegalArgumentException("No selective enforcement for " + permission);
20455        }
20456    }
20457
20458    @Override
20459    @Deprecated
20460    public boolean isPermissionEnforced(String permission) {
20461        return true;
20462    }
20463
20464    @Override
20465    public boolean isStorageLow() {
20466        final long token = Binder.clearCallingIdentity();
20467        try {
20468            final DeviceStorageMonitorInternal
20469                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20470            if (dsm != null) {
20471                return dsm.isMemoryLow();
20472            } else {
20473                return false;
20474            }
20475        } finally {
20476            Binder.restoreCallingIdentity(token);
20477        }
20478    }
20479
20480    @Override
20481    public IPackageInstaller getPackageInstaller() {
20482        return mInstallerService;
20483    }
20484
20485    private boolean userNeedsBadging(int userId) {
20486        int index = mUserNeedsBadging.indexOfKey(userId);
20487        if (index < 0) {
20488            final UserInfo userInfo;
20489            final long token = Binder.clearCallingIdentity();
20490            try {
20491                userInfo = sUserManager.getUserInfo(userId);
20492            } finally {
20493                Binder.restoreCallingIdentity(token);
20494            }
20495            final boolean b;
20496            if (userInfo != null && userInfo.isManagedProfile()) {
20497                b = true;
20498            } else {
20499                b = false;
20500            }
20501            mUserNeedsBadging.put(userId, b);
20502            return b;
20503        }
20504        return mUserNeedsBadging.valueAt(index);
20505    }
20506
20507    @Override
20508    public KeySet getKeySetByAlias(String packageName, String alias) {
20509        if (packageName == null || alias == null) {
20510            return null;
20511        }
20512        synchronized(mPackages) {
20513            final PackageParser.Package pkg = mPackages.get(packageName);
20514            if (pkg == null) {
20515                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20516                throw new IllegalArgumentException("Unknown package: " + packageName);
20517            }
20518            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20519            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20520        }
20521    }
20522
20523    @Override
20524    public KeySet getSigningKeySet(String packageName) {
20525        if (packageName == null) {
20526            return null;
20527        }
20528        synchronized(mPackages) {
20529            final PackageParser.Package pkg = mPackages.get(packageName);
20530            if (pkg == null) {
20531                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20532                throw new IllegalArgumentException("Unknown package: " + packageName);
20533            }
20534            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20535                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20536                throw new SecurityException("May not access signing KeySet of other apps.");
20537            }
20538            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20539            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20540        }
20541    }
20542
20543    @Override
20544    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20545        if (packageName == null || ks == null) {
20546            return false;
20547        }
20548        synchronized(mPackages) {
20549            final PackageParser.Package pkg = mPackages.get(packageName);
20550            if (pkg == null) {
20551                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20552                throw new IllegalArgumentException("Unknown package: " + packageName);
20553            }
20554            IBinder ksh = ks.getToken();
20555            if (ksh instanceof KeySetHandle) {
20556                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20557                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20558            }
20559            return false;
20560        }
20561    }
20562
20563    @Override
20564    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20565        if (packageName == null || ks == null) {
20566            return false;
20567        }
20568        synchronized(mPackages) {
20569            final PackageParser.Package pkg = mPackages.get(packageName);
20570            if (pkg == null) {
20571                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20572                throw new IllegalArgumentException("Unknown package: " + packageName);
20573            }
20574            IBinder ksh = ks.getToken();
20575            if (ksh instanceof KeySetHandle) {
20576                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20577                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20578            }
20579            return false;
20580        }
20581    }
20582
20583    private void deletePackageIfUnusedLPr(final String packageName) {
20584        PackageSetting ps = mSettings.mPackages.get(packageName);
20585        if (ps == null) {
20586            return;
20587        }
20588        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20589            // TODO Implement atomic delete if package is unused
20590            // It is currently possible that the package will be deleted even if it is installed
20591            // after this method returns.
20592            mHandler.post(new Runnable() {
20593                public void run() {
20594                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20595                }
20596            });
20597        }
20598    }
20599
20600    /**
20601     * Check and throw if the given before/after packages would be considered a
20602     * downgrade.
20603     */
20604    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20605            throws PackageManagerException {
20606        if (after.versionCode < before.mVersionCode) {
20607            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20608                    "Update version code " + after.versionCode + " is older than current "
20609                    + before.mVersionCode);
20610        } else if (after.versionCode == before.mVersionCode) {
20611            if (after.baseRevisionCode < before.baseRevisionCode) {
20612                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20613                        "Update base revision code " + after.baseRevisionCode
20614                        + " is older than current " + before.baseRevisionCode);
20615            }
20616
20617            if (!ArrayUtils.isEmpty(after.splitNames)) {
20618                for (int i = 0; i < after.splitNames.length; i++) {
20619                    final String splitName = after.splitNames[i];
20620                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20621                    if (j != -1) {
20622                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20623                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20624                                    "Update split " + splitName + " revision code "
20625                                    + after.splitRevisionCodes[i] + " is older than current "
20626                                    + before.splitRevisionCodes[j]);
20627                        }
20628                    }
20629                }
20630            }
20631        }
20632    }
20633
20634    private static class MoveCallbacks extends Handler {
20635        private static final int MSG_CREATED = 1;
20636        private static final int MSG_STATUS_CHANGED = 2;
20637
20638        private final RemoteCallbackList<IPackageMoveObserver>
20639                mCallbacks = new RemoteCallbackList<>();
20640
20641        private final SparseIntArray mLastStatus = new SparseIntArray();
20642
20643        public MoveCallbacks(Looper looper) {
20644            super(looper);
20645        }
20646
20647        public void register(IPackageMoveObserver callback) {
20648            mCallbacks.register(callback);
20649        }
20650
20651        public void unregister(IPackageMoveObserver callback) {
20652            mCallbacks.unregister(callback);
20653        }
20654
20655        @Override
20656        public void handleMessage(Message msg) {
20657            final SomeArgs args = (SomeArgs) msg.obj;
20658            final int n = mCallbacks.beginBroadcast();
20659            for (int i = 0; i < n; i++) {
20660                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20661                try {
20662                    invokeCallback(callback, msg.what, args);
20663                } catch (RemoteException ignored) {
20664                }
20665            }
20666            mCallbacks.finishBroadcast();
20667            args.recycle();
20668        }
20669
20670        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20671                throws RemoteException {
20672            switch (what) {
20673                case MSG_CREATED: {
20674                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20675                    break;
20676                }
20677                case MSG_STATUS_CHANGED: {
20678                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20679                    break;
20680                }
20681            }
20682        }
20683
20684        private void notifyCreated(int moveId, Bundle extras) {
20685            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20686
20687            final SomeArgs args = SomeArgs.obtain();
20688            args.argi1 = moveId;
20689            args.arg2 = extras;
20690            obtainMessage(MSG_CREATED, args).sendToTarget();
20691        }
20692
20693        private void notifyStatusChanged(int moveId, int status) {
20694            notifyStatusChanged(moveId, status, -1);
20695        }
20696
20697        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20698            Slog.v(TAG, "Move " + moveId + " status " + status);
20699
20700            final SomeArgs args = SomeArgs.obtain();
20701            args.argi1 = moveId;
20702            args.argi2 = status;
20703            args.arg3 = estMillis;
20704            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20705
20706            synchronized (mLastStatus) {
20707                mLastStatus.put(moveId, status);
20708            }
20709        }
20710    }
20711
20712    private final static class OnPermissionChangeListeners extends Handler {
20713        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20714
20715        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20716                new RemoteCallbackList<>();
20717
20718        public OnPermissionChangeListeners(Looper looper) {
20719            super(looper);
20720        }
20721
20722        @Override
20723        public void handleMessage(Message msg) {
20724            switch (msg.what) {
20725                case MSG_ON_PERMISSIONS_CHANGED: {
20726                    final int uid = msg.arg1;
20727                    handleOnPermissionsChanged(uid);
20728                } break;
20729            }
20730        }
20731
20732        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20733            mPermissionListeners.register(listener);
20734
20735        }
20736
20737        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20738            mPermissionListeners.unregister(listener);
20739        }
20740
20741        public void onPermissionsChanged(int uid) {
20742            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20743                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20744            }
20745        }
20746
20747        private void handleOnPermissionsChanged(int uid) {
20748            final int count = mPermissionListeners.beginBroadcast();
20749            try {
20750                for (int i = 0; i < count; i++) {
20751                    IOnPermissionsChangeListener callback = mPermissionListeners
20752                            .getBroadcastItem(i);
20753                    try {
20754                        callback.onPermissionsChanged(uid);
20755                    } catch (RemoteException e) {
20756                        Log.e(TAG, "Permission listener is dead", e);
20757                    }
20758                }
20759            } finally {
20760                mPermissionListeners.finishBroadcast();
20761            }
20762        }
20763    }
20764
20765    private class PackageManagerInternalImpl extends PackageManagerInternal {
20766        @Override
20767        public void setLocationPackagesProvider(PackagesProvider provider) {
20768            synchronized (mPackages) {
20769                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20770            }
20771        }
20772
20773        @Override
20774        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20775            synchronized (mPackages) {
20776                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20777            }
20778        }
20779
20780        @Override
20781        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20782            synchronized (mPackages) {
20783                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20784            }
20785        }
20786
20787        @Override
20788        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20789            synchronized (mPackages) {
20790                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20791            }
20792        }
20793
20794        @Override
20795        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20796            synchronized (mPackages) {
20797                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20798            }
20799        }
20800
20801        @Override
20802        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20803            synchronized (mPackages) {
20804                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20805            }
20806        }
20807
20808        @Override
20809        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20810            synchronized (mPackages) {
20811                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20812                        packageName, userId);
20813            }
20814        }
20815
20816        @Override
20817        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20818            synchronized (mPackages) {
20819                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20820                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20821                        packageName, userId);
20822            }
20823        }
20824
20825        @Override
20826        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20827            synchronized (mPackages) {
20828                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20829                        packageName, userId);
20830            }
20831        }
20832
20833        @Override
20834        public void setKeepUninstalledPackages(final List<String> packageList) {
20835            Preconditions.checkNotNull(packageList);
20836            List<String> removedFromList = null;
20837            synchronized (mPackages) {
20838                if (mKeepUninstalledPackages != null) {
20839                    final int packagesCount = mKeepUninstalledPackages.size();
20840                    for (int i = 0; i < packagesCount; i++) {
20841                        String oldPackage = mKeepUninstalledPackages.get(i);
20842                        if (packageList != null && packageList.contains(oldPackage)) {
20843                            continue;
20844                        }
20845                        if (removedFromList == null) {
20846                            removedFromList = new ArrayList<>();
20847                        }
20848                        removedFromList.add(oldPackage);
20849                    }
20850                }
20851                mKeepUninstalledPackages = new ArrayList<>(packageList);
20852                if (removedFromList != null) {
20853                    final int removedCount = removedFromList.size();
20854                    for (int i = 0; i < removedCount; i++) {
20855                        deletePackageIfUnusedLPr(removedFromList.get(i));
20856                    }
20857                }
20858            }
20859        }
20860
20861        @Override
20862        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20863            synchronized (mPackages) {
20864                // If we do not support permission review, done.
20865                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20866                    return false;
20867                }
20868
20869                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20870                if (packageSetting == null) {
20871                    return false;
20872                }
20873
20874                // Permission review applies only to apps not supporting the new permission model.
20875                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20876                    return false;
20877                }
20878
20879                // Legacy apps have the permission and get user consent on launch.
20880                PermissionsState permissionsState = packageSetting.getPermissionsState();
20881                return permissionsState.isPermissionReviewRequired(userId);
20882            }
20883        }
20884
20885        @Override
20886        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20887            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20888        }
20889
20890        @Override
20891        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20892                int userId) {
20893            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20894        }
20895
20896        @Override
20897        public void setDeviceAndProfileOwnerPackages(
20898                int deviceOwnerUserId, String deviceOwnerPackage,
20899                SparseArray<String> profileOwnerPackages) {
20900            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20901                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20902        }
20903
20904        @Override
20905        public boolean isPackageDataProtected(int userId, String packageName) {
20906            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20907        }
20908    }
20909
20910    @Override
20911    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20912        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20913        synchronized (mPackages) {
20914            final long identity = Binder.clearCallingIdentity();
20915            try {
20916                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20917                        packageNames, userId);
20918            } finally {
20919                Binder.restoreCallingIdentity(identity);
20920            }
20921        }
20922    }
20923
20924    private static void enforceSystemOrPhoneCaller(String tag) {
20925        int callingUid = Binder.getCallingUid();
20926        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20927            throw new SecurityException(
20928                    "Cannot call " + tag + " from UID " + callingUid);
20929        }
20930    }
20931
20932    boolean isHistoricalPackageUsageAvailable() {
20933        return mPackageUsage.isHistoricalPackageUsageAvailable();
20934    }
20935
20936    /**
20937     * Return a <b>copy</b> of the collection of packages known to the package manager.
20938     * @return A copy of the values of mPackages.
20939     */
20940    Collection<PackageParser.Package> getPackages() {
20941        synchronized (mPackages) {
20942            return new ArrayList<>(mPackages.values());
20943        }
20944    }
20945
20946    /**
20947     * Logs process start information (including base APK hash) to the security log.
20948     * @hide
20949     */
20950    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20951            String apkFile, int pid) {
20952        if (!SecurityLog.isLoggingEnabled()) {
20953            return;
20954        }
20955        Bundle data = new Bundle();
20956        data.putLong("startTimestamp", System.currentTimeMillis());
20957        data.putString("processName", processName);
20958        data.putInt("uid", uid);
20959        data.putString("seinfo", seinfo);
20960        data.putString("apkFile", apkFile);
20961        data.putInt("pid", pid);
20962        Message msg = mProcessLoggingHandler.obtainMessage(
20963                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20964        msg.setData(data);
20965        mProcessLoggingHandler.sendMessage(msg);
20966    }
20967}
20968