PackageManagerService.java revision a87770828637813dacd176ba3c8d3810f7ed6ab8
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.security.KeyStore;
200import android.security.SystemKeyStore;
201import android.system.ErrnoException;
202import android.system.Os;
203import android.text.TextUtils;
204import android.text.format.DateUtils;
205import android.util.ArrayMap;
206import android.util.ArraySet;
207import android.util.AtomicFile;
208import android.util.DisplayMetrics;
209import android.util.EventLog;
210import android.util.ExceptionUtils;
211import android.util.Log;
212import android.util.LogPrinter;
213import android.util.MathUtils;
214import android.util.PrintStreamPrinter;
215import android.util.Slog;
216import android.util.SparseArray;
217import android.util.SparseBooleanArray;
218import android.util.SparseIntArray;
219import android.util.Xml;
220import android.util.jar.StrictJarFile;
221import android.view.Display;
222
223import com.android.internal.R;
224import com.android.internal.annotations.GuardedBy;
225import com.android.internal.app.IMediaContainerService;
226import com.android.internal.app.ResolverActivity;
227import com.android.internal.content.NativeLibraryHelper;
228import com.android.internal.content.PackageHelper;
229import com.android.internal.logging.MetricsLogger;
230import com.android.internal.os.IParcelFileDescriptorFactory;
231import com.android.internal.os.InstallerConnection.InstallerException;
232import com.android.internal.os.SomeArgs;
233import com.android.internal.os.Zygote;
234import com.android.internal.telephony.CarrierAppUtils;
235import com.android.internal.util.ArrayUtils;
236import com.android.internal.util.FastPrintWriter;
237import com.android.internal.util.FastXmlSerializer;
238import com.android.internal.util.IndentingPrintWriter;
239import com.android.internal.util.Preconditions;
240import com.android.internal.util.XmlUtils;
241import com.android.server.EventLogTags;
242import com.android.server.FgThread;
243import com.android.server.IntentResolver;
244import com.android.server.LocalServices;
245import com.android.server.ServiceThread;
246import com.android.server.SystemConfig;
247import com.android.server.Watchdog;
248import com.android.server.net.NetworkPolicyManagerInternal;
249import com.android.server.pm.PermissionsState.PermissionState;
250import com.android.server.pm.Settings.DatabaseVersion;
251import com.android.server.pm.Settings.VersionInfo;
252import com.android.server.storage.DeviceStorageMonitorInternal;
253
254import dalvik.system.CloseGuard;
255import dalvik.system.DexFile;
256import dalvik.system.VMRuntime;
257
258import libcore.io.IoUtils;
259import libcore.util.EmptyArray;
260
261import org.xmlpull.v1.XmlPullParser;
262import org.xmlpull.v1.XmlPullParserException;
263import org.xmlpull.v1.XmlSerializer;
264
265import java.io.BufferedInputStream;
266import java.io.BufferedOutputStream;
267import java.io.BufferedReader;
268import java.io.ByteArrayInputStream;
269import java.io.ByteArrayOutputStream;
270import java.io.File;
271import java.io.FileDescriptor;
272import java.io.FileInputStream;
273import java.io.FileNotFoundException;
274import java.io.FileOutputStream;
275import java.io.FileReader;
276import java.io.FilenameFilter;
277import java.io.IOException;
278import java.io.InputStream;
279import java.io.PrintWriter;
280import java.nio.charset.StandardCharsets;
281import java.security.DigestInputStream;
282import java.security.MessageDigest;
283import java.security.NoSuchAlgorithmException;
284import java.security.PublicKey;
285import java.security.cert.Certificate;
286import java.security.cert.CertificateEncodingException;
287import java.security.cert.CertificateException;
288import java.text.SimpleDateFormat;
289import java.util.ArrayList;
290import java.util.Arrays;
291import java.util.Collection;
292import java.util.Collections;
293import java.util.Comparator;
294import java.util.Date;
295import java.util.HashSet;
296import java.util.Iterator;
297import java.util.List;
298import java.util.Map;
299import java.util.Objects;
300import java.util.Set;
301import java.util.concurrent.CountDownLatch;
302import java.util.concurrent.TimeUnit;
303import java.util.concurrent.atomic.AtomicBoolean;
304import java.util.concurrent.atomic.AtomicInteger;
305import java.util.concurrent.atomic.AtomicLong;
306
307/**
308 * Keep track of all those APKs everywhere.
309 * <p>
310 * Internally there are two important locks:
311 * <ul>
312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
313 * and other related state. It is a fine-grained lock that should only be held
314 * momentarily, as it's one of the most contended locks in the system.
315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
316 * operations typically involve heavy lifting of application data on disk. Since
317 * {@code installd} is single-threaded, and it's operations can often be slow,
318 * this lock should never be acquired while already holding {@link #mPackages}.
319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
320 * holding {@link #mInstallLock}.
321 * </ul>
322 * Many internal methods rely on the caller to hold the appropriate locks, and
323 * this contract is expressed through method name suffixes:
324 * <ul>
325 * <li>fooLI(): the caller must hold {@link #mInstallLock}
326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
327 * being modified must be frozen
328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
330 * </ul>
331 * <p>
332 * Because this class is very central to the platform's security; please run all
333 * CTS and unit tests whenever making modifications:
334 *
335 * <pre>
336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
338 * </pre>
339 */
340public class PackageManagerService extends IPackageManager.Stub {
341    static final String TAG = "PackageManager";
342    static final boolean DEBUG_SETTINGS = false;
343    static final boolean DEBUG_PREFERRED = false;
344    static final boolean DEBUG_UPGRADE = false;
345    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
346    private static final boolean DEBUG_BACKUP = false;
347    private static final boolean DEBUG_INSTALL = false;
348    private static final boolean DEBUG_REMOVE = false;
349    private static final boolean DEBUG_BROADCASTS = false;
350    private static final boolean DEBUG_SHOW_INFO = false;
351    private static final boolean DEBUG_PACKAGE_INFO = false;
352    private static final boolean DEBUG_INTENT_MATCHING = false;
353    private static final boolean DEBUG_PACKAGE_SCANNING = false;
354    private static final boolean DEBUG_VERIFY = false;
355    private static final boolean DEBUG_FILTERS = false;
356
357    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
358    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
359    // user, but by default initialize to this.
360    static final boolean DEBUG_DEXOPT = false;
361
362    private static final boolean DEBUG_ABI_SELECTION = false;
363    private static final boolean DEBUG_EPHEMERAL = false;
364    private static final boolean DEBUG_TRIAGED_MISSING = false;
365    private static final boolean DEBUG_APP_DATA = false;
366
367    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
368
369    private static final boolean DISABLE_EPHEMERAL_APPS = true;
370
371    private static final int RADIO_UID = Process.PHONE_UID;
372    private static final int LOG_UID = Process.LOG_UID;
373    private static final int NFC_UID = Process.NFC_UID;
374    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
375    private static final int SHELL_UID = Process.SHELL_UID;
376
377    // Cap the size of permission trees that 3rd party apps can define
378    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
379
380    // Suffix used during package installation when copying/moving
381    // package apks to install directory.
382    private static final String INSTALL_PACKAGE_SUFFIX = "-";
383
384    static final int SCAN_NO_DEX = 1<<1;
385    static final int SCAN_FORCE_DEX = 1<<2;
386    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
387    static final int SCAN_NEW_INSTALL = 1<<4;
388    static final int SCAN_NO_PATHS = 1<<5;
389    static final int SCAN_UPDATE_TIME = 1<<6;
390    static final int SCAN_DEFER_DEX = 1<<7;
391    static final int SCAN_BOOTING = 1<<8;
392    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
393    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
394    static final int SCAN_REPLACING = 1<<11;
395    static final int SCAN_REQUIRE_KNOWN = 1<<12;
396    static final int SCAN_MOVE = 1<<13;
397    static final int SCAN_INITIAL = 1<<14;
398    static final int SCAN_CHECK_ONLY = 1<<15;
399    static final int SCAN_DONT_KILL_APP = 1<<17;
400    static final int SCAN_IGNORE_FROZEN = 1<<18;
401
402    static final int REMOVE_CHATTY = 1<<16;
403
404    private static final int[] EMPTY_INT_ARRAY = new int[0];
405
406    /**
407     * Timeout (in milliseconds) after which the watchdog should declare that
408     * our handler thread is wedged.  The usual default for such things is one
409     * minute but we sometimes do very lengthy I/O operations on this thread,
410     * such as installing multi-gigabyte applications, so ours needs to be longer.
411     */
412    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
413
414    /**
415     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
416     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
417     * settings entry if available, otherwise we use the hardcoded default.  If it's been
418     * more than this long since the last fstrim, we force one during the boot sequence.
419     *
420     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
421     * one gets run at the next available charging+idle time.  This final mandatory
422     * no-fstrim check kicks in only of the other scheduling criteria is never met.
423     */
424    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
425
426    /**
427     * Whether verification is enabled by default.
428     */
429    private static final boolean DEFAULT_VERIFY_ENABLE = true;
430
431    /**
432     * The default maximum time to wait for the verification agent to return in
433     * milliseconds.
434     */
435    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
436
437    /**
438     * The default response for package verification timeout.
439     *
440     * This can be either PackageManager.VERIFICATION_ALLOW or
441     * PackageManager.VERIFICATION_REJECT.
442     */
443    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
444
445    static final String PLATFORM_PACKAGE_NAME = "android";
446
447    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
448
449    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
450            DEFAULT_CONTAINER_PACKAGE,
451            "com.android.defcontainer.DefaultContainerService");
452
453    private static final String KILL_APP_REASON_GIDS_CHANGED =
454            "permission grant or revoke changed gids";
455
456    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
457            "permissions revoked";
458
459    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
460
461    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
462
463    /** Permission grant: not grant the permission. */
464    private static final int GRANT_DENIED = 1;
465
466    /** Permission grant: grant the permission as an install permission. */
467    private static final int GRANT_INSTALL = 2;
468
469    /** Permission grant: grant the permission as a runtime one. */
470    private static final int GRANT_RUNTIME = 3;
471
472    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
473    private static final int GRANT_UPGRADE = 4;
474
475    /** Canonical intent used to identify what counts as a "web browser" app */
476    private static final Intent sBrowserIntent;
477    static {
478        sBrowserIntent = new Intent();
479        sBrowserIntent.setAction(Intent.ACTION_VIEW);
480        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
481        sBrowserIntent.setData(Uri.parse("http:"));
482    }
483
484    /**
485     * The set of all protected actions [i.e. those actions for which a high priority
486     * intent filter is disallowed].
487     */
488    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
489    static {
490        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
491        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
493        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
494    }
495
496    // Compilation reasons.
497    public static final int REASON_FIRST_BOOT = 0;
498    public static final int REASON_BOOT = 1;
499    public static final int REASON_INSTALL = 2;
500    public static final int REASON_BACKGROUND_DEXOPT = 3;
501    public static final int REASON_AB_OTA = 4;
502    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
503    public static final int REASON_SHARED_APK = 6;
504    public static final int REASON_FORCED_DEXOPT = 7;
505
506    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
507
508    /** Special library name that skips shared libraries check during compilation. */
509    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
510
511    final ServiceThread mHandlerThread;
512
513    final PackageHandler mHandler;
514
515    private final ProcessLoggingHandler mProcessLoggingHandler;
516
517    /**
518     * Messages for {@link #mHandler} that need to wait for system ready before
519     * being dispatched.
520     */
521    private ArrayList<Message> mPostSystemReadyMessages;
522
523    final int mSdkVersion = Build.VERSION.SDK_INT;
524
525    final Context mContext;
526    final boolean mFactoryTest;
527    final boolean mOnlyCore;
528    final DisplayMetrics mMetrics;
529    final int mDefParseFlags;
530    final String[] mSeparateProcesses;
531    final boolean mIsUpgrade;
532    final boolean mIsPreNUpgrade;
533
534    /** The location for ASEC container files on internal storage. */
535    final String mAsecInternalPath;
536
537    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
538    // LOCK HELD.  Can be called with mInstallLock held.
539    @GuardedBy("mInstallLock")
540    final Installer mInstaller;
541
542    /** Directory where installed third-party apps stored */
543    final File mAppInstallDir;
544    final File mEphemeralInstallDir;
545
546    /**
547     * Directory to which applications installed internally have their
548     * 32 bit native libraries copied.
549     */
550    private File mAppLib32InstallDir;
551
552    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
553    // apps.
554    final File mDrmAppPrivateInstallDir;
555
556    // ----------------------------------------------------------------
557
558    // Lock for state used when installing and doing other long running
559    // operations.  Methods that must be called with this lock held have
560    // the suffix "LI".
561    final Object mInstallLock = new Object();
562
563    // ----------------------------------------------------------------
564
565    // Keys are String (package name), values are Package.  This also serves
566    // as the lock for the global state.  Methods that must be called with
567    // this lock held have the prefix "LP".
568    @GuardedBy("mPackages")
569    final ArrayMap<String, PackageParser.Package> mPackages =
570            new ArrayMap<String, PackageParser.Package>();
571
572    final ArrayMap<String, Set<String>> mKnownCodebase =
573            new ArrayMap<String, Set<String>>();
574
575    // Tracks available target package names -> overlay package paths.
576    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
577        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
578
579    /**
580     * Tracks new system packages [received in an OTA] that we expect to
581     * find updated user-installed versions. Keys are package name, values
582     * are package location.
583     */
584    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
585    /**
586     * Tracks high priority intent filters for protected actions. During boot, certain
587     * filter actions are protected and should never be allowed to have a high priority
588     * intent filter for them. However, there is one, and only one exception -- the
589     * setup wizard. It must be able to define a high priority intent filter for these
590     * actions to ensure there are no escapes from the wizard. We need to delay processing
591     * of these during boot as we need to look at all of the system packages in order
592     * to know which component is the setup wizard.
593     */
594    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
595    /**
596     * Whether or not processing protected filters should be deferred.
597     */
598    private boolean mDeferProtectedFilters = true;
599
600    /**
601     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
602     */
603    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
604    /**
605     * Whether or not system app permissions should be promoted from install to runtime.
606     */
607    boolean mPromoteSystemApps;
608
609    @GuardedBy("mPackages")
610    final Settings mSettings;
611
612    /**
613     * Set of package names that are currently "frozen", which means active
614     * surgery is being done on the code/data for that package. The platform
615     * will refuse to launch frozen packages to avoid race conditions.
616     *
617     * @see PackageFreezer
618     */
619    @GuardedBy("mPackages")
620    final ArraySet<String> mFrozenPackages = new ArraySet<>();
621
622    boolean mRestoredSettings;
623
624    // System configuration read by SystemConfig.
625    final int[] mGlobalGids;
626    final SparseArray<ArraySet<String>> mSystemPermissions;
627    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
628
629    // If mac_permissions.xml was found for seinfo labeling.
630    boolean mFoundPolicyFile;
631
632    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
633
634    public static final class SharedLibraryEntry {
635        public final String path;
636        public final String apk;
637
638        SharedLibraryEntry(String _path, String _apk) {
639            path = _path;
640            apk = _apk;
641        }
642    }
643
644    // Currently known shared libraries.
645    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
646            new ArrayMap<String, SharedLibraryEntry>();
647
648    // All available activities, for your resolving pleasure.
649    final ActivityIntentResolver mActivities =
650            new ActivityIntentResolver();
651
652    // All available receivers, for your resolving pleasure.
653    final ActivityIntentResolver mReceivers =
654            new ActivityIntentResolver();
655
656    // All available services, for your resolving pleasure.
657    final ServiceIntentResolver mServices = new ServiceIntentResolver();
658
659    // All available providers, for your resolving pleasure.
660    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
661
662    // Mapping from provider base names (first directory in content URI codePath)
663    // to the provider information.
664    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
665            new ArrayMap<String, PackageParser.Provider>();
666
667    // Mapping from instrumentation class names to info about them.
668    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
669            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
670
671    // Mapping from permission names to info about them.
672    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
673            new ArrayMap<String, PackageParser.PermissionGroup>();
674
675    // Packages whose data we have transfered into another package, thus
676    // should no longer exist.
677    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
678
679    // Broadcast actions that are only available to the system.
680    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
681
682    /** List of packages waiting for verification. */
683    final SparseArray<PackageVerificationState> mPendingVerification
684            = new SparseArray<PackageVerificationState>();
685
686    /** Set of packages associated with each app op permission. */
687    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
688
689    final PackageInstallerService mInstallerService;
690
691    private final PackageDexOptimizer mPackageDexOptimizer;
692
693    private AtomicInteger mNextMoveId = new AtomicInteger();
694    private final MoveCallbacks mMoveCallbacks;
695
696    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
697
698    // Cache of users who need badging.
699    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
700
701    /** Token for keys in mPendingVerification. */
702    private int mPendingVerificationToken = 0;
703
704    volatile boolean mSystemReady;
705    volatile boolean mSafeMode;
706    volatile boolean mHasSystemUidErrors;
707
708    ApplicationInfo mAndroidApplication;
709    final ActivityInfo mResolveActivity = new ActivityInfo();
710    final ResolveInfo mResolveInfo = new ResolveInfo();
711    ComponentName mResolveComponentName;
712    PackageParser.Package mPlatformPackage;
713    ComponentName mCustomResolverComponentName;
714
715    boolean mResolverReplaced = false;
716
717    private final @Nullable ComponentName mIntentFilterVerifierComponent;
718    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
719
720    private int mIntentFilterVerificationToken = 0;
721
722    /** Component that knows whether or not an ephemeral application exists */
723    final ComponentName mEphemeralResolverComponent;
724    /** The service connection to the ephemeral resolver */
725    final EphemeralResolverConnection mEphemeralResolverConnection;
726
727    /** Component used to install ephemeral applications */
728    final ComponentName mEphemeralInstallerComponent;
729    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
730    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
731
732    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
733            = new SparseArray<IntentFilterVerificationState>();
734
735    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
736            new DefaultPermissionGrantPolicy(this);
737
738    // List of packages names to keep cached, even if they are uninstalled for all users
739    private List<String> mKeepUninstalledPackages;
740
741    private UserManagerInternal mUserManagerInternal;
742
743    private static class IFVerificationParams {
744        PackageParser.Package pkg;
745        boolean replacing;
746        int userId;
747        int verifierUid;
748
749        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
750                int _userId, int _verifierUid) {
751            pkg = _pkg;
752            replacing = _replacing;
753            userId = _userId;
754            replacing = _replacing;
755            verifierUid = _verifierUid;
756        }
757    }
758
759    private interface IntentFilterVerifier<T extends IntentFilter> {
760        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
761                                               T filter, String packageName);
762        void startVerifications(int userId);
763        void receiveVerificationResponse(int verificationId);
764    }
765
766    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
767        private Context mContext;
768        private ComponentName mIntentFilterVerifierComponent;
769        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
770
771        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
772            mContext = context;
773            mIntentFilterVerifierComponent = verifierComponent;
774        }
775
776        private String getDefaultScheme() {
777            return IntentFilter.SCHEME_HTTPS;
778        }
779
780        @Override
781        public void startVerifications(int userId) {
782            // Launch verifications requests
783            int count = mCurrentIntentFilterVerifications.size();
784            for (int n=0; n<count; n++) {
785                int verificationId = mCurrentIntentFilterVerifications.get(n);
786                final IntentFilterVerificationState ivs =
787                        mIntentFilterVerificationStates.get(verificationId);
788
789                String packageName = ivs.getPackageName();
790
791                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
792                final int filterCount = filters.size();
793                ArraySet<String> domainsSet = new ArraySet<>();
794                for (int m=0; m<filterCount; m++) {
795                    PackageParser.ActivityIntentInfo filter = filters.get(m);
796                    domainsSet.addAll(filter.getHostsList());
797                }
798                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
799                synchronized (mPackages) {
800                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
801                            packageName, domainsList) != null) {
802                        scheduleWriteSettingsLocked();
803                    }
804                }
805                sendVerificationRequest(userId, verificationId, ivs);
806            }
807            mCurrentIntentFilterVerifications.clear();
808        }
809
810        private void sendVerificationRequest(int userId, int verificationId,
811                IntentFilterVerificationState ivs) {
812
813            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
816                    verificationId);
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
819                    getDefaultScheme());
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
822                    ivs.getHostsString());
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
825                    ivs.getPackageName());
826            verificationIntent.setComponent(mIntentFilterVerifierComponent);
827            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
828
829            UserHandle user = new UserHandle(userId);
830            mContext.sendBroadcastAsUser(verificationIntent, user);
831            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
832                    "Sending IntentFilter verification broadcast");
833        }
834
835        public void receiveVerificationResponse(int verificationId) {
836            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
837
838            final boolean verified = ivs.isVerified();
839
840            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
841            final int count = filters.size();
842            if (DEBUG_DOMAIN_VERIFICATION) {
843                Slog.i(TAG, "Received verification response " + verificationId
844                        + " for " + count + " filters, verified=" + verified);
845            }
846            for (int n=0; n<count; n++) {
847                PackageParser.ActivityIntentInfo filter = filters.get(n);
848                filter.setVerified(verified);
849
850                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
851                        + " verified with result:" + verified + " and hosts:"
852                        + ivs.getHostsString());
853            }
854
855            mIntentFilterVerificationStates.remove(verificationId);
856
857            final String packageName = ivs.getPackageName();
858            IntentFilterVerificationInfo ivi = null;
859
860            synchronized (mPackages) {
861                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
862            }
863            if (ivi == null) {
864                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
865                        + verificationId + " packageName:" + packageName);
866                return;
867            }
868            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
869                    "Updating IntentFilterVerificationInfo for package " + packageName
870                            +" verificationId:" + verificationId);
871
872            synchronized (mPackages) {
873                if (verified) {
874                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
875                } else {
876                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
877                }
878                scheduleWriteSettingsLocked();
879
880                final int userId = ivs.getUserId();
881                if (userId != UserHandle.USER_ALL) {
882                    final int userStatus =
883                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
884
885                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
886                    boolean needUpdate = false;
887
888                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
889                    // already been set by the User thru the Disambiguation dialog
890                    switch (userStatus) {
891                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
892                            if (verified) {
893                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
894                            } else {
895                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
896                            }
897                            needUpdate = true;
898                            break;
899
900                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
901                            if (verified) {
902                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
903                                needUpdate = true;
904                            }
905                            break;
906
907                        default:
908                            // Nothing to do
909                    }
910
911                    if (needUpdate) {
912                        mSettings.updateIntentFilterVerificationStatusLPw(
913                                packageName, updatedStatus, userId);
914                        scheduleWritePackageRestrictionsLocked(userId);
915                    }
916                }
917            }
918        }
919
920        @Override
921        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
922                    ActivityIntentInfo filter, String packageName) {
923            if (!hasValidDomains(filter)) {
924                return false;
925            }
926            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
927            if (ivs == null) {
928                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
929                        packageName);
930            }
931            if (DEBUG_DOMAIN_VERIFICATION) {
932                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
933            }
934            ivs.addFilter(filter);
935            return true;
936        }
937
938        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
939                int userId, int verificationId, String packageName) {
940            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
941                    verifierUid, userId, packageName);
942            ivs.setPendingState();
943            synchronized (mPackages) {
944                mIntentFilterVerificationStates.append(verificationId, ivs);
945                mCurrentIntentFilterVerifications.add(verificationId);
946            }
947            return ivs;
948        }
949    }
950
951    private static boolean hasValidDomains(ActivityIntentInfo filter) {
952        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
953                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
954                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
955    }
956
957    // Set of pending broadcasts for aggregating enable/disable of components.
958    static class PendingPackageBroadcasts {
959        // for each user id, a map of <package name -> components within that package>
960        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
961
962        public PendingPackageBroadcasts() {
963            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
964        }
965
966        public ArrayList<String> get(int userId, String packageName) {
967            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
968            return packages.get(packageName);
969        }
970
971        public void put(int userId, String packageName, ArrayList<String> components) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            packages.put(packageName, components);
974        }
975
976        public void remove(int userId, String packageName) {
977            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
978            if (packages != null) {
979                packages.remove(packageName);
980            }
981        }
982
983        public void remove(int userId) {
984            mUidMap.remove(userId);
985        }
986
987        public int userIdCount() {
988            return mUidMap.size();
989        }
990
991        public int userIdAt(int n) {
992            return mUidMap.keyAt(n);
993        }
994
995        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
996            return mUidMap.get(userId);
997        }
998
999        public int size() {
1000            // total number of pending broadcast entries across all userIds
1001            int num = 0;
1002            for (int i = 0; i< mUidMap.size(); i++) {
1003                num += mUidMap.valueAt(i).size();
1004            }
1005            return num;
1006        }
1007
1008        public void clear() {
1009            mUidMap.clear();
1010        }
1011
1012        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1013            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1014            if (map == null) {
1015                map = new ArrayMap<String, ArrayList<String>>();
1016                mUidMap.put(userId, map);
1017            }
1018            return map;
1019        }
1020    }
1021    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1022
1023    // Service Connection to remote media container service to copy
1024    // package uri's from external media onto secure containers
1025    // or internal storage.
1026    private IMediaContainerService mContainerService = null;
1027
1028    static final int SEND_PENDING_BROADCAST = 1;
1029    static final int MCS_BOUND = 3;
1030    static final int END_COPY = 4;
1031    static final int INIT_COPY = 5;
1032    static final int MCS_UNBIND = 6;
1033    static final int START_CLEANING_PACKAGE = 7;
1034    static final int FIND_INSTALL_LOC = 8;
1035    static final int POST_INSTALL = 9;
1036    static final int MCS_RECONNECT = 10;
1037    static final int MCS_GIVE_UP = 11;
1038    static final int UPDATED_MEDIA_STATUS = 12;
1039    static final int WRITE_SETTINGS = 13;
1040    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1041    static final int PACKAGE_VERIFIED = 15;
1042    static final int CHECK_PENDING_VERIFICATION = 16;
1043    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1044    static final int INTENT_FILTER_VERIFIED = 18;
1045    static final int WRITE_PACKAGE_LIST = 19;
1046
1047    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1048
1049    // Delay time in millisecs
1050    static final int BROADCAST_DELAY = 10 * 1000;
1051
1052    static UserManagerService sUserManager;
1053
1054    // Stores a list of users whose package restrictions file needs to be updated
1055    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1056
1057    final private DefaultContainerConnection mDefContainerConn =
1058            new DefaultContainerConnection();
1059    class DefaultContainerConnection implements ServiceConnection {
1060        public void onServiceConnected(ComponentName name, IBinder service) {
1061            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1062            IMediaContainerService imcs =
1063                IMediaContainerService.Stub.asInterface(service);
1064            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1065        }
1066
1067        public void onServiceDisconnected(ComponentName name) {
1068            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1069        }
1070    }
1071
1072    // Recordkeeping of restore-after-install operations that are currently in flight
1073    // between the Package Manager and the Backup Manager
1074    static class PostInstallData {
1075        public InstallArgs args;
1076        public PackageInstalledInfo res;
1077
1078        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1079            args = _a;
1080            res = _r;
1081        }
1082    }
1083
1084    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1085    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1086
1087    // XML tags for backup/restore of various bits of state
1088    private static final String TAG_PREFERRED_BACKUP = "pa";
1089    private static final String TAG_DEFAULT_APPS = "da";
1090    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1091
1092    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1093    private static final String TAG_ALL_GRANTS = "rt-grants";
1094    private static final String TAG_GRANT = "grant";
1095    private static final String ATTR_PACKAGE_NAME = "pkg";
1096
1097    private static final String TAG_PERMISSION = "perm";
1098    private static final String ATTR_PERMISSION_NAME = "name";
1099    private static final String ATTR_IS_GRANTED = "g";
1100    private static final String ATTR_USER_SET = "set";
1101    private static final String ATTR_USER_FIXED = "fixed";
1102    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1103
1104    // System/policy permission grants are not backed up
1105    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1106            FLAG_PERMISSION_POLICY_FIXED
1107            | FLAG_PERMISSION_SYSTEM_FIXED
1108            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1109
1110    // And we back up these user-adjusted states
1111    private static final int USER_RUNTIME_GRANT_MASK =
1112            FLAG_PERMISSION_USER_SET
1113            | FLAG_PERMISSION_USER_FIXED
1114            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1115
1116    final @Nullable String mRequiredVerifierPackage;
1117    final @NonNull String mRequiredInstallerPackage;
1118    final @Nullable String mSetupWizardPackage;
1119    final @NonNull String mServicesSystemSharedLibraryPackageName;
1120    final @NonNull String mSharedSystemSharedLibraryPackageName;
1121
1122    private final PackageUsage mPackageUsage = new PackageUsage();
1123
1124    private class PackageUsage {
1125        private static final int WRITE_INTERVAL
1126            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1127
1128        private final Object mFileLock = new Object();
1129        private final AtomicLong mLastWritten = new AtomicLong(0);
1130        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1131
1132        private boolean mIsHistoricalPackageUsageAvailable = true;
1133
1134        boolean isHistoricalPackageUsageAvailable() {
1135            return mIsHistoricalPackageUsageAvailable;
1136        }
1137
1138        void write(boolean force) {
1139            if (force) {
1140                writeInternal();
1141                return;
1142            }
1143            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1144                && !DEBUG_DEXOPT) {
1145                return;
1146            }
1147            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1148                new Thread("PackageUsage_DiskWriter") {
1149                    @Override
1150                    public void run() {
1151                        try {
1152                            writeInternal();
1153                        } finally {
1154                            mBackgroundWriteRunning.set(false);
1155                        }
1156                    }
1157                }.start();
1158            }
1159        }
1160
1161        private void writeInternal() {
1162            synchronized (mPackages) {
1163                synchronized (mFileLock) {
1164                    AtomicFile file = getFile();
1165                    FileOutputStream f = null;
1166                    try {
1167                        f = file.startWrite();
1168                        BufferedOutputStream out = new BufferedOutputStream(f);
1169                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1170                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1171                        StringBuilder sb = new StringBuilder();
1172
1173                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1174                        sb.append('\n');
1175                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1176
1177                        for (PackageParser.Package pkg : mPackages.values()) {
1178                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1179                                continue;
1180                            }
1181                            sb.setLength(0);
1182                            sb.append(pkg.packageName);
1183                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1184                                sb.append(' ');
1185                                sb.append(usageTimeInMillis);
1186                            }
1187                            sb.append('\n');
1188                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1189                        }
1190                        out.flush();
1191                        file.finishWrite(f);
1192                    } catch (IOException e) {
1193                        if (f != null) {
1194                            file.failWrite(f);
1195                        }
1196                        Log.e(TAG, "Failed to write package usage times", e);
1197                    }
1198                }
1199            }
1200            mLastWritten.set(SystemClock.elapsedRealtime());
1201        }
1202
1203        void readLP() {
1204            synchronized (mFileLock) {
1205                AtomicFile file = getFile();
1206                BufferedInputStream in = null;
1207                try {
1208                    in = new BufferedInputStream(file.openRead());
1209                    StringBuffer sb = new StringBuffer();
1210
1211                    String firstLine = readLine(in, sb);
1212                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1213                        readVersion1LP(in, sb);
1214                    } else {
1215                        readVersion0LP(in, sb, firstLine);
1216                    }
1217                } catch (FileNotFoundException expected) {
1218                    mIsHistoricalPackageUsageAvailable = false;
1219                } catch (IOException e) {
1220                    Log.w(TAG, "Failed to read package usage times", e);
1221                } finally {
1222                    IoUtils.closeQuietly(in);
1223                }
1224            }
1225            mLastWritten.set(SystemClock.elapsedRealtime());
1226        }
1227
1228        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1229                throws IOException {
1230            // Initial version of the file had no version number and stored one
1231            // package-timestamp pair per line.
1232            // Note that the first line has already been read from the InputStream.
1233            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1234                String[] tokens = line.split(" ");
1235                if (tokens.length != 2) {
1236                    throw new IOException("Failed to parse " + line +
1237                            " as package-timestamp pair.");
1238                }
1239
1240                String packageName = tokens[0];
1241                PackageParser.Package pkg = mPackages.get(packageName);
1242                if (pkg == null) {
1243                    continue;
1244                }
1245
1246                long timestamp = parseAsLong(tokens[1]);
1247                for (int reason = 0;
1248                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1249                        reason++) {
1250                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1251                }
1252            }
1253        }
1254
1255        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1256            // Version 1 of the file started with the corresponding version
1257            // number and then stored a package name and eight timestamps per line.
1258            String line;
1259            while ((line = readLine(in, sb)) != null) {
1260                String[] tokens = line.split(" ");
1261                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1262                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1263                }
1264
1265                String packageName = tokens[0];
1266                PackageParser.Package pkg = mPackages.get(packageName);
1267                if (pkg == null) {
1268                    continue;
1269                }
1270
1271                for (int reason = 0;
1272                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1273                        reason++) {
1274                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1275                }
1276            }
1277        }
1278
1279        private long parseAsLong(String token) throws IOException {
1280            try {
1281                return Long.parseLong(token);
1282            } catch (NumberFormatException e) {
1283                throw new IOException("Failed to parse " + token + " as a long.", e);
1284            }
1285        }
1286
1287        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1288            return readToken(in, sb, '\n');
1289        }
1290
1291        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1292                throws IOException {
1293            sb.setLength(0);
1294            while (true) {
1295                int ch = in.read();
1296                if (ch == -1) {
1297                    if (sb.length() == 0) {
1298                        return null;
1299                    }
1300                    throw new IOException("Unexpected EOF");
1301                }
1302                if (ch == endOfToken) {
1303                    return sb.toString();
1304                }
1305                sb.append((char)ch);
1306            }
1307        }
1308
1309        private AtomicFile getFile() {
1310            File dataDir = Environment.getDataDirectory();
1311            File systemDir = new File(dataDir, "system");
1312            File fname = new File(systemDir, "package-usage.list");
1313            return new AtomicFile(fname);
1314        }
1315
1316        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1317        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1318    }
1319
1320    class PackageHandler extends Handler {
1321        private boolean mBound = false;
1322        final ArrayList<HandlerParams> mPendingInstalls =
1323            new ArrayList<HandlerParams>();
1324
1325        private boolean connectToService() {
1326            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1327                    " DefaultContainerService");
1328            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1329            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1330            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1331                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1332                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1333                mBound = true;
1334                return true;
1335            }
1336            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1337            return false;
1338        }
1339
1340        private void disconnectService() {
1341            mContainerService = null;
1342            mBound = false;
1343            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1344            mContext.unbindService(mDefContainerConn);
1345            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1346        }
1347
1348        PackageHandler(Looper looper) {
1349            super(looper);
1350        }
1351
1352        public void handleMessage(Message msg) {
1353            try {
1354                doHandleMessage(msg);
1355            } finally {
1356                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1357            }
1358        }
1359
1360        void doHandleMessage(Message msg) {
1361            switch (msg.what) {
1362                case INIT_COPY: {
1363                    HandlerParams params = (HandlerParams) msg.obj;
1364                    int idx = mPendingInstalls.size();
1365                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1366                    // If a bind was already initiated we dont really
1367                    // need to do anything. The pending install
1368                    // will be processed later on.
1369                    if (!mBound) {
1370                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1371                                System.identityHashCode(mHandler));
1372                        // If this is the only one pending we might
1373                        // have to bind to the service again.
1374                        if (!connectToService()) {
1375                            Slog.e(TAG, "Failed to bind to media container service");
1376                            params.serviceError();
1377                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1378                                    System.identityHashCode(mHandler));
1379                            if (params.traceMethod != null) {
1380                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1381                                        params.traceCookie);
1382                            }
1383                            return;
1384                        } else {
1385                            // Once we bind to the service, the first
1386                            // pending request will be processed.
1387                            mPendingInstalls.add(idx, params);
1388                        }
1389                    } else {
1390                        mPendingInstalls.add(idx, params);
1391                        // Already bound to the service. Just make
1392                        // sure we trigger off processing the first request.
1393                        if (idx == 0) {
1394                            mHandler.sendEmptyMessage(MCS_BOUND);
1395                        }
1396                    }
1397                    break;
1398                }
1399                case MCS_BOUND: {
1400                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1401                    if (msg.obj != null) {
1402                        mContainerService = (IMediaContainerService) msg.obj;
1403                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1404                                System.identityHashCode(mHandler));
1405                    }
1406                    if (mContainerService == null) {
1407                        if (!mBound) {
1408                            // Something seriously wrong since we are not bound and we are not
1409                            // waiting for connection. Bail out.
1410                            Slog.e(TAG, "Cannot bind to media container service");
1411                            for (HandlerParams params : mPendingInstalls) {
1412                                // Indicate service bind error
1413                                params.serviceError();
1414                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1415                                        System.identityHashCode(params));
1416                                if (params.traceMethod != null) {
1417                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1418                                            params.traceMethod, params.traceCookie);
1419                                }
1420                                return;
1421                            }
1422                            mPendingInstalls.clear();
1423                        } else {
1424                            Slog.w(TAG, "Waiting to connect to media container service");
1425                        }
1426                    } else if (mPendingInstalls.size() > 0) {
1427                        HandlerParams params = mPendingInstalls.get(0);
1428                        if (params != null) {
1429                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1430                                    System.identityHashCode(params));
1431                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1432                            if (params.startCopy()) {
1433                                // We are done...  look for more work or to
1434                                // go idle.
1435                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1436                                        "Checking for more work or unbind...");
1437                                // Delete pending install
1438                                if (mPendingInstalls.size() > 0) {
1439                                    mPendingInstalls.remove(0);
1440                                }
1441                                if (mPendingInstalls.size() == 0) {
1442                                    if (mBound) {
1443                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1444                                                "Posting delayed MCS_UNBIND");
1445                                        removeMessages(MCS_UNBIND);
1446                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1447                                        // Unbind after a little delay, to avoid
1448                                        // continual thrashing.
1449                                        sendMessageDelayed(ubmsg, 10000);
1450                                    }
1451                                } else {
1452                                    // There are more pending requests in queue.
1453                                    // Just post MCS_BOUND message to trigger processing
1454                                    // of next pending install.
1455                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1456                                            "Posting MCS_BOUND for next work");
1457                                    mHandler.sendEmptyMessage(MCS_BOUND);
1458                                }
1459                            }
1460                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1461                        }
1462                    } else {
1463                        // Should never happen ideally.
1464                        Slog.w(TAG, "Empty queue");
1465                    }
1466                    break;
1467                }
1468                case MCS_RECONNECT: {
1469                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1470                    if (mPendingInstalls.size() > 0) {
1471                        if (mBound) {
1472                            disconnectService();
1473                        }
1474                        if (!connectToService()) {
1475                            Slog.e(TAG, "Failed to bind to media container service");
1476                            for (HandlerParams params : mPendingInstalls) {
1477                                // Indicate service bind error
1478                                params.serviceError();
1479                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1480                                        System.identityHashCode(params));
1481                            }
1482                            mPendingInstalls.clear();
1483                        }
1484                    }
1485                    break;
1486                }
1487                case MCS_UNBIND: {
1488                    // If there is no actual work left, then time to unbind.
1489                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1490
1491                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1492                        if (mBound) {
1493                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1494
1495                            disconnectService();
1496                        }
1497                    } else if (mPendingInstalls.size() > 0) {
1498                        // There are more pending requests in queue.
1499                        // Just post MCS_BOUND message to trigger processing
1500                        // of next pending install.
1501                        mHandler.sendEmptyMessage(MCS_BOUND);
1502                    }
1503
1504                    break;
1505                }
1506                case MCS_GIVE_UP: {
1507                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1508                    HandlerParams params = mPendingInstalls.remove(0);
1509                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                            System.identityHashCode(params));
1511                    break;
1512                }
1513                case SEND_PENDING_BROADCAST: {
1514                    String packages[];
1515                    ArrayList<String> components[];
1516                    int size = 0;
1517                    int uids[];
1518                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1519                    synchronized (mPackages) {
1520                        if (mPendingBroadcasts == null) {
1521                            return;
1522                        }
1523                        size = mPendingBroadcasts.size();
1524                        if (size <= 0) {
1525                            // Nothing to be done. Just return
1526                            return;
1527                        }
1528                        packages = new String[size];
1529                        components = new ArrayList[size];
1530                        uids = new int[size];
1531                        int i = 0;  // filling out the above arrays
1532
1533                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1534                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1535                            Iterator<Map.Entry<String, ArrayList<String>>> it
1536                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1537                                            .entrySet().iterator();
1538                            while (it.hasNext() && i < size) {
1539                                Map.Entry<String, ArrayList<String>> ent = it.next();
1540                                packages[i] = ent.getKey();
1541                                components[i] = ent.getValue();
1542                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1543                                uids[i] = (ps != null)
1544                                        ? UserHandle.getUid(packageUserId, ps.appId)
1545                                        : -1;
1546                                i++;
1547                            }
1548                        }
1549                        size = i;
1550                        mPendingBroadcasts.clear();
1551                    }
1552                    // Send broadcasts
1553                    for (int i = 0; i < size; i++) {
1554                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1555                    }
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1557                    break;
1558                }
1559                case START_CLEANING_PACKAGE: {
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1561                    final String packageName = (String)msg.obj;
1562                    final int userId = msg.arg1;
1563                    final boolean andCode = msg.arg2 != 0;
1564                    synchronized (mPackages) {
1565                        if (userId == UserHandle.USER_ALL) {
1566                            int[] users = sUserManager.getUserIds();
1567                            for (int user : users) {
1568                                mSettings.addPackageToCleanLPw(
1569                                        new PackageCleanItem(user, packageName, andCode));
1570                            }
1571                        } else {
1572                            mSettings.addPackageToCleanLPw(
1573                                    new PackageCleanItem(userId, packageName, andCode));
1574                        }
1575                    }
1576                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1577                    startCleaningPackages();
1578                } break;
1579                case POST_INSTALL: {
1580                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1581
1582                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1583                    final boolean didRestore = (msg.arg2 != 0);
1584                    mRunningInstalls.delete(msg.arg1);
1585
1586                    if (data != null) {
1587                        InstallArgs args = data.args;
1588                        PackageInstalledInfo parentRes = data.res;
1589
1590                        final boolean grantPermissions = (args.installFlags
1591                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1592                        final boolean killApp = (args.installFlags
1593                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1594                        final String[] grantedPermissions = args.installGrantPermissions;
1595
1596                        // Handle the parent package
1597                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1598                                grantedPermissions, didRestore, args.installerPackageName,
1599                                args.observer);
1600
1601                        // Handle the child packages
1602                        final int childCount = (parentRes.addedChildPackages != null)
1603                                ? parentRes.addedChildPackages.size() : 0;
1604                        for (int i = 0; i < childCount; i++) {
1605                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1606                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1607                                    grantedPermissions, false, args.installerPackageName,
1608                                    args.observer);
1609                        }
1610
1611                        // Log tracing if needed
1612                        if (args.traceMethod != null) {
1613                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1614                                    args.traceCookie);
1615                        }
1616                    } else {
1617                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1618                    }
1619
1620                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1621                } break;
1622                case UPDATED_MEDIA_STATUS: {
1623                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1624                    boolean reportStatus = msg.arg1 == 1;
1625                    boolean doGc = msg.arg2 == 1;
1626                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1627                    if (doGc) {
1628                        // Force a gc to clear up stale containers.
1629                        Runtime.getRuntime().gc();
1630                    }
1631                    if (msg.obj != null) {
1632                        @SuppressWarnings("unchecked")
1633                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1634                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1635                        // Unload containers
1636                        unloadAllContainers(args);
1637                    }
1638                    if (reportStatus) {
1639                        try {
1640                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1641                            PackageHelper.getMountService().finishMediaUpdate();
1642                        } catch (RemoteException e) {
1643                            Log.e(TAG, "MountService not running?");
1644                        }
1645                    }
1646                } break;
1647                case WRITE_SETTINGS: {
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1649                    synchronized (mPackages) {
1650                        removeMessages(WRITE_SETTINGS);
1651                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1652                        mSettings.writeLPr();
1653                        mDirtyUsers.clear();
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                } break;
1657                case WRITE_PACKAGE_RESTRICTIONS: {
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1659                    synchronized (mPackages) {
1660                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1661                        for (int userId : mDirtyUsers) {
1662                            mSettings.writePackageRestrictionsLPr(userId);
1663                        }
1664                        mDirtyUsers.clear();
1665                    }
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1667                } break;
1668                case WRITE_PACKAGE_LIST: {
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1670                    synchronized (mPackages) {
1671                        removeMessages(WRITE_PACKAGE_LIST);
1672                        mSettings.writePackageListLPr(msg.arg1);
1673                    }
1674                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1675                } break;
1676                case CHECK_PENDING_VERIFICATION: {
1677                    final int verificationId = msg.arg1;
1678                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1679
1680                    if ((state != null) && !state.timeoutExtended()) {
1681                        final InstallArgs args = state.getInstallArgs();
1682                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1683
1684                        Slog.i(TAG, "Verification timed out for " + originUri);
1685                        mPendingVerification.remove(verificationId);
1686
1687                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1688
1689                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1690                            Slog.i(TAG, "Continuing with installation of " + originUri);
1691                            state.setVerifierResponse(Binder.getCallingUid(),
1692                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1693                            broadcastPackageVerified(verificationId, originUri,
1694                                    PackageManager.VERIFICATION_ALLOW,
1695                                    state.getInstallArgs().getUser());
1696                            try {
1697                                ret = args.copyApk(mContainerService, true);
1698                            } catch (RemoteException e) {
1699                                Slog.e(TAG, "Could not contact the ContainerService");
1700                            }
1701                        } else {
1702                            broadcastPackageVerified(verificationId, originUri,
1703                                    PackageManager.VERIFICATION_REJECT,
1704                                    state.getInstallArgs().getUser());
1705                        }
1706
1707                        Trace.asyncTraceEnd(
1708                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1709
1710                        processPendingInstall(args, ret);
1711                        mHandler.sendEmptyMessage(MCS_UNBIND);
1712                    }
1713                    break;
1714                }
1715                case PACKAGE_VERIFIED: {
1716                    final int verificationId = msg.arg1;
1717
1718                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1719                    if (state == null) {
1720                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1721                        break;
1722                    }
1723
1724                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1725
1726                    state.setVerifierResponse(response.callerUid, response.code);
1727
1728                    if (state.isVerificationComplete()) {
1729                        mPendingVerification.remove(verificationId);
1730
1731                        final InstallArgs args = state.getInstallArgs();
1732                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1733
1734                        int ret;
1735                        if (state.isInstallAllowed()) {
1736                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1737                            broadcastPackageVerified(verificationId, originUri,
1738                                    response.code, state.getInstallArgs().getUser());
1739                            try {
1740                                ret = args.copyApk(mContainerService, true);
1741                            } catch (RemoteException e) {
1742                                Slog.e(TAG, "Could not contact the ContainerService");
1743                            }
1744                        } else {
1745                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1746                        }
1747
1748                        Trace.asyncTraceEnd(
1749                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1750
1751                        processPendingInstall(args, ret);
1752                        mHandler.sendEmptyMessage(MCS_UNBIND);
1753                    }
1754
1755                    break;
1756                }
1757                case START_INTENT_FILTER_VERIFICATIONS: {
1758                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1759                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1760                            params.replacing, params.pkg);
1761                    break;
1762                }
1763                case INTENT_FILTER_VERIFIED: {
1764                    final int verificationId = msg.arg1;
1765
1766                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1767                            verificationId);
1768                    if (state == null) {
1769                        Slog.w(TAG, "Invalid IntentFilter verification token "
1770                                + verificationId + " received");
1771                        break;
1772                    }
1773
1774                    final int userId = state.getUserId();
1775
1776                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1777                            "Processing IntentFilter verification with token:"
1778                            + verificationId + " and userId:" + userId);
1779
1780                    final IntentFilterVerificationResponse response =
1781                            (IntentFilterVerificationResponse) msg.obj;
1782
1783                    state.setVerifierResponse(response.callerUid, response.code);
1784
1785                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1786                            "IntentFilter verification with token:" + verificationId
1787                            + " and userId:" + userId
1788                            + " is settings verifier response with response code:"
1789                            + response.code);
1790
1791                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1792                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1793                                + response.getFailedDomainsString());
1794                    }
1795
1796                    if (state.isVerificationComplete()) {
1797                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1798                    } else {
1799                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1800                                "IntentFilter verification with token:" + verificationId
1801                                + " was not said to be complete");
1802                    }
1803
1804                    break;
1805                }
1806            }
1807        }
1808    }
1809
1810    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1811            boolean killApp, String[] grantedPermissions,
1812            boolean launchedForRestore, String installerPackage,
1813            IPackageInstallObserver2 installObserver) {
1814        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1815            // Send the removed broadcasts
1816            if (res.removedInfo != null) {
1817                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1818            }
1819
1820            // Now that we successfully installed the package, grant runtime
1821            // permissions if requested before broadcasting the install.
1822            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1823                    >= Build.VERSION_CODES.M) {
1824                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1825            }
1826
1827            final boolean update = res.removedInfo != null
1828                    && res.removedInfo.removedPackage != null;
1829
1830            // If this is the first time we have child packages for a disabled privileged
1831            // app that had no children, we grant requested runtime permissions to the new
1832            // children if the parent on the system image had them already granted.
1833            if (res.pkg.parentPackage != null) {
1834                synchronized (mPackages) {
1835                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1836                }
1837            }
1838
1839            synchronized (mPackages) {
1840                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1841            }
1842
1843            final String packageName = res.pkg.applicationInfo.packageName;
1844            Bundle extras = new Bundle(1);
1845            extras.putInt(Intent.EXTRA_UID, res.uid);
1846
1847            // Determine the set of users who are adding this package for
1848            // the first time vs. those who are seeing an update.
1849            int[] firstUsers = EMPTY_INT_ARRAY;
1850            int[] updateUsers = EMPTY_INT_ARRAY;
1851            if (res.origUsers == null || res.origUsers.length == 0) {
1852                firstUsers = res.newUsers;
1853            } else {
1854                for (int newUser : res.newUsers) {
1855                    boolean isNew = true;
1856                    for (int origUser : res.origUsers) {
1857                        if (origUser == newUser) {
1858                            isNew = false;
1859                            break;
1860                        }
1861                    }
1862                    if (isNew) {
1863                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1864                    } else {
1865                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1866                    }
1867                }
1868            }
1869
1870            // Send installed broadcasts if the install/update is not ephemeral
1871            if (!isEphemeral(res.pkg)) {
1872                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1873
1874                // Send added for users that see the package for the first time
1875                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1876                        extras, 0 /*flags*/, null /*targetPackage*/,
1877                        null /*finishedReceiver*/, firstUsers);
1878
1879                // Send added for users that don't see the package for the first time
1880                if (update) {
1881                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1882                }
1883                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1884                        extras, 0 /*flags*/, null /*targetPackage*/,
1885                        null /*finishedReceiver*/, updateUsers);
1886
1887                // Send replaced for users that don't see the package for the first time
1888                if (update) {
1889                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1890                            packageName, extras, 0 /*flags*/,
1891                            null /*targetPackage*/, null /*finishedReceiver*/,
1892                            updateUsers);
1893                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1894                            null /*package*/, null /*extras*/, 0 /*flags*/,
1895                            packageName /*targetPackage*/,
1896                            null /*finishedReceiver*/, updateUsers);
1897                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1898                    // First-install and we did a restore, so we're responsible for the
1899                    // first-launch broadcast.
1900                    if (DEBUG_BACKUP) {
1901                        Slog.i(TAG, "Post-restore of " + packageName
1902                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1903                    }
1904                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1905                }
1906
1907                // Send broadcast package appeared if forward locked/external for all users
1908                // treat asec-hosted packages like removable media on upgrade
1909                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1910                    if (DEBUG_INSTALL) {
1911                        Slog.i(TAG, "upgrading pkg " + res.pkg
1912                                + " is ASEC-hosted -> AVAILABLE");
1913                    }
1914                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1915                    ArrayList<String> pkgList = new ArrayList<>(1);
1916                    pkgList.add(packageName);
1917                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1918                }
1919            }
1920
1921            // Work that needs to happen on first install within each user
1922            if (firstUsers != null && firstUsers.length > 0) {
1923                synchronized (mPackages) {
1924                    for (int userId : firstUsers) {
1925                        // If this app is a browser and it's newly-installed for some
1926                        // users, clear any default-browser state in those users. The
1927                        // app's nature doesn't depend on the user, so we can just check
1928                        // its browser nature in any user and generalize.
1929                        if (packageIsBrowser(packageName, userId)) {
1930                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1931                        }
1932
1933                        // We may also need to apply pending (restored) runtime
1934                        // permission grants within these users.
1935                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1936                    }
1937                }
1938            }
1939
1940            // Log current value of "unknown sources" setting
1941            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1942                    getUnknownSourcesSettings());
1943
1944            // Force a gc to clear up things
1945            Runtime.getRuntime().gc();
1946
1947            // Remove the replaced package's older resources safely now
1948            // We delete after a gc for applications  on sdcard.
1949            if (res.removedInfo != null && res.removedInfo.args != null) {
1950                synchronized (mInstallLock) {
1951                    res.removedInfo.args.doPostDeleteLI(true);
1952                }
1953            }
1954        }
1955
1956        // If someone is watching installs - notify them
1957        if (installObserver != null) {
1958            try {
1959                Bundle extras = extrasForInstallResult(res);
1960                installObserver.onPackageInstalled(res.name, res.returnCode,
1961                        res.returnMsg, extras);
1962            } catch (RemoteException e) {
1963                Slog.i(TAG, "Observer no longer exists.");
1964            }
1965        }
1966    }
1967
1968    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1969            PackageParser.Package pkg) {
1970        if (pkg.parentPackage == null) {
1971            return;
1972        }
1973        if (pkg.requestedPermissions == null) {
1974            return;
1975        }
1976        final PackageSetting disabledSysParentPs = mSettings
1977                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1978        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1979                || !disabledSysParentPs.isPrivileged()
1980                || (disabledSysParentPs.childPackageNames != null
1981                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1982            return;
1983        }
1984        final int[] allUserIds = sUserManager.getUserIds();
1985        final int permCount = pkg.requestedPermissions.size();
1986        for (int i = 0; i < permCount; i++) {
1987            String permission = pkg.requestedPermissions.get(i);
1988            BasePermission bp = mSettings.mPermissions.get(permission);
1989            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1990                continue;
1991            }
1992            for (int userId : allUserIds) {
1993                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1994                        permission, userId)) {
1995                    grantRuntimePermission(pkg.packageName, permission, userId);
1996                }
1997            }
1998        }
1999    }
2000
2001    private StorageEventListener mStorageListener = new StorageEventListener() {
2002        @Override
2003        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2004            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2005                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2006                    final String volumeUuid = vol.getFsUuid();
2007
2008                    // Clean up any users or apps that were removed or recreated
2009                    // while this volume was missing
2010                    reconcileUsers(volumeUuid);
2011                    reconcileApps(volumeUuid);
2012
2013                    // Clean up any install sessions that expired or were
2014                    // cancelled while this volume was missing
2015                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2016
2017                    loadPrivatePackages(vol);
2018
2019                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2020                    unloadPrivatePackages(vol);
2021                }
2022            }
2023
2024            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2025                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2026                    updateExternalMediaStatus(true, false);
2027                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2028                    updateExternalMediaStatus(false, false);
2029                }
2030            }
2031        }
2032
2033        @Override
2034        public void onVolumeForgotten(String fsUuid) {
2035            if (TextUtils.isEmpty(fsUuid)) {
2036                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2037                return;
2038            }
2039
2040            // Remove any apps installed on the forgotten volume
2041            synchronized (mPackages) {
2042                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2043                for (PackageSetting ps : packages) {
2044                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2045                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2046                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2047                }
2048
2049                mSettings.onVolumeForgotten(fsUuid);
2050                mSettings.writeLPr();
2051            }
2052        }
2053    };
2054
2055    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2056            String[] grantedPermissions) {
2057        for (int userId : userIds) {
2058            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2059        }
2060
2061        // We could have touched GID membership, so flush out packages.list
2062        synchronized (mPackages) {
2063            mSettings.writePackageListLPr();
2064        }
2065    }
2066
2067    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2068            String[] grantedPermissions) {
2069        SettingBase sb = (SettingBase) pkg.mExtras;
2070        if (sb == null) {
2071            return;
2072        }
2073
2074        PermissionsState permissionsState = sb.getPermissionsState();
2075
2076        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2077                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2078
2079        for (String permission : pkg.requestedPermissions) {
2080            final BasePermission bp;
2081            synchronized (mPackages) {
2082                bp = mSettings.mPermissions.get(permission);
2083            }
2084            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2085                    && (grantedPermissions == null
2086                           || ArrayUtils.contains(grantedPermissions, permission))) {
2087                final int flags = permissionsState.getPermissionFlags(permission, userId);
2088                // Installer cannot change immutable permissions.
2089                if ((flags & immutableFlags) == 0) {
2090                    grantRuntimePermission(pkg.packageName, permission, userId);
2091                }
2092            }
2093        }
2094    }
2095
2096    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2097        Bundle extras = null;
2098        switch (res.returnCode) {
2099            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2100                extras = new Bundle();
2101                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2102                        res.origPermission);
2103                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2104                        res.origPackage);
2105                break;
2106            }
2107            case PackageManager.INSTALL_SUCCEEDED: {
2108                extras = new Bundle();
2109                extras.putBoolean(Intent.EXTRA_REPLACING,
2110                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2111                break;
2112            }
2113        }
2114        return extras;
2115    }
2116
2117    void scheduleWriteSettingsLocked() {
2118        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2119            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2120        }
2121    }
2122
2123    void scheduleWritePackageListLocked(int userId) {
2124        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2125            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2126            msg.arg1 = userId;
2127            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2128        }
2129    }
2130
2131    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2132        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2133        scheduleWritePackageRestrictionsLocked(userId);
2134    }
2135
2136    void scheduleWritePackageRestrictionsLocked(int userId) {
2137        final int[] userIds = (userId == UserHandle.USER_ALL)
2138                ? sUserManager.getUserIds() : new int[]{userId};
2139        for (int nextUserId : userIds) {
2140            if (!sUserManager.exists(nextUserId)) return;
2141            mDirtyUsers.add(nextUserId);
2142            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2143                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2144            }
2145        }
2146    }
2147
2148    public static PackageManagerService main(Context context, Installer installer,
2149            boolean factoryTest, boolean onlyCore) {
2150        // Self-check for initial settings.
2151        PackageManagerServiceCompilerMapping.checkProperties();
2152
2153        PackageManagerService m = new PackageManagerService(context, installer,
2154                factoryTest, onlyCore);
2155        m.enableSystemUserPackages();
2156        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2157        // disabled after already being started.
2158        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2159                UserHandle.USER_SYSTEM);
2160        ServiceManager.addService("package", m);
2161        return m;
2162    }
2163
2164    private void enableSystemUserPackages() {
2165        if (!UserManager.isSplitSystemUser()) {
2166            return;
2167        }
2168        // For system user, enable apps based on the following conditions:
2169        // - app is whitelisted or belong to one of these groups:
2170        //   -- system app which has no launcher icons
2171        //   -- system app which has INTERACT_ACROSS_USERS permission
2172        //   -- system IME app
2173        // - app is not in the blacklist
2174        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2175        Set<String> enableApps = new ArraySet<>();
2176        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2177                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2178                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2179        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2180        enableApps.addAll(wlApps);
2181        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2182                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2183        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2184        enableApps.removeAll(blApps);
2185        Log.i(TAG, "Applications installed for system user: " + enableApps);
2186        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2187                UserHandle.SYSTEM);
2188        final int allAppsSize = allAps.size();
2189        synchronized (mPackages) {
2190            for (int i = 0; i < allAppsSize; i++) {
2191                String pName = allAps.get(i);
2192                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2193                // Should not happen, but we shouldn't be failing if it does
2194                if (pkgSetting == null) {
2195                    continue;
2196                }
2197                boolean install = enableApps.contains(pName);
2198                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2199                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2200                            + " for system user");
2201                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2202                }
2203            }
2204        }
2205    }
2206
2207    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2208        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2209                Context.DISPLAY_SERVICE);
2210        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2211    }
2212
2213    public PackageManagerService(Context context, Installer installer,
2214            boolean factoryTest, boolean onlyCore) {
2215        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2216                SystemClock.uptimeMillis());
2217
2218        if (mSdkVersion <= 0) {
2219            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2220        }
2221
2222        mContext = context;
2223        mFactoryTest = factoryTest;
2224        mOnlyCore = onlyCore;
2225        mMetrics = new DisplayMetrics();
2226        mSettings = new Settings(mPackages);
2227        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2228                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2229        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2230                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2231        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2232                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2233        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2234                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2235        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2236                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2237        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239
2240        String separateProcesses = SystemProperties.get("debug.separate_processes");
2241        if (separateProcesses != null && separateProcesses.length() > 0) {
2242            if ("*".equals(separateProcesses)) {
2243                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2244                mSeparateProcesses = null;
2245                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2246            } else {
2247                mDefParseFlags = 0;
2248                mSeparateProcesses = separateProcesses.split(",");
2249                Slog.w(TAG, "Running with debug.separate_processes: "
2250                        + separateProcesses);
2251            }
2252        } else {
2253            mDefParseFlags = 0;
2254            mSeparateProcesses = null;
2255        }
2256
2257        mInstaller = installer;
2258        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2259                "*dexopt*");
2260        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2261
2262        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2263                FgThread.get().getLooper());
2264
2265        getDefaultDisplayMetrics(context, mMetrics);
2266
2267        SystemConfig systemConfig = SystemConfig.getInstance();
2268        mGlobalGids = systemConfig.getGlobalGids();
2269        mSystemPermissions = systemConfig.getSystemPermissions();
2270        mAvailableFeatures = systemConfig.getAvailableFeatures();
2271
2272        synchronized (mInstallLock) {
2273        // writer
2274        synchronized (mPackages) {
2275            mHandlerThread = new ServiceThread(TAG,
2276                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2277            mHandlerThread.start();
2278            mHandler = new PackageHandler(mHandlerThread.getLooper());
2279            mProcessLoggingHandler = new ProcessLoggingHandler();
2280            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2281
2282            File dataDir = Environment.getDataDirectory();
2283            mAppInstallDir = new File(dataDir, "app");
2284            mAppLib32InstallDir = new File(dataDir, "app-lib");
2285            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2286            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2287            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2288
2289            sUserManager = new UserManagerService(context, this, mPackages);
2290
2291            // Propagate permission configuration in to package manager.
2292            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2293                    = systemConfig.getPermissions();
2294            for (int i=0; i<permConfig.size(); i++) {
2295                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2296                BasePermission bp = mSettings.mPermissions.get(perm.name);
2297                if (bp == null) {
2298                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2299                    mSettings.mPermissions.put(perm.name, bp);
2300                }
2301                if (perm.gids != null) {
2302                    bp.setGids(perm.gids, perm.perUser);
2303                }
2304            }
2305
2306            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2307            for (int i=0; i<libConfig.size(); i++) {
2308                mSharedLibraries.put(libConfig.keyAt(i),
2309                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2310            }
2311
2312            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2313
2314            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2315
2316            String customResolverActivity = Resources.getSystem().getString(
2317                    R.string.config_customResolverActivity);
2318            if (TextUtils.isEmpty(customResolverActivity)) {
2319                customResolverActivity = null;
2320            } else {
2321                mCustomResolverComponentName = ComponentName.unflattenFromString(
2322                        customResolverActivity);
2323            }
2324
2325            long startTime = SystemClock.uptimeMillis();
2326
2327            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2328                    startTime);
2329
2330            // Set flag to monitor and not change apk file paths when
2331            // scanning install directories.
2332            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2333
2334            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2335            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2336
2337            if (bootClassPath == null) {
2338                Slog.w(TAG, "No BOOTCLASSPATH found!");
2339            }
2340
2341            if (systemServerClassPath == null) {
2342                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2343            }
2344
2345            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2346            final String[] dexCodeInstructionSets =
2347                    getDexCodeInstructionSets(
2348                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2349
2350            /**
2351             * Ensure all external libraries have had dexopt run on them.
2352             */
2353            if (mSharedLibraries.size() > 0) {
2354                // NOTE: For now, we're compiling these system "shared libraries"
2355                // (and framework jars) into all available architectures. It's possible
2356                // to compile them only when we come across an app that uses them (there's
2357                // already logic for that in scanPackageLI) but that adds some complexity.
2358                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2359                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2360                        final String lib = libEntry.path;
2361                        if (lib == null) {
2362                            continue;
2363                        }
2364
2365                        try {
2366                            // Shared libraries do not have profiles so we perform a full
2367                            // AOT compilation (if needed).
2368                            int dexoptNeeded = DexFile.getDexOptNeeded(
2369                                    lib, dexCodeInstructionSet,
2370                                    getCompilerFilterForReason(REASON_SHARED_APK),
2371                                    false /* newProfile */);
2372                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2373                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2374                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2375                                        getCompilerFilterForReason(REASON_SHARED_APK),
2376                                        StorageManager.UUID_PRIVATE_INTERNAL,
2377                                        SKIP_SHARED_LIBRARY_CHECK);
2378                            }
2379                        } catch (FileNotFoundException e) {
2380                            Slog.w(TAG, "Library not found: " + lib);
2381                        } catch (IOException | InstallerException e) {
2382                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2383                                    + e.getMessage());
2384                        }
2385                    }
2386                }
2387            }
2388
2389            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2390
2391            final VersionInfo ver = mSettings.getInternalVersion();
2392            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2393
2394            // when upgrading from pre-M, promote system app permissions from install to runtime
2395            mPromoteSystemApps =
2396                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2397
2398            // When upgrading from pre-N, we need to handle package extraction like first boot,
2399            // as there is no profiling data available.
2400            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2401
2402            // save off the names of pre-existing system packages prior to scanning; we don't
2403            // want to automatically grant runtime permissions for new system apps
2404            if (mPromoteSystemApps) {
2405                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2406                while (pkgSettingIter.hasNext()) {
2407                    PackageSetting ps = pkgSettingIter.next();
2408                    if (isSystemApp(ps)) {
2409                        mExistingSystemPackages.add(ps.name);
2410                    }
2411                }
2412            }
2413
2414            // Collect vendor overlay packages.
2415            // (Do this before scanning any apps.)
2416            // For security and version matching reason, only consider
2417            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2418            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2419            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2420                    | PackageParser.PARSE_IS_SYSTEM
2421                    | PackageParser.PARSE_IS_SYSTEM_DIR
2422                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2423
2424            // Find base frameworks (resource packages without code).
2425            scanDirTracedLI(frameworkDir, mDefParseFlags
2426                    | PackageParser.PARSE_IS_SYSTEM
2427                    | PackageParser.PARSE_IS_SYSTEM_DIR
2428                    | PackageParser.PARSE_IS_PRIVILEGED,
2429                    scanFlags | SCAN_NO_DEX, 0);
2430
2431            // Collected privileged system packages.
2432            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2433            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2434                    | PackageParser.PARSE_IS_SYSTEM
2435                    | PackageParser.PARSE_IS_SYSTEM_DIR
2436                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2437
2438            // Collect ordinary system packages.
2439            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2440            scanDirTracedLI(systemAppDir, mDefParseFlags
2441                    | PackageParser.PARSE_IS_SYSTEM
2442                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2443
2444            // Collect all vendor packages.
2445            File vendorAppDir = new File("/vendor/app");
2446            try {
2447                vendorAppDir = vendorAppDir.getCanonicalFile();
2448            } catch (IOException e) {
2449                // failed to look up canonical path, continue with original one
2450            }
2451            scanDirTracedLI(vendorAppDir, mDefParseFlags
2452                    | PackageParser.PARSE_IS_SYSTEM
2453                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2454
2455            // Collect all OEM packages.
2456            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2457            scanDirTracedLI(oemAppDir, mDefParseFlags
2458                    | PackageParser.PARSE_IS_SYSTEM
2459                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2460
2461            // Prune any system packages that no longer exist.
2462            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2463            if (!mOnlyCore) {
2464                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2465                while (psit.hasNext()) {
2466                    PackageSetting ps = psit.next();
2467
2468                    /*
2469                     * If this is not a system app, it can't be a
2470                     * disable system app.
2471                     */
2472                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2473                        continue;
2474                    }
2475
2476                    /*
2477                     * If the package is scanned, it's not erased.
2478                     */
2479                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2480                    if (scannedPkg != null) {
2481                        /*
2482                         * If the system app is both scanned and in the
2483                         * disabled packages list, then it must have been
2484                         * added via OTA. Remove it from the currently
2485                         * scanned package so the previously user-installed
2486                         * application can be scanned.
2487                         */
2488                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2489                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2490                                    + ps.name + "; removing system app.  Last known codePath="
2491                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2492                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2493                                    + scannedPkg.mVersionCode);
2494                            removePackageLI(scannedPkg, true);
2495                            mExpectingBetter.put(ps.name, ps.codePath);
2496                        }
2497
2498                        continue;
2499                    }
2500
2501                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2502                        psit.remove();
2503                        logCriticalInfo(Log.WARN, "System package " + ps.name
2504                                + " no longer exists; it's data will be wiped");
2505                        // Actual deletion of code and data will be handled by later
2506                        // reconciliation step
2507                    } else {
2508                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2509                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2510                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2511                        }
2512                    }
2513                }
2514            }
2515
2516            //look for any incomplete package installations
2517            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2518            for (int i = 0; i < deletePkgsList.size(); i++) {
2519                // Actual deletion of code and data will be handled by later
2520                // reconciliation step
2521                final String packageName = deletePkgsList.get(i).name;
2522                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2523                synchronized (mPackages) {
2524                    mSettings.removePackageLPw(packageName);
2525                }
2526            }
2527
2528            //delete tmp files
2529            deleteTempPackageFiles();
2530
2531            // Remove any shared userIDs that have no associated packages
2532            mSettings.pruneSharedUsersLPw();
2533
2534            if (!mOnlyCore) {
2535                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2536                        SystemClock.uptimeMillis());
2537                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2538
2539                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2540                        | PackageParser.PARSE_FORWARD_LOCK,
2541                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2542
2543                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2544                        | PackageParser.PARSE_IS_EPHEMERAL,
2545                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2546
2547                /**
2548                 * Remove disable package settings for any updated system
2549                 * apps that were removed via an OTA. If they're not a
2550                 * previously-updated app, remove them completely.
2551                 * Otherwise, just revoke their system-level permissions.
2552                 */
2553                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2554                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2555                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2556
2557                    String msg;
2558                    if (deletedPkg == null) {
2559                        msg = "Updated system package " + deletedAppName
2560                                + " no longer exists; it's data will be wiped";
2561                        // Actual deletion of code and data will be handled by later
2562                        // reconciliation step
2563                    } else {
2564                        msg = "Updated system app + " + deletedAppName
2565                                + " no longer present; removing system privileges for "
2566                                + deletedAppName;
2567
2568                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2569
2570                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2571                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2572                    }
2573                    logCriticalInfo(Log.WARN, msg);
2574                }
2575
2576                /**
2577                 * Make sure all system apps that we expected to appear on
2578                 * the userdata partition actually showed up. If they never
2579                 * appeared, crawl back and revive the system version.
2580                 */
2581                for (int i = 0; i < mExpectingBetter.size(); i++) {
2582                    final String packageName = mExpectingBetter.keyAt(i);
2583                    if (!mPackages.containsKey(packageName)) {
2584                        final File scanFile = mExpectingBetter.valueAt(i);
2585
2586                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2587                                + " but never showed up; reverting to system");
2588
2589                        int reparseFlags = mDefParseFlags;
2590                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2591                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2592                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2593                                    | PackageParser.PARSE_IS_PRIVILEGED;
2594                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2595                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2596                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2597                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2598                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2599                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2600                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2601                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2602                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2603                        } else {
2604                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2605                            continue;
2606                        }
2607
2608                        mSettings.enableSystemPackageLPw(packageName);
2609
2610                        try {
2611                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2612                        } catch (PackageManagerException e) {
2613                            Slog.e(TAG, "Failed to parse original system package: "
2614                                    + e.getMessage());
2615                        }
2616                    }
2617                }
2618            }
2619            mExpectingBetter.clear();
2620
2621            // Resolve protected action filters. Only the setup wizard is allowed to
2622            // have a high priority filter for these actions.
2623            mSetupWizardPackage = getSetupWizardPackageName();
2624            if (mProtectedFilters.size() > 0) {
2625                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2626                    Slog.i(TAG, "No setup wizard;"
2627                        + " All protected intents capped to priority 0");
2628                }
2629                for (ActivityIntentInfo filter : mProtectedFilters) {
2630                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2631                        if (DEBUG_FILTERS) {
2632                            Slog.i(TAG, "Found setup wizard;"
2633                                + " allow priority " + filter.getPriority() + ";"
2634                                + " package: " + filter.activity.info.packageName
2635                                + " activity: " + filter.activity.className
2636                                + " priority: " + filter.getPriority());
2637                        }
2638                        // skip setup wizard; allow it to keep the high priority filter
2639                        continue;
2640                    }
2641                    Slog.w(TAG, "Protected action; cap priority to 0;"
2642                            + " package: " + filter.activity.info.packageName
2643                            + " activity: " + filter.activity.className
2644                            + " origPrio: " + filter.getPriority());
2645                    filter.setPriority(0);
2646                }
2647            }
2648            mDeferProtectedFilters = false;
2649            mProtectedFilters.clear();
2650
2651            // Now that we know all of the shared libraries, update all clients to have
2652            // the correct library paths.
2653            updateAllSharedLibrariesLPw();
2654
2655            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2656                // NOTE: We ignore potential failures here during a system scan (like
2657                // the rest of the commands above) because there's precious little we
2658                // can do about it. A settings error is reported, though.
2659                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2660                        false /* boot complete */);
2661            }
2662
2663            // Now that we know all the packages we are keeping,
2664            // read and update their last usage times.
2665            mPackageUsage.readLP();
2666
2667            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2668                    SystemClock.uptimeMillis());
2669            Slog.i(TAG, "Time to scan packages: "
2670                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2671                    + " seconds");
2672
2673            // If the platform SDK has changed since the last time we booted,
2674            // we need to re-grant app permission to catch any new ones that
2675            // appear.  This is really a hack, and means that apps can in some
2676            // cases get permissions that the user didn't initially explicitly
2677            // allow...  it would be nice to have some better way to handle
2678            // this situation.
2679            int updateFlags = UPDATE_PERMISSIONS_ALL;
2680            if (ver.sdkVersion != mSdkVersion) {
2681                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2682                        + mSdkVersion + "; regranting permissions for internal storage");
2683                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2684            }
2685            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2686            ver.sdkVersion = mSdkVersion;
2687
2688            // If this is the first boot or an update from pre-M, and it is a normal
2689            // boot, then we need to initialize the default preferred apps across
2690            // all defined users.
2691            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2692                for (UserInfo user : sUserManager.getUsers(true)) {
2693                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2694                    applyFactoryDefaultBrowserLPw(user.id);
2695                    primeDomainVerificationsLPw(user.id);
2696                }
2697            }
2698
2699            // Prepare storage for system user really early during boot,
2700            // since core system apps like SettingsProvider and SystemUI
2701            // can't wait for user to start
2702            final int storageFlags;
2703            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2704                storageFlags = StorageManager.FLAG_STORAGE_DE;
2705            } else {
2706                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2707            }
2708            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2709                    storageFlags);
2710
2711            // If this is first boot after an OTA, and a normal boot, then
2712            // we need to clear code cache directories.
2713            // Note that we do *not* clear the application profiles. These remain valid
2714            // across OTAs and are used to drive profile verification (post OTA) and
2715            // profile compilation (without waiting to collect a fresh set of profiles).
2716            if (mIsUpgrade && !onlyCore) {
2717                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2718                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2719                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2720                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2721                        // No apps are running this early, so no need to freeze
2722                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2723                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2724                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2725                    }
2726                    clearAppProfilesLIF(ps.pkg, UserHandle.USER_ALL);
2727                }
2728                ver.fingerprint = Build.FINGERPRINT;
2729            }
2730
2731            checkDefaultBrowser();
2732
2733            // clear only after permissions and other defaults have been updated
2734            mExistingSystemPackages.clear();
2735            mPromoteSystemApps = false;
2736
2737            // All the changes are done during package scanning.
2738            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2739
2740            // can downgrade to reader
2741            mSettings.writeLPr();
2742
2743            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2744                    SystemClock.uptimeMillis());
2745
2746            if (!mOnlyCore) {
2747                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2748                mRequiredInstallerPackage = getRequiredInstallerLPr();
2749                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2750                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2751                        mIntentFilterVerifierComponent);
2752                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2753                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2754                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2755                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2756            } else {
2757                mRequiredVerifierPackage = null;
2758                mRequiredInstallerPackage = null;
2759                mIntentFilterVerifierComponent = null;
2760                mIntentFilterVerifier = null;
2761                mServicesSystemSharedLibraryPackageName = null;
2762                mSharedSystemSharedLibraryPackageName = null;
2763            }
2764
2765            mInstallerService = new PackageInstallerService(context, this);
2766
2767            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2768            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2769            // both the installer and resolver must be present to enable ephemeral
2770            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2771                if (DEBUG_EPHEMERAL) {
2772                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2773                            + " installer:" + ephemeralInstallerComponent);
2774                }
2775                mEphemeralResolverComponent = ephemeralResolverComponent;
2776                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2777                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2778                mEphemeralResolverConnection =
2779                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2780            } else {
2781                if (DEBUG_EPHEMERAL) {
2782                    final String missingComponent =
2783                            (ephemeralResolverComponent == null)
2784                            ? (ephemeralInstallerComponent == null)
2785                                    ? "resolver and installer"
2786                                    : "resolver"
2787                            : "installer";
2788                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2789                }
2790                mEphemeralResolverComponent = null;
2791                mEphemeralInstallerComponent = null;
2792                mEphemeralResolverConnection = null;
2793            }
2794
2795            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2796        } // synchronized (mPackages)
2797        } // synchronized (mInstallLock)
2798
2799        // Now after opening every single application zip, make sure they
2800        // are all flushed.  Not really needed, but keeps things nice and
2801        // tidy.
2802        Runtime.getRuntime().gc();
2803
2804        // The initial scanning above does many calls into installd while
2805        // holding the mPackages lock, but we're mostly interested in yelling
2806        // once we have a booted system.
2807        mInstaller.setWarnIfHeld(mPackages);
2808
2809        // Expose private service for system components to use.
2810        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2811    }
2812
2813    @Override
2814    public boolean isFirstBoot() {
2815        return !mRestoredSettings;
2816    }
2817
2818    @Override
2819    public boolean isOnlyCoreApps() {
2820        return mOnlyCore;
2821    }
2822
2823    @Override
2824    public boolean isUpgrade() {
2825        return mIsUpgrade;
2826    }
2827
2828    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2829        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2830
2831        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2832                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2833                UserHandle.USER_SYSTEM);
2834        if (matches.size() == 1) {
2835            return matches.get(0).getComponentInfo().packageName;
2836        } else {
2837            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2838            return null;
2839        }
2840    }
2841
2842    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2843        synchronized (mPackages) {
2844            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2845            if (libraryEntry == null) {
2846                throw new IllegalStateException("Missing required shared library:" + libraryName);
2847            }
2848            return libraryEntry.apk;
2849        }
2850    }
2851
2852    private @NonNull String getRequiredInstallerLPr() {
2853        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2854        intent.addCategory(Intent.CATEGORY_DEFAULT);
2855        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2856
2857        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2858                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2859                UserHandle.USER_SYSTEM);
2860        if (matches.size() == 1) {
2861            ResolveInfo resolveInfo = matches.get(0);
2862            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2863                throw new RuntimeException("The installer must be a privileged app");
2864            }
2865            return matches.get(0).getComponentInfo().packageName;
2866        } else {
2867            throw new RuntimeException("There must be exactly one installer; found " + matches);
2868        }
2869    }
2870
2871    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2872        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2873
2874        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2875                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2876                UserHandle.USER_SYSTEM);
2877        ResolveInfo best = null;
2878        final int N = matches.size();
2879        for (int i = 0; i < N; i++) {
2880            final ResolveInfo cur = matches.get(i);
2881            final String packageName = cur.getComponentInfo().packageName;
2882            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2883                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2884                continue;
2885            }
2886
2887            if (best == null || cur.priority > best.priority) {
2888                best = cur;
2889            }
2890        }
2891
2892        if (best != null) {
2893            return best.getComponentInfo().getComponentName();
2894        } else {
2895            throw new RuntimeException("There must be at least one intent filter verifier");
2896        }
2897    }
2898
2899    private @Nullable ComponentName getEphemeralResolverLPr() {
2900        final String[] packageArray =
2901                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2902        if (packageArray.length == 0) {
2903            if (DEBUG_EPHEMERAL) {
2904                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2905            }
2906            return null;
2907        }
2908
2909        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2910        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2911                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2912                UserHandle.USER_SYSTEM);
2913
2914        final int N = resolvers.size();
2915        if (N == 0) {
2916            if (DEBUG_EPHEMERAL) {
2917                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2918            }
2919            return null;
2920        }
2921
2922        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2923        for (int i = 0; i < N; i++) {
2924            final ResolveInfo info = resolvers.get(i);
2925
2926            if (info.serviceInfo == null) {
2927                continue;
2928            }
2929
2930            final String packageName = info.serviceInfo.packageName;
2931            if (!possiblePackages.contains(packageName)) {
2932                if (DEBUG_EPHEMERAL) {
2933                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2934                            + " pkg: " + packageName + ", info:" + info);
2935                }
2936                continue;
2937            }
2938
2939            if (DEBUG_EPHEMERAL) {
2940                Slog.v(TAG, "Ephemeral resolver found;"
2941                        + " pkg: " + packageName + ", info:" + info);
2942            }
2943            return new ComponentName(packageName, info.serviceInfo.name);
2944        }
2945        if (DEBUG_EPHEMERAL) {
2946            Slog.v(TAG, "Ephemeral resolver NOT found");
2947        }
2948        return null;
2949    }
2950
2951    private @Nullable ComponentName getEphemeralInstallerLPr() {
2952        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2953        intent.addCategory(Intent.CATEGORY_DEFAULT);
2954        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2955
2956        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2957                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2958                UserHandle.USER_SYSTEM);
2959        if (matches.size() == 0) {
2960            return null;
2961        } else if (matches.size() == 1) {
2962            return matches.get(0).getComponentInfo().getComponentName();
2963        } else {
2964            throw new RuntimeException(
2965                    "There must be at most one ephemeral installer; found " + matches);
2966        }
2967    }
2968
2969    private void primeDomainVerificationsLPw(int userId) {
2970        if (DEBUG_DOMAIN_VERIFICATION) {
2971            Slog.d(TAG, "Priming domain verifications in user " + userId);
2972        }
2973
2974        SystemConfig systemConfig = SystemConfig.getInstance();
2975        ArraySet<String> packages = systemConfig.getLinkedApps();
2976        ArraySet<String> domains = new ArraySet<String>();
2977
2978        for (String packageName : packages) {
2979            PackageParser.Package pkg = mPackages.get(packageName);
2980            if (pkg != null) {
2981                if (!pkg.isSystemApp()) {
2982                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2983                    continue;
2984                }
2985
2986                domains.clear();
2987                for (PackageParser.Activity a : pkg.activities) {
2988                    for (ActivityIntentInfo filter : a.intents) {
2989                        if (hasValidDomains(filter)) {
2990                            domains.addAll(filter.getHostsList());
2991                        }
2992                    }
2993                }
2994
2995                if (domains.size() > 0) {
2996                    if (DEBUG_DOMAIN_VERIFICATION) {
2997                        Slog.v(TAG, "      + " + packageName);
2998                    }
2999                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3000                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3001                    // and then 'always' in the per-user state actually used for intent resolution.
3002                    final IntentFilterVerificationInfo ivi;
3003                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3004                            new ArrayList<String>(domains));
3005                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3006                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3007                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3008                } else {
3009                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3010                            + "' does not handle web links");
3011                }
3012            } else {
3013                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3014            }
3015        }
3016
3017        scheduleWritePackageRestrictionsLocked(userId);
3018        scheduleWriteSettingsLocked();
3019    }
3020
3021    private void applyFactoryDefaultBrowserLPw(int userId) {
3022        // The default browser app's package name is stored in a string resource,
3023        // with a product-specific overlay used for vendor customization.
3024        String browserPkg = mContext.getResources().getString(
3025                com.android.internal.R.string.default_browser);
3026        if (!TextUtils.isEmpty(browserPkg)) {
3027            // non-empty string => required to be a known package
3028            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3029            if (ps == null) {
3030                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3031                browserPkg = null;
3032            } else {
3033                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3034            }
3035        }
3036
3037        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3038        // default.  If there's more than one, just leave everything alone.
3039        if (browserPkg == null) {
3040            calculateDefaultBrowserLPw(userId);
3041        }
3042    }
3043
3044    private void calculateDefaultBrowserLPw(int userId) {
3045        List<String> allBrowsers = resolveAllBrowserApps(userId);
3046        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3047        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3048    }
3049
3050    private List<String> resolveAllBrowserApps(int userId) {
3051        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3052        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3053                PackageManager.MATCH_ALL, userId);
3054
3055        final int count = list.size();
3056        List<String> result = new ArrayList<String>(count);
3057        for (int i=0; i<count; i++) {
3058            ResolveInfo info = list.get(i);
3059            if (info.activityInfo == null
3060                    || !info.handleAllWebDataURI
3061                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3062                    || result.contains(info.activityInfo.packageName)) {
3063                continue;
3064            }
3065            result.add(info.activityInfo.packageName);
3066        }
3067
3068        return result;
3069    }
3070
3071    private boolean packageIsBrowser(String packageName, int userId) {
3072        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3073                PackageManager.MATCH_ALL, userId);
3074        final int N = list.size();
3075        for (int i = 0; i < N; i++) {
3076            ResolveInfo info = list.get(i);
3077            if (packageName.equals(info.activityInfo.packageName)) {
3078                return true;
3079            }
3080        }
3081        return false;
3082    }
3083
3084    private void checkDefaultBrowser() {
3085        final int myUserId = UserHandle.myUserId();
3086        final String packageName = getDefaultBrowserPackageName(myUserId);
3087        if (packageName != null) {
3088            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3089            if (info == null) {
3090                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3091                synchronized (mPackages) {
3092                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3093                }
3094            }
3095        }
3096    }
3097
3098    @Override
3099    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3100            throws RemoteException {
3101        try {
3102            return super.onTransact(code, data, reply, flags);
3103        } catch (RuntimeException e) {
3104            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3105                Slog.wtf(TAG, "Package Manager Crash", e);
3106            }
3107            throw e;
3108        }
3109    }
3110
3111    static int[] appendInts(int[] cur, int[] add) {
3112        if (add == null) return cur;
3113        if (cur == null) return add;
3114        final int N = add.length;
3115        for (int i=0; i<N; i++) {
3116            cur = appendInt(cur, add[i]);
3117        }
3118        return cur;
3119    }
3120
3121    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3122        if (!sUserManager.exists(userId)) return null;
3123        if (ps == null) {
3124            return null;
3125        }
3126        final PackageParser.Package p = ps.pkg;
3127        if (p == null) {
3128            return null;
3129        }
3130
3131        final PermissionsState permissionsState = ps.getPermissionsState();
3132
3133        final int[] gids = permissionsState.computeGids(userId);
3134        final Set<String> permissions = permissionsState.getPermissions(userId);
3135        final PackageUserState state = ps.readUserState(userId);
3136
3137        return PackageParser.generatePackageInfo(p, gids, flags,
3138                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3139    }
3140
3141    @Override
3142    public void checkPackageStartable(String packageName, int userId) {
3143        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3144
3145        synchronized (mPackages) {
3146            final PackageSetting ps = mSettings.mPackages.get(packageName);
3147            if (ps == null) {
3148                throw new SecurityException("Package " + packageName + " was not found!");
3149            }
3150
3151            if (!ps.getInstalled(userId)) {
3152                throw new SecurityException(
3153                        "Package " + packageName + " was not installed for user " + userId + "!");
3154            }
3155
3156            if (mSafeMode && !ps.isSystem()) {
3157                throw new SecurityException("Package " + packageName + " not a system app!");
3158            }
3159
3160            if (mFrozenPackages.contains(packageName)) {
3161                throw new SecurityException("Package " + packageName + " is currently frozen!");
3162            }
3163
3164            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3165                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3166                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3167            }
3168        }
3169    }
3170
3171    @Override
3172    public boolean isPackageAvailable(String packageName, int userId) {
3173        if (!sUserManager.exists(userId)) return false;
3174        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3175                false /* requireFullPermission */, false /* checkShell */, "is package available");
3176        synchronized (mPackages) {
3177            PackageParser.Package p = mPackages.get(packageName);
3178            if (p != null) {
3179                final PackageSetting ps = (PackageSetting) p.mExtras;
3180                if (ps != null) {
3181                    final PackageUserState state = ps.readUserState(userId);
3182                    if (state != null) {
3183                        return PackageParser.isAvailable(state);
3184                    }
3185                }
3186            }
3187        }
3188        return false;
3189    }
3190
3191    @Override
3192    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3193        if (!sUserManager.exists(userId)) return null;
3194        flags = updateFlagsForPackage(flags, userId, packageName);
3195        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3196                false /* requireFullPermission */, false /* checkShell */, "get package info");
3197        // reader
3198        synchronized (mPackages) {
3199            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3200            PackageParser.Package p = null;
3201            if (matchFactoryOnly) {
3202                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3203                if (ps != null) {
3204                    return generatePackageInfo(ps, flags, userId);
3205                }
3206            }
3207            if (p == null) {
3208                p = mPackages.get(packageName);
3209                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3210                    return null;
3211                }
3212            }
3213            if (DEBUG_PACKAGE_INFO)
3214                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3215            if (p != null) {
3216                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3217            }
3218            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3219                final PackageSetting ps = mSettings.mPackages.get(packageName);
3220                return generatePackageInfo(ps, flags, userId);
3221            }
3222        }
3223        return null;
3224    }
3225
3226    @Override
3227    public String[] currentToCanonicalPackageNames(String[] names) {
3228        String[] out = new String[names.length];
3229        // reader
3230        synchronized (mPackages) {
3231            for (int i=names.length-1; i>=0; i--) {
3232                PackageSetting ps = mSettings.mPackages.get(names[i]);
3233                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3234            }
3235        }
3236        return out;
3237    }
3238
3239    @Override
3240    public String[] canonicalToCurrentPackageNames(String[] names) {
3241        String[] out = new String[names.length];
3242        // reader
3243        synchronized (mPackages) {
3244            for (int i=names.length-1; i>=0; i--) {
3245                String cur = mSettings.mRenamedPackages.get(names[i]);
3246                out[i] = cur != null ? cur : names[i];
3247            }
3248        }
3249        return out;
3250    }
3251
3252    @Override
3253    public int getPackageUid(String packageName, int flags, int userId) {
3254        if (!sUserManager.exists(userId)) return -1;
3255        flags = updateFlagsForPackage(flags, userId, packageName);
3256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3257                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3258
3259        // reader
3260        synchronized (mPackages) {
3261            final PackageParser.Package p = mPackages.get(packageName);
3262            if (p != null && p.isMatch(flags)) {
3263                return UserHandle.getUid(userId, p.applicationInfo.uid);
3264            }
3265            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3266                final PackageSetting ps = mSettings.mPackages.get(packageName);
3267                if (ps != null && ps.isMatch(flags)) {
3268                    return UserHandle.getUid(userId, ps.appId);
3269                }
3270            }
3271        }
3272
3273        return -1;
3274    }
3275
3276    @Override
3277    public int[] getPackageGids(String packageName, int flags, int userId) {
3278        if (!sUserManager.exists(userId)) return null;
3279        flags = updateFlagsForPackage(flags, userId, packageName);
3280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3281                false /* requireFullPermission */, false /* checkShell */,
3282                "getPackageGids");
3283
3284        // reader
3285        synchronized (mPackages) {
3286            final PackageParser.Package p = mPackages.get(packageName);
3287            if (p != null && p.isMatch(flags)) {
3288                PackageSetting ps = (PackageSetting) p.mExtras;
3289                return ps.getPermissionsState().computeGids(userId);
3290            }
3291            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3292                final PackageSetting ps = mSettings.mPackages.get(packageName);
3293                if (ps != null && ps.isMatch(flags)) {
3294                    return ps.getPermissionsState().computeGids(userId);
3295                }
3296            }
3297        }
3298
3299        return null;
3300    }
3301
3302    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3303        if (bp.perm != null) {
3304            return PackageParser.generatePermissionInfo(bp.perm, flags);
3305        }
3306        PermissionInfo pi = new PermissionInfo();
3307        pi.name = bp.name;
3308        pi.packageName = bp.sourcePackage;
3309        pi.nonLocalizedLabel = bp.name;
3310        pi.protectionLevel = bp.protectionLevel;
3311        return pi;
3312    }
3313
3314    @Override
3315    public PermissionInfo getPermissionInfo(String name, int flags) {
3316        // reader
3317        synchronized (mPackages) {
3318            final BasePermission p = mSettings.mPermissions.get(name);
3319            if (p != null) {
3320                return generatePermissionInfo(p, flags);
3321            }
3322            return null;
3323        }
3324    }
3325
3326    @Override
3327    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3328            int flags) {
3329        // reader
3330        synchronized (mPackages) {
3331            if (group != null && !mPermissionGroups.containsKey(group)) {
3332                // This is thrown as NameNotFoundException
3333                return null;
3334            }
3335
3336            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3337            for (BasePermission p : mSettings.mPermissions.values()) {
3338                if (group == null) {
3339                    if (p.perm == null || p.perm.info.group == null) {
3340                        out.add(generatePermissionInfo(p, flags));
3341                    }
3342                } else {
3343                    if (p.perm != null && group.equals(p.perm.info.group)) {
3344                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3345                    }
3346                }
3347            }
3348            return new ParceledListSlice<>(out);
3349        }
3350    }
3351
3352    @Override
3353    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3354        // reader
3355        synchronized (mPackages) {
3356            return PackageParser.generatePermissionGroupInfo(
3357                    mPermissionGroups.get(name), flags);
3358        }
3359    }
3360
3361    @Override
3362    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3363        // reader
3364        synchronized (mPackages) {
3365            final int N = mPermissionGroups.size();
3366            ArrayList<PermissionGroupInfo> out
3367                    = new ArrayList<PermissionGroupInfo>(N);
3368            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3369                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3370            }
3371            return new ParceledListSlice<>(out);
3372        }
3373    }
3374
3375    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3376            int userId) {
3377        if (!sUserManager.exists(userId)) return null;
3378        PackageSetting ps = mSettings.mPackages.get(packageName);
3379        if (ps != null) {
3380            if (ps.pkg == null) {
3381                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3382                if (pInfo != null) {
3383                    return pInfo.applicationInfo;
3384                }
3385                return null;
3386            }
3387            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3388                    ps.readUserState(userId), userId);
3389        }
3390        return null;
3391    }
3392
3393    @Override
3394    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3395        if (!sUserManager.exists(userId)) return null;
3396        flags = updateFlagsForApplication(flags, userId, packageName);
3397        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3398                false /* requireFullPermission */, false /* checkShell */, "get application info");
3399        // writer
3400        synchronized (mPackages) {
3401            PackageParser.Package p = mPackages.get(packageName);
3402            if (DEBUG_PACKAGE_INFO) Log.v(
3403                    TAG, "getApplicationInfo " + packageName
3404                    + ": " + p);
3405            if (p != null) {
3406                PackageSetting ps = mSettings.mPackages.get(packageName);
3407                if (ps == null) return null;
3408                // Note: isEnabledLP() does not apply here - always return info
3409                return PackageParser.generateApplicationInfo(
3410                        p, flags, ps.readUserState(userId), userId);
3411            }
3412            if ("android".equals(packageName)||"system".equals(packageName)) {
3413                return mAndroidApplication;
3414            }
3415            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3416                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3417            }
3418        }
3419        return null;
3420    }
3421
3422    @Override
3423    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3424            final IPackageDataObserver observer) {
3425        mContext.enforceCallingOrSelfPermission(
3426                android.Manifest.permission.CLEAR_APP_CACHE, null);
3427        // Queue up an async operation since clearing cache may take a little while.
3428        mHandler.post(new Runnable() {
3429            public void run() {
3430                mHandler.removeCallbacks(this);
3431                boolean success = true;
3432                synchronized (mInstallLock) {
3433                    try {
3434                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3435                    } catch (InstallerException e) {
3436                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3437                        success = false;
3438                    }
3439                }
3440                if (observer != null) {
3441                    try {
3442                        observer.onRemoveCompleted(null, success);
3443                    } catch (RemoteException e) {
3444                        Slog.w(TAG, "RemoveException when invoking call back");
3445                    }
3446                }
3447            }
3448        });
3449    }
3450
3451    @Override
3452    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3453            final IntentSender pi) {
3454        mContext.enforceCallingOrSelfPermission(
3455                android.Manifest.permission.CLEAR_APP_CACHE, null);
3456        // Queue up an async operation since clearing cache may take a little while.
3457        mHandler.post(new Runnable() {
3458            public void run() {
3459                mHandler.removeCallbacks(this);
3460                boolean success = true;
3461                synchronized (mInstallLock) {
3462                    try {
3463                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3464                    } catch (InstallerException e) {
3465                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3466                        success = false;
3467                    }
3468                }
3469                if(pi != null) {
3470                    try {
3471                        // Callback via pending intent
3472                        int code = success ? 1 : 0;
3473                        pi.sendIntent(null, code, null,
3474                                null, null);
3475                    } catch (SendIntentException e1) {
3476                        Slog.i(TAG, "Failed to send pending intent");
3477                    }
3478                }
3479            }
3480        });
3481    }
3482
3483    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3484        synchronized (mInstallLock) {
3485            try {
3486                mInstaller.freeCache(volumeUuid, freeStorageSize);
3487            } catch (InstallerException e) {
3488                throw new IOException("Failed to free enough space", e);
3489            }
3490        }
3491    }
3492
3493    /**
3494     * Update given flags based on encryption status of current user.
3495     */
3496    private int updateFlags(int flags, int userId) {
3497        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3498                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3499            // Caller expressed an explicit opinion about what encryption
3500            // aware/unaware components they want to see, so fall through and
3501            // give them what they want
3502        } else {
3503            // Caller expressed no opinion, so match based on user state
3504            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3505                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3506            } else {
3507                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3508            }
3509        }
3510        return flags;
3511    }
3512
3513    private UserManagerInternal getUserManagerInternal() {
3514        if (mUserManagerInternal == null) {
3515            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3516        }
3517        return mUserManagerInternal;
3518    }
3519
3520    /**
3521     * Update given flags when being used to request {@link PackageInfo}.
3522     */
3523    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3524        boolean triaged = true;
3525        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3526                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3527            // Caller is asking for component details, so they'd better be
3528            // asking for specific encryption matching behavior, or be triaged
3529            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3530                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3531                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3532                triaged = false;
3533            }
3534        }
3535        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3536                | PackageManager.MATCH_SYSTEM_ONLY
3537                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3538            triaged = false;
3539        }
3540        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3541            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3542                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3543        }
3544        return updateFlags(flags, userId);
3545    }
3546
3547    /**
3548     * Update given flags when being used to request {@link ApplicationInfo}.
3549     */
3550    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3551        return updateFlagsForPackage(flags, userId, cookie);
3552    }
3553
3554    /**
3555     * Update given flags when being used to request {@link ComponentInfo}.
3556     */
3557    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3558        if (cookie instanceof Intent) {
3559            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3560                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3561            }
3562        }
3563
3564        boolean triaged = true;
3565        // Caller is asking for component details, so they'd better be
3566        // asking for specific encryption matching behavior, or be triaged
3567        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3568                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3569                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3570            triaged = false;
3571        }
3572        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3573            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3574                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3575        }
3576
3577        return updateFlags(flags, userId);
3578    }
3579
3580    /**
3581     * Update given flags when being used to request {@link ResolveInfo}.
3582     */
3583    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3584        // Safe mode means we shouldn't match any third-party components
3585        if (mSafeMode) {
3586            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3587        }
3588
3589        return updateFlagsForComponent(flags, userId, cookie);
3590    }
3591
3592    @Override
3593    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3594        if (!sUserManager.exists(userId)) return null;
3595        flags = updateFlagsForComponent(flags, userId, component);
3596        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3597                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3598        synchronized (mPackages) {
3599            PackageParser.Activity a = mActivities.mActivities.get(component);
3600
3601            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3602            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3603                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3604                if (ps == null) return null;
3605                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3606                        userId);
3607            }
3608            if (mResolveComponentName.equals(component)) {
3609                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3610                        new PackageUserState(), userId);
3611            }
3612        }
3613        return null;
3614    }
3615
3616    @Override
3617    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3618            String resolvedType) {
3619        synchronized (mPackages) {
3620            if (component.equals(mResolveComponentName)) {
3621                // The resolver supports EVERYTHING!
3622                return true;
3623            }
3624            PackageParser.Activity a = mActivities.mActivities.get(component);
3625            if (a == null) {
3626                return false;
3627            }
3628            for (int i=0; i<a.intents.size(); i++) {
3629                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3630                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3631                    return true;
3632                }
3633            }
3634            return false;
3635        }
3636    }
3637
3638    @Override
3639    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3640        if (!sUserManager.exists(userId)) return null;
3641        flags = updateFlagsForComponent(flags, userId, component);
3642        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3643                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3644        synchronized (mPackages) {
3645            PackageParser.Activity a = mReceivers.mActivities.get(component);
3646            if (DEBUG_PACKAGE_INFO) Log.v(
3647                TAG, "getReceiverInfo " + component + ": " + a);
3648            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3649                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3650                if (ps == null) return null;
3651                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3652                        userId);
3653            }
3654        }
3655        return null;
3656    }
3657
3658    @Override
3659    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3660        if (!sUserManager.exists(userId)) return null;
3661        flags = updateFlagsForComponent(flags, userId, component);
3662        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3663                false /* requireFullPermission */, false /* checkShell */, "get service info");
3664        synchronized (mPackages) {
3665            PackageParser.Service s = mServices.mServices.get(component);
3666            if (DEBUG_PACKAGE_INFO) Log.v(
3667                TAG, "getServiceInfo " + component + ": " + s);
3668            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3669                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3670                if (ps == null) return null;
3671                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3672                        userId);
3673            }
3674        }
3675        return null;
3676    }
3677
3678    @Override
3679    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3680        if (!sUserManager.exists(userId)) return null;
3681        flags = updateFlagsForComponent(flags, userId, component);
3682        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3683                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3684        synchronized (mPackages) {
3685            PackageParser.Provider p = mProviders.mProviders.get(component);
3686            if (DEBUG_PACKAGE_INFO) Log.v(
3687                TAG, "getProviderInfo " + component + ": " + p);
3688            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3689                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3690                if (ps == null) return null;
3691                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3692                        userId);
3693            }
3694        }
3695        return null;
3696    }
3697
3698    @Override
3699    public String[] getSystemSharedLibraryNames() {
3700        Set<String> libSet;
3701        synchronized (mPackages) {
3702            libSet = mSharedLibraries.keySet();
3703            int size = libSet.size();
3704            if (size > 0) {
3705                String[] libs = new String[size];
3706                libSet.toArray(libs);
3707                return libs;
3708            }
3709        }
3710        return null;
3711    }
3712
3713    @Override
3714    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3715        synchronized (mPackages) {
3716            return mServicesSystemSharedLibraryPackageName;
3717        }
3718    }
3719
3720    @Override
3721    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3722        synchronized (mPackages) {
3723            return mSharedSystemSharedLibraryPackageName;
3724        }
3725    }
3726
3727    @Override
3728    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3729        synchronized (mPackages) {
3730            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3731
3732            final FeatureInfo fi = new FeatureInfo();
3733            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3734                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3735            res.add(fi);
3736
3737            return new ParceledListSlice<>(res);
3738        }
3739    }
3740
3741    @Override
3742    public boolean hasSystemFeature(String name, int version) {
3743        synchronized (mPackages) {
3744            final FeatureInfo feat = mAvailableFeatures.get(name);
3745            if (feat == null) {
3746                return false;
3747            } else {
3748                return feat.version >= version;
3749            }
3750        }
3751    }
3752
3753    @Override
3754    public int checkPermission(String permName, String pkgName, int userId) {
3755        if (!sUserManager.exists(userId)) {
3756            return PackageManager.PERMISSION_DENIED;
3757        }
3758
3759        synchronized (mPackages) {
3760            final PackageParser.Package p = mPackages.get(pkgName);
3761            if (p != null && p.mExtras != null) {
3762                final PackageSetting ps = (PackageSetting) p.mExtras;
3763                final PermissionsState permissionsState = ps.getPermissionsState();
3764                if (permissionsState.hasPermission(permName, userId)) {
3765                    return PackageManager.PERMISSION_GRANTED;
3766                }
3767                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3768                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3769                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3770                    return PackageManager.PERMISSION_GRANTED;
3771                }
3772            }
3773        }
3774
3775        return PackageManager.PERMISSION_DENIED;
3776    }
3777
3778    @Override
3779    public int checkUidPermission(String permName, int uid) {
3780        final int userId = UserHandle.getUserId(uid);
3781
3782        if (!sUserManager.exists(userId)) {
3783            return PackageManager.PERMISSION_DENIED;
3784        }
3785
3786        synchronized (mPackages) {
3787            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3788            if (obj != null) {
3789                final SettingBase ps = (SettingBase) obj;
3790                final PermissionsState permissionsState = ps.getPermissionsState();
3791                if (permissionsState.hasPermission(permName, userId)) {
3792                    return PackageManager.PERMISSION_GRANTED;
3793                }
3794                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3795                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3796                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3797                    return PackageManager.PERMISSION_GRANTED;
3798                }
3799            } else {
3800                ArraySet<String> perms = mSystemPermissions.get(uid);
3801                if (perms != null) {
3802                    if (perms.contains(permName)) {
3803                        return PackageManager.PERMISSION_GRANTED;
3804                    }
3805                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3806                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3807                        return PackageManager.PERMISSION_GRANTED;
3808                    }
3809                }
3810            }
3811        }
3812
3813        return PackageManager.PERMISSION_DENIED;
3814    }
3815
3816    @Override
3817    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3818        if (UserHandle.getCallingUserId() != userId) {
3819            mContext.enforceCallingPermission(
3820                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3821                    "isPermissionRevokedByPolicy for user " + userId);
3822        }
3823
3824        if (checkPermission(permission, packageName, userId)
3825                == PackageManager.PERMISSION_GRANTED) {
3826            return false;
3827        }
3828
3829        final long identity = Binder.clearCallingIdentity();
3830        try {
3831            final int flags = getPermissionFlags(permission, packageName, userId);
3832            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3833        } finally {
3834            Binder.restoreCallingIdentity(identity);
3835        }
3836    }
3837
3838    @Override
3839    public String getPermissionControllerPackageName() {
3840        synchronized (mPackages) {
3841            return mRequiredInstallerPackage;
3842        }
3843    }
3844
3845    /**
3846     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3847     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3848     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3849     * @param message the message to log on security exception
3850     */
3851    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3852            boolean checkShell, String message) {
3853        if (userId < 0) {
3854            throw new IllegalArgumentException("Invalid userId " + userId);
3855        }
3856        if (checkShell) {
3857            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3858        }
3859        if (userId == UserHandle.getUserId(callingUid)) return;
3860        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3861            if (requireFullPermission) {
3862                mContext.enforceCallingOrSelfPermission(
3863                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3864            } else {
3865                try {
3866                    mContext.enforceCallingOrSelfPermission(
3867                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3868                } catch (SecurityException se) {
3869                    mContext.enforceCallingOrSelfPermission(
3870                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3871                }
3872            }
3873        }
3874    }
3875
3876    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3877        if (callingUid == Process.SHELL_UID) {
3878            if (userHandle >= 0
3879                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3880                throw new SecurityException("Shell does not have permission to access user "
3881                        + userHandle);
3882            } else if (userHandle < 0) {
3883                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3884                        + Debug.getCallers(3));
3885            }
3886        }
3887    }
3888
3889    private BasePermission findPermissionTreeLP(String permName) {
3890        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3891            if (permName.startsWith(bp.name) &&
3892                    permName.length() > bp.name.length() &&
3893                    permName.charAt(bp.name.length()) == '.') {
3894                return bp;
3895            }
3896        }
3897        return null;
3898    }
3899
3900    private BasePermission checkPermissionTreeLP(String permName) {
3901        if (permName != null) {
3902            BasePermission bp = findPermissionTreeLP(permName);
3903            if (bp != null) {
3904                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3905                    return bp;
3906                }
3907                throw new SecurityException("Calling uid "
3908                        + Binder.getCallingUid()
3909                        + " is not allowed to add to permission tree "
3910                        + bp.name + " owned by uid " + bp.uid);
3911            }
3912        }
3913        throw new SecurityException("No permission tree found for " + permName);
3914    }
3915
3916    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3917        if (s1 == null) {
3918            return s2 == null;
3919        }
3920        if (s2 == null) {
3921            return false;
3922        }
3923        if (s1.getClass() != s2.getClass()) {
3924            return false;
3925        }
3926        return s1.equals(s2);
3927    }
3928
3929    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3930        if (pi1.icon != pi2.icon) return false;
3931        if (pi1.logo != pi2.logo) return false;
3932        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3933        if (!compareStrings(pi1.name, pi2.name)) return false;
3934        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3935        // We'll take care of setting this one.
3936        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3937        // These are not currently stored in settings.
3938        //if (!compareStrings(pi1.group, pi2.group)) return false;
3939        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3940        //if (pi1.labelRes != pi2.labelRes) return false;
3941        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3942        return true;
3943    }
3944
3945    int permissionInfoFootprint(PermissionInfo info) {
3946        int size = info.name.length();
3947        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3948        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3949        return size;
3950    }
3951
3952    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3953        int size = 0;
3954        for (BasePermission perm : mSettings.mPermissions.values()) {
3955            if (perm.uid == tree.uid) {
3956                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3957            }
3958        }
3959        return size;
3960    }
3961
3962    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3963        // We calculate the max size of permissions defined by this uid and throw
3964        // if that plus the size of 'info' would exceed our stated maximum.
3965        if (tree.uid != Process.SYSTEM_UID) {
3966            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3967            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3968                throw new SecurityException("Permission tree size cap exceeded");
3969            }
3970        }
3971    }
3972
3973    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3974        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3975            throw new SecurityException("Label must be specified in permission");
3976        }
3977        BasePermission tree = checkPermissionTreeLP(info.name);
3978        BasePermission bp = mSettings.mPermissions.get(info.name);
3979        boolean added = bp == null;
3980        boolean changed = true;
3981        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3982        if (added) {
3983            enforcePermissionCapLocked(info, tree);
3984            bp = new BasePermission(info.name, tree.sourcePackage,
3985                    BasePermission.TYPE_DYNAMIC);
3986        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3987            throw new SecurityException(
3988                    "Not allowed to modify non-dynamic permission "
3989                    + info.name);
3990        } else {
3991            if (bp.protectionLevel == fixedLevel
3992                    && bp.perm.owner.equals(tree.perm.owner)
3993                    && bp.uid == tree.uid
3994                    && comparePermissionInfos(bp.perm.info, info)) {
3995                changed = false;
3996            }
3997        }
3998        bp.protectionLevel = fixedLevel;
3999        info = new PermissionInfo(info);
4000        info.protectionLevel = fixedLevel;
4001        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4002        bp.perm.info.packageName = tree.perm.info.packageName;
4003        bp.uid = tree.uid;
4004        if (added) {
4005            mSettings.mPermissions.put(info.name, bp);
4006        }
4007        if (changed) {
4008            if (!async) {
4009                mSettings.writeLPr();
4010            } else {
4011                scheduleWriteSettingsLocked();
4012            }
4013        }
4014        return added;
4015    }
4016
4017    @Override
4018    public boolean addPermission(PermissionInfo info) {
4019        synchronized (mPackages) {
4020            return addPermissionLocked(info, false);
4021        }
4022    }
4023
4024    @Override
4025    public boolean addPermissionAsync(PermissionInfo info) {
4026        synchronized (mPackages) {
4027            return addPermissionLocked(info, true);
4028        }
4029    }
4030
4031    @Override
4032    public void removePermission(String name) {
4033        synchronized (mPackages) {
4034            checkPermissionTreeLP(name);
4035            BasePermission bp = mSettings.mPermissions.get(name);
4036            if (bp != null) {
4037                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4038                    throw new SecurityException(
4039                            "Not allowed to modify non-dynamic permission "
4040                            + name);
4041                }
4042                mSettings.mPermissions.remove(name);
4043                mSettings.writeLPr();
4044            }
4045        }
4046    }
4047
4048    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4049            BasePermission bp) {
4050        int index = pkg.requestedPermissions.indexOf(bp.name);
4051        if (index == -1) {
4052            throw new SecurityException("Package " + pkg.packageName
4053                    + " has not requested permission " + bp.name);
4054        }
4055        if (!bp.isRuntime() && !bp.isDevelopment()) {
4056            throw new SecurityException("Permission " + bp.name
4057                    + " is not a changeable permission type");
4058        }
4059    }
4060
4061    @Override
4062    public void grantRuntimePermission(String packageName, String name, final int userId) {
4063        if (!sUserManager.exists(userId)) {
4064            Log.e(TAG, "No such user:" + userId);
4065            return;
4066        }
4067
4068        mContext.enforceCallingOrSelfPermission(
4069                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4070                "grantRuntimePermission");
4071
4072        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4073                true /* requireFullPermission */, true /* checkShell */,
4074                "grantRuntimePermission");
4075
4076        final int uid;
4077        final SettingBase sb;
4078
4079        synchronized (mPackages) {
4080            final PackageParser.Package pkg = mPackages.get(packageName);
4081            if (pkg == null) {
4082                throw new IllegalArgumentException("Unknown package: " + packageName);
4083            }
4084
4085            final BasePermission bp = mSettings.mPermissions.get(name);
4086            if (bp == null) {
4087                throw new IllegalArgumentException("Unknown permission: " + name);
4088            }
4089
4090            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4091
4092            // If a permission review is required for legacy apps we represent
4093            // their permissions as always granted runtime ones since we need
4094            // to keep the review required permission flag per user while an
4095            // install permission's state is shared across all users.
4096            if (Build.PERMISSIONS_REVIEW_REQUIRED
4097                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4098                    && bp.isRuntime()) {
4099                return;
4100            }
4101
4102            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4103            sb = (SettingBase) pkg.mExtras;
4104            if (sb == null) {
4105                throw new IllegalArgumentException("Unknown package: " + packageName);
4106            }
4107
4108            final PermissionsState permissionsState = sb.getPermissionsState();
4109
4110            final int flags = permissionsState.getPermissionFlags(name, userId);
4111            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4112                throw new SecurityException("Cannot grant system fixed permission "
4113                        + name + " for package " + packageName);
4114            }
4115
4116            if (bp.isDevelopment()) {
4117                // Development permissions must be handled specially, since they are not
4118                // normal runtime permissions.  For now they apply to all users.
4119                if (permissionsState.grantInstallPermission(bp) !=
4120                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4121                    scheduleWriteSettingsLocked();
4122                }
4123                return;
4124            }
4125
4126            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4127                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4128                return;
4129            }
4130
4131            final int result = permissionsState.grantRuntimePermission(bp, userId);
4132            switch (result) {
4133                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4134                    return;
4135                }
4136
4137                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4138                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4139                    mHandler.post(new Runnable() {
4140                        @Override
4141                        public void run() {
4142                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4143                        }
4144                    });
4145                }
4146                break;
4147            }
4148
4149            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4150
4151            // Not critical if that is lost - app has to request again.
4152            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4153        }
4154
4155        // Only need to do this if user is initialized. Otherwise it's a new user
4156        // and there are no processes running as the user yet and there's no need
4157        // to make an expensive call to remount processes for the changed permissions.
4158        if (READ_EXTERNAL_STORAGE.equals(name)
4159                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4160            final long token = Binder.clearCallingIdentity();
4161            try {
4162                if (sUserManager.isInitialized(userId)) {
4163                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4164                            MountServiceInternal.class);
4165                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4166                }
4167            } finally {
4168                Binder.restoreCallingIdentity(token);
4169            }
4170        }
4171    }
4172
4173    @Override
4174    public void revokeRuntimePermission(String packageName, String name, int userId) {
4175        if (!sUserManager.exists(userId)) {
4176            Log.e(TAG, "No such user:" + userId);
4177            return;
4178        }
4179
4180        mContext.enforceCallingOrSelfPermission(
4181                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4182                "revokeRuntimePermission");
4183
4184        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4185                true /* requireFullPermission */, true /* checkShell */,
4186                "revokeRuntimePermission");
4187
4188        final int appId;
4189
4190        synchronized (mPackages) {
4191            final PackageParser.Package pkg = mPackages.get(packageName);
4192            if (pkg == null) {
4193                throw new IllegalArgumentException("Unknown package: " + packageName);
4194            }
4195
4196            final BasePermission bp = mSettings.mPermissions.get(name);
4197            if (bp == null) {
4198                throw new IllegalArgumentException("Unknown permission: " + name);
4199            }
4200
4201            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4202
4203            // If a permission review is required for legacy apps we represent
4204            // their permissions as always granted runtime ones since we need
4205            // to keep the review required permission flag per user while an
4206            // install permission's state is shared across all users.
4207            if (Build.PERMISSIONS_REVIEW_REQUIRED
4208                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4209                    && bp.isRuntime()) {
4210                return;
4211            }
4212
4213            SettingBase sb = (SettingBase) pkg.mExtras;
4214            if (sb == null) {
4215                throw new IllegalArgumentException("Unknown package: " + packageName);
4216            }
4217
4218            final PermissionsState permissionsState = sb.getPermissionsState();
4219
4220            final int flags = permissionsState.getPermissionFlags(name, userId);
4221            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4222                throw new SecurityException("Cannot revoke system fixed permission "
4223                        + name + " for package " + packageName);
4224            }
4225
4226            if (bp.isDevelopment()) {
4227                // Development permissions must be handled specially, since they are not
4228                // normal runtime permissions.  For now they apply to all users.
4229                if (permissionsState.revokeInstallPermission(bp) !=
4230                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4231                    scheduleWriteSettingsLocked();
4232                }
4233                return;
4234            }
4235
4236            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4237                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4238                return;
4239            }
4240
4241            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4242
4243            // Critical, after this call app should never have the permission.
4244            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4245
4246            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4247        }
4248
4249        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4250    }
4251
4252    @Override
4253    public void resetRuntimePermissions() {
4254        mContext.enforceCallingOrSelfPermission(
4255                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4256                "revokeRuntimePermission");
4257
4258        int callingUid = Binder.getCallingUid();
4259        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4260            mContext.enforceCallingOrSelfPermission(
4261                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4262                    "resetRuntimePermissions");
4263        }
4264
4265        synchronized (mPackages) {
4266            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4267            for (int userId : UserManagerService.getInstance().getUserIds()) {
4268                final int packageCount = mPackages.size();
4269                for (int i = 0; i < packageCount; i++) {
4270                    PackageParser.Package pkg = mPackages.valueAt(i);
4271                    if (!(pkg.mExtras instanceof PackageSetting)) {
4272                        continue;
4273                    }
4274                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4275                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4276                }
4277            }
4278        }
4279    }
4280
4281    @Override
4282    public int getPermissionFlags(String name, String packageName, int userId) {
4283        if (!sUserManager.exists(userId)) {
4284            return 0;
4285        }
4286
4287        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4288
4289        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4290                true /* requireFullPermission */, false /* checkShell */,
4291                "getPermissionFlags");
4292
4293        synchronized (mPackages) {
4294            final PackageParser.Package pkg = mPackages.get(packageName);
4295            if (pkg == null) {
4296                return 0;
4297            }
4298
4299            final BasePermission bp = mSettings.mPermissions.get(name);
4300            if (bp == null) {
4301                return 0;
4302            }
4303
4304            SettingBase sb = (SettingBase) pkg.mExtras;
4305            if (sb == null) {
4306                return 0;
4307            }
4308
4309            PermissionsState permissionsState = sb.getPermissionsState();
4310            return permissionsState.getPermissionFlags(name, userId);
4311        }
4312    }
4313
4314    @Override
4315    public void updatePermissionFlags(String name, String packageName, int flagMask,
4316            int flagValues, int userId) {
4317        if (!sUserManager.exists(userId)) {
4318            return;
4319        }
4320
4321        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4322
4323        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4324                true /* requireFullPermission */, true /* checkShell */,
4325                "updatePermissionFlags");
4326
4327        // Only the system can change these flags and nothing else.
4328        if (getCallingUid() != Process.SYSTEM_UID) {
4329            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4330            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4331            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4332            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4333            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4334        }
4335
4336        synchronized (mPackages) {
4337            final PackageParser.Package pkg = mPackages.get(packageName);
4338            if (pkg == null) {
4339                throw new IllegalArgumentException("Unknown package: " + packageName);
4340            }
4341
4342            final BasePermission bp = mSettings.mPermissions.get(name);
4343            if (bp == null) {
4344                throw new IllegalArgumentException("Unknown permission: " + name);
4345            }
4346
4347            SettingBase sb = (SettingBase) pkg.mExtras;
4348            if (sb == null) {
4349                throw new IllegalArgumentException("Unknown package: " + packageName);
4350            }
4351
4352            PermissionsState permissionsState = sb.getPermissionsState();
4353
4354            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4355
4356            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4357                // Install and runtime permissions are stored in different places,
4358                // so figure out what permission changed and persist the change.
4359                if (permissionsState.getInstallPermissionState(name) != null) {
4360                    scheduleWriteSettingsLocked();
4361                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4362                        || hadState) {
4363                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4364                }
4365            }
4366        }
4367    }
4368
4369    /**
4370     * Update the permission flags for all packages and runtime permissions of a user in order
4371     * to allow device or profile owner to remove POLICY_FIXED.
4372     */
4373    @Override
4374    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4375        if (!sUserManager.exists(userId)) {
4376            return;
4377        }
4378
4379        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4380
4381        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4382                true /* requireFullPermission */, true /* checkShell */,
4383                "updatePermissionFlagsForAllApps");
4384
4385        // Only the system can change system fixed flags.
4386        if (getCallingUid() != Process.SYSTEM_UID) {
4387            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4388            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4389        }
4390
4391        synchronized (mPackages) {
4392            boolean changed = false;
4393            final int packageCount = mPackages.size();
4394            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4395                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4396                SettingBase sb = (SettingBase) pkg.mExtras;
4397                if (sb == null) {
4398                    continue;
4399                }
4400                PermissionsState permissionsState = sb.getPermissionsState();
4401                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4402                        userId, flagMask, flagValues);
4403            }
4404            if (changed) {
4405                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4406            }
4407        }
4408    }
4409
4410    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4411        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4412                != PackageManager.PERMISSION_GRANTED
4413            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4414                != PackageManager.PERMISSION_GRANTED) {
4415            throw new SecurityException(message + " requires "
4416                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4417                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4418        }
4419    }
4420
4421    @Override
4422    public boolean shouldShowRequestPermissionRationale(String permissionName,
4423            String packageName, int userId) {
4424        if (UserHandle.getCallingUserId() != userId) {
4425            mContext.enforceCallingPermission(
4426                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4427                    "canShowRequestPermissionRationale for user " + userId);
4428        }
4429
4430        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4431        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4432            return false;
4433        }
4434
4435        if (checkPermission(permissionName, packageName, userId)
4436                == PackageManager.PERMISSION_GRANTED) {
4437            return false;
4438        }
4439
4440        final int flags;
4441
4442        final long identity = Binder.clearCallingIdentity();
4443        try {
4444            flags = getPermissionFlags(permissionName,
4445                    packageName, userId);
4446        } finally {
4447            Binder.restoreCallingIdentity(identity);
4448        }
4449
4450        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4451                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4452                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4453
4454        if ((flags & fixedFlags) != 0) {
4455            return false;
4456        }
4457
4458        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4459    }
4460
4461    @Override
4462    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4463        mContext.enforceCallingOrSelfPermission(
4464                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4465                "addOnPermissionsChangeListener");
4466
4467        synchronized (mPackages) {
4468            mOnPermissionChangeListeners.addListenerLocked(listener);
4469        }
4470    }
4471
4472    @Override
4473    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4474        synchronized (mPackages) {
4475            mOnPermissionChangeListeners.removeListenerLocked(listener);
4476        }
4477    }
4478
4479    @Override
4480    public boolean isProtectedBroadcast(String actionName) {
4481        synchronized (mPackages) {
4482            if (mProtectedBroadcasts.contains(actionName)) {
4483                return true;
4484            } else if (actionName != null) {
4485                // TODO: remove these terrible hacks
4486                if (actionName.startsWith("android.net.netmon.lingerExpired")
4487                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4488                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4489                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4490                    return true;
4491                }
4492            }
4493        }
4494        return false;
4495    }
4496
4497    @Override
4498    public int checkSignatures(String pkg1, String pkg2) {
4499        synchronized (mPackages) {
4500            final PackageParser.Package p1 = mPackages.get(pkg1);
4501            final PackageParser.Package p2 = mPackages.get(pkg2);
4502            if (p1 == null || p1.mExtras == null
4503                    || p2 == null || p2.mExtras == null) {
4504                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4505            }
4506            return compareSignatures(p1.mSignatures, p2.mSignatures);
4507        }
4508    }
4509
4510    @Override
4511    public int checkUidSignatures(int uid1, int uid2) {
4512        // Map to base uids.
4513        uid1 = UserHandle.getAppId(uid1);
4514        uid2 = UserHandle.getAppId(uid2);
4515        // reader
4516        synchronized (mPackages) {
4517            Signature[] s1;
4518            Signature[] s2;
4519            Object obj = mSettings.getUserIdLPr(uid1);
4520            if (obj != null) {
4521                if (obj instanceof SharedUserSetting) {
4522                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4523                } else if (obj instanceof PackageSetting) {
4524                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4525                } else {
4526                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4527                }
4528            } else {
4529                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4530            }
4531            obj = mSettings.getUserIdLPr(uid2);
4532            if (obj != null) {
4533                if (obj instanceof SharedUserSetting) {
4534                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4535                } else if (obj instanceof PackageSetting) {
4536                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4537                } else {
4538                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4539                }
4540            } else {
4541                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4542            }
4543            return compareSignatures(s1, s2);
4544        }
4545    }
4546
4547    /**
4548     * This method should typically only be used when granting or revoking
4549     * permissions, since the app may immediately restart after this call.
4550     * <p>
4551     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4552     * guard your work against the app being relaunched.
4553     */
4554    private void killUid(int appId, int userId, String reason) {
4555        final long identity = Binder.clearCallingIdentity();
4556        try {
4557            IActivityManager am = ActivityManagerNative.getDefault();
4558            if (am != null) {
4559                try {
4560                    am.killUid(appId, userId, reason);
4561                } catch (RemoteException e) {
4562                    /* ignore - same process */
4563                }
4564            }
4565        } finally {
4566            Binder.restoreCallingIdentity(identity);
4567        }
4568    }
4569
4570    /**
4571     * Compares two sets of signatures. Returns:
4572     * <br />
4573     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4574     * <br />
4575     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4576     * <br />
4577     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4578     * <br />
4579     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4580     * <br />
4581     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4582     */
4583    static int compareSignatures(Signature[] s1, Signature[] s2) {
4584        if (s1 == null) {
4585            return s2 == null
4586                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4587                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4588        }
4589
4590        if (s2 == null) {
4591            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4592        }
4593
4594        if (s1.length != s2.length) {
4595            return PackageManager.SIGNATURE_NO_MATCH;
4596        }
4597
4598        // Since both signature sets are of size 1, we can compare without HashSets.
4599        if (s1.length == 1) {
4600            return s1[0].equals(s2[0]) ?
4601                    PackageManager.SIGNATURE_MATCH :
4602                    PackageManager.SIGNATURE_NO_MATCH;
4603        }
4604
4605        ArraySet<Signature> set1 = new ArraySet<Signature>();
4606        for (Signature sig : s1) {
4607            set1.add(sig);
4608        }
4609        ArraySet<Signature> set2 = new ArraySet<Signature>();
4610        for (Signature sig : s2) {
4611            set2.add(sig);
4612        }
4613        // Make sure s2 contains all signatures in s1.
4614        if (set1.equals(set2)) {
4615            return PackageManager.SIGNATURE_MATCH;
4616        }
4617        return PackageManager.SIGNATURE_NO_MATCH;
4618    }
4619
4620    /**
4621     * If the database version for this type of package (internal storage or
4622     * external storage) is less than the version where package signatures
4623     * were updated, return true.
4624     */
4625    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4626        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4627        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4628    }
4629
4630    /**
4631     * Used for backward compatibility to make sure any packages with
4632     * certificate chains get upgraded to the new style. {@code existingSigs}
4633     * will be in the old format (since they were stored on disk from before the
4634     * system upgrade) and {@code scannedSigs} will be in the newer format.
4635     */
4636    private int compareSignaturesCompat(PackageSignatures existingSigs,
4637            PackageParser.Package scannedPkg) {
4638        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4639            return PackageManager.SIGNATURE_NO_MATCH;
4640        }
4641
4642        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4643        for (Signature sig : existingSigs.mSignatures) {
4644            existingSet.add(sig);
4645        }
4646        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4647        for (Signature sig : scannedPkg.mSignatures) {
4648            try {
4649                Signature[] chainSignatures = sig.getChainSignatures();
4650                for (Signature chainSig : chainSignatures) {
4651                    scannedCompatSet.add(chainSig);
4652                }
4653            } catch (CertificateEncodingException e) {
4654                scannedCompatSet.add(sig);
4655            }
4656        }
4657        /*
4658         * Make sure the expanded scanned set contains all signatures in the
4659         * existing one.
4660         */
4661        if (scannedCompatSet.equals(existingSet)) {
4662            // Migrate the old signatures to the new scheme.
4663            existingSigs.assignSignatures(scannedPkg.mSignatures);
4664            // The new KeySets will be re-added later in the scanning process.
4665            synchronized (mPackages) {
4666                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4667            }
4668            return PackageManager.SIGNATURE_MATCH;
4669        }
4670        return PackageManager.SIGNATURE_NO_MATCH;
4671    }
4672
4673    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4674        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4675        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4676    }
4677
4678    private int compareSignaturesRecover(PackageSignatures existingSigs,
4679            PackageParser.Package scannedPkg) {
4680        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4681            return PackageManager.SIGNATURE_NO_MATCH;
4682        }
4683
4684        String msg = null;
4685        try {
4686            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4687                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4688                        + scannedPkg.packageName);
4689                return PackageManager.SIGNATURE_MATCH;
4690            }
4691        } catch (CertificateException e) {
4692            msg = e.getMessage();
4693        }
4694
4695        logCriticalInfo(Log.INFO,
4696                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4697        return PackageManager.SIGNATURE_NO_MATCH;
4698    }
4699
4700    @Override
4701    public List<String> getAllPackages() {
4702        synchronized (mPackages) {
4703            return new ArrayList<String>(mPackages.keySet());
4704        }
4705    }
4706
4707    @Override
4708    public String[] getPackagesForUid(int uid) {
4709        uid = UserHandle.getAppId(uid);
4710        // reader
4711        synchronized (mPackages) {
4712            Object obj = mSettings.getUserIdLPr(uid);
4713            if (obj instanceof SharedUserSetting) {
4714                final SharedUserSetting sus = (SharedUserSetting) obj;
4715                final int N = sus.packages.size();
4716                final String[] res = new String[N];
4717                final Iterator<PackageSetting> it = sus.packages.iterator();
4718                int i = 0;
4719                while (it.hasNext()) {
4720                    res[i++] = it.next().name;
4721                }
4722                return res;
4723            } else if (obj instanceof PackageSetting) {
4724                final PackageSetting ps = (PackageSetting) obj;
4725                return new String[] { ps.name };
4726            }
4727        }
4728        return null;
4729    }
4730
4731    @Override
4732    public String getNameForUid(int uid) {
4733        // reader
4734        synchronized (mPackages) {
4735            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4736            if (obj instanceof SharedUserSetting) {
4737                final SharedUserSetting sus = (SharedUserSetting) obj;
4738                return sus.name + ":" + sus.userId;
4739            } else if (obj instanceof PackageSetting) {
4740                final PackageSetting ps = (PackageSetting) obj;
4741                return ps.name;
4742            }
4743        }
4744        return null;
4745    }
4746
4747    @Override
4748    public int getUidForSharedUser(String sharedUserName) {
4749        if(sharedUserName == null) {
4750            return -1;
4751        }
4752        // reader
4753        synchronized (mPackages) {
4754            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4755            if (suid == null) {
4756                return -1;
4757            }
4758            return suid.userId;
4759        }
4760    }
4761
4762    @Override
4763    public int getFlagsForUid(int uid) {
4764        synchronized (mPackages) {
4765            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4766            if (obj instanceof SharedUserSetting) {
4767                final SharedUserSetting sus = (SharedUserSetting) obj;
4768                return sus.pkgFlags;
4769            } else if (obj instanceof PackageSetting) {
4770                final PackageSetting ps = (PackageSetting) obj;
4771                return ps.pkgFlags;
4772            }
4773        }
4774        return 0;
4775    }
4776
4777    @Override
4778    public int getPrivateFlagsForUid(int uid) {
4779        synchronized (mPackages) {
4780            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4781            if (obj instanceof SharedUserSetting) {
4782                final SharedUserSetting sus = (SharedUserSetting) obj;
4783                return sus.pkgPrivateFlags;
4784            } else if (obj instanceof PackageSetting) {
4785                final PackageSetting ps = (PackageSetting) obj;
4786                return ps.pkgPrivateFlags;
4787            }
4788        }
4789        return 0;
4790    }
4791
4792    @Override
4793    public boolean isUidPrivileged(int uid) {
4794        uid = UserHandle.getAppId(uid);
4795        // reader
4796        synchronized (mPackages) {
4797            Object obj = mSettings.getUserIdLPr(uid);
4798            if (obj instanceof SharedUserSetting) {
4799                final SharedUserSetting sus = (SharedUserSetting) obj;
4800                final Iterator<PackageSetting> it = sus.packages.iterator();
4801                while (it.hasNext()) {
4802                    if (it.next().isPrivileged()) {
4803                        return true;
4804                    }
4805                }
4806            } else if (obj instanceof PackageSetting) {
4807                final PackageSetting ps = (PackageSetting) obj;
4808                return ps.isPrivileged();
4809            }
4810        }
4811        return false;
4812    }
4813
4814    @Override
4815    public String[] getAppOpPermissionPackages(String permissionName) {
4816        synchronized (mPackages) {
4817            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4818            if (pkgs == null) {
4819                return null;
4820            }
4821            return pkgs.toArray(new String[pkgs.size()]);
4822        }
4823    }
4824
4825    @Override
4826    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4827            int flags, int userId) {
4828        try {
4829            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4830
4831            if (!sUserManager.exists(userId)) return null;
4832            flags = updateFlagsForResolve(flags, userId, intent);
4833            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4834                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4835
4836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4837            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4838                    flags, userId);
4839            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4840
4841            final ResolveInfo bestChoice =
4842                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4843
4844            if (isEphemeralAllowed(intent, query, userId)) {
4845                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4846                final EphemeralResolveInfo ai =
4847                        getEphemeralResolveInfo(intent, resolvedType, userId);
4848                if (ai != null) {
4849                    if (DEBUG_EPHEMERAL) {
4850                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4851                    }
4852                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4853                    bestChoice.ephemeralResolveInfo = ai;
4854                }
4855                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4856            }
4857            return bestChoice;
4858        } finally {
4859            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4860        }
4861    }
4862
4863    @Override
4864    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4865            IntentFilter filter, int match, ComponentName activity) {
4866        final int userId = UserHandle.getCallingUserId();
4867        if (DEBUG_PREFERRED) {
4868            Log.v(TAG, "setLastChosenActivity intent=" + intent
4869                + " resolvedType=" + resolvedType
4870                + " flags=" + flags
4871                + " filter=" + filter
4872                + " match=" + match
4873                + " activity=" + activity);
4874            filter.dump(new PrintStreamPrinter(System.out), "    ");
4875        }
4876        intent.setComponent(null);
4877        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4878                userId);
4879        // Find any earlier preferred or last chosen entries and nuke them
4880        findPreferredActivity(intent, resolvedType,
4881                flags, query, 0, false, true, false, userId);
4882        // Add the new activity as the last chosen for this filter
4883        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4884                "Setting last chosen");
4885    }
4886
4887    @Override
4888    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4889        final int userId = UserHandle.getCallingUserId();
4890        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4891        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4892                userId);
4893        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4894                false, false, false, userId);
4895    }
4896
4897
4898    private boolean isEphemeralAllowed(
4899            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4900        // Short circuit and return early if possible.
4901        if (DISABLE_EPHEMERAL_APPS) {
4902            return false;
4903        }
4904        final int callingUser = UserHandle.getCallingUserId();
4905        if (callingUser != UserHandle.USER_SYSTEM) {
4906            return false;
4907        }
4908        if (mEphemeralResolverConnection == null) {
4909            return false;
4910        }
4911        if (intent.getComponent() != null) {
4912            return false;
4913        }
4914        if (intent.getPackage() != null) {
4915            return false;
4916        }
4917        final boolean isWebUri = hasWebURI(intent);
4918        if (!isWebUri) {
4919            return false;
4920        }
4921        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4922        synchronized (mPackages) {
4923            final int count = resolvedActivites.size();
4924            for (int n = 0; n < count; n++) {
4925                ResolveInfo info = resolvedActivites.get(n);
4926                String packageName = info.activityInfo.packageName;
4927                PackageSetting ps = mSettings.mPackages.get(packageName);
4928                if (ps != null) {
4929                    // Try to get the status from User settings first
4930                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4931                    int status = (int) (packedStatus >> 32);
4932                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4933                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4934                        if (DEBUG_EPHEMERAL) {
4935                            Slog.v(TAG, "DENY ephemeral apps;"
4936                                + " pkg: " + packageName + ", status: " + status);
4937                        }
4938                        return false;
4939                    }
4940                }
4941            }
4942        }
4943        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4944        return true;
4945    }
4946
4947    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4948            int userId) {
4949        MessageDigest digest = null;
4950        try {
4951            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4952        } catch (NoSuchAlgorithmException e) {
4953            // If we can't create a digest, ignore ephemeral apps.
4954            return null;
4955        }
4956
4957        final byte[] hostBytes = intent.getData().getHost().getBytes();
4958        final byte[] digestBytes = digest.digest(hostBytes);
4959        int shaPrefix =
4960                digestBytes[0] << 24
4961                | digestBytes[1] << 16
4962                | digestBytes[2] << 8
4963                | digestBytes[3] << 0;
4964        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4965                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4966        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4967            // No hash prefix match; there are no ephemeral apps for this domain.
4968            return null;
4969        }
4970        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4971            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4972            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4973                continue;
4974            }
4975            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4976            // No filters; this should never happen.
4977            if (filters.isEmpty()) {
4978                continue;
4979            }
4980            // We have a domain match; resolve the filters to see if anything matches.
4981            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4982            for (int j = filters.size() - 1; j >= 0; --j) {
4983                final EphemeralResolveIntentInfo intentInfo =
4984                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4985                ephemeralResolver.addFilter(intentInfo);
4986            }
4987            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4988                    intent, resolvedType, false /*defaultOnly*/, userId);
4989            if (!matchedResolveInfoList.isEmpty()) {
4990                return matchedResolveInfoList.get(0);
4991            }
4992        }
4993        // Hash or filter mis-match; no ephemeral apps for this domain.
4994        return null;
4995    }
4996
4997    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4998            int flags, List<ResolveInfo> query, int userId) {
4999        if (query != null) {
5000            final int N = query.size();
5001            if (N == 1) {
5002                return query.get(0);
5003            } else if (N > 1) {
5004                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5005                // If there is more than one activity with the same priority,
5006                // then let the user decide between them.
5007                ResolveInfo r0 = query.get(0);
5008                ResolveInfo r1 = query.get(1);
5009                if (DEBUG_INTENT_MATCHING || debug) {
5010                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5011                            + r1.activityInfo.name + "=" + r1.priority);
5012                }
5013                // If the first activity has a higher priority, or a different
5014                // default, then it is always desirable to pick it.
5015                if (r0.priority != r1.priority
5016                        || r0.preferredOrder != r1.preferredOrder
5017                        || r0.isDefault != r1.isDefault) {
5018                    return query.get(0);
5019                }
5020                // If we have saved a preference for a preferred activity for
5021                // this Intent, use that.
5022                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5023                        flags, query, r0.priority, true, false, debug, userId);
5024                if (ri != null) {
5025                    return ri;
5026                }
5027                ri = new ResolveInfo(mResolveInfo);
5028                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5029                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5030                // If all of the options come from the same package, show the application's
5031                // label and icon instead of the generic resolver's.
5032                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5033                // and then throw away the ResolveInfo itself, meaning that the caller loses
5034                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5035                // a fallback for this case; we only set the target package's resources on
5036                // the ResolveInfo, not the ActivityInfo.
5037                final String intentPackage = intent.getPackage();
5038                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5039                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5040                    ri.resolvePackageName = intentPackage;
5041                    if (userNeedsBadging(userId)) {
5042                        ri.noResourceId = true;
5043                    } else {
5044                        ri.icon = appi.icon;
5045                    }
5046                    ri.iconResourceId = appi.icon;
5047                    ri.labelRes = appi.labelRes;
5048                }
5049                ri.activityInfo.applicationInfo = new ApplicationInfo(
5050                        ri.activityInfo.applicationInfo);
5051                if (userId != 0) {
5052                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5053                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5054                }
5055                // Make sure that the resolver is displayable in car mode
5056                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5057                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5058                return ri;
5059            }
5060        }
5061        return null;
5062    }
5063
5064    /**
5065     * Return true if the given list is not empty and all of its contents have
5066     * an activityInfo with the given package name.
5067     */
5068    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5069        if (ArrayUtils.isEmpty(list)) {
5070            return false;
5071        }
5072        for (int i = 0, N = list.size(); i < N; i++) {
5073            final ResolveInfo ri = list.get(i);
5074            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5075            if (ai == null || !packageName.equals(ai.packageName)) {
5076                return false;
5077            }
5078        }
5079        return true;
5080    }
5081
5082    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5083            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5084        final int N = query.size();
5085        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5086                .get(userId);
5087        // Get the list of persistent preferred activities that handle the intent
5088        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5089        List<PersistentPreferredActivity> pprefs = ppir != null
5090                ? ppir.queryIntent(intent, resolvedType,
5091                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5092                : null;
5093        if (pprefs != null && pprefs.size() > 0) {
5094            final int M = pprefs.size();
5095            for (int i=0; i<M; i++) {
5096                final PersistentPreferredActivity ppa = pprefs.get(i);
5097                if (DEBUG_PREFERRED || debug) {
5098                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5099                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5100                            + "\n  component=" + ppa.mComponent);
5101                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5102                }
5103                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5104                        flags | MATCH_DISABLED_COMPONENTS, userId);
5105                if (DEBUG_PREFERRED || debug) {
5106                    Slog.v(TAG, "Found persistent preferred activity:");
5107                    if (ai != null) {
5108                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5109                    } else {
5110                        Slog.v(TAG, "  null");
5111                    }
5112                }
5113                if (ai == null) {
5114                    // This previously registered persistent preferred activity
5115                    // component is no longer known. Ignore it and do NOT remove it.
5116                    continue;
5117                }
5118                for (int j=0; j<N; j++) {
5119                    final ResolveInfo ri = query.get(j);
5120                    if (!ri.activityInfo.applicationInfo.packageName
5121                            .equals(ai.applicationInfo.packageName)) {
5122                        continue;
5123                    }
5124                    if (!ri.activityInfo.name.equals(ai.name)) {
5125                        continue;
5126                    }
5127                    //  Found a persistent preference that can handle the intent.
5128                    if (DEBUG_PREFERRED || debug) {
5129                        Slog.v(TAG, "Returning persistent preferred activity: " +
5130                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5131                    }
5132                    return ri;
5133                }
5134            }
5135        }
5136        return null;
5137    }
5138
5139    // TODO: handle preferred activities missing while user has amnesia
5140    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5141            List<ResolveInfo> query, int priority, boolean always,
5142            boolean removeMatches, boolean debug, int userId) {
5143        if (!sUserManager.exists(userId)) return null;
5144        flags = updateFlagsForResolve(flags, userId, intent);
5145        // writer
5146        synchronized (mPackages) {
5147            if (intent.getSelector() != null) {
5148                intent = intent.getSelector();
5149            }
5150            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5151
5152            // Try to find a matching persistent preferred activity.
5153            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5154                    debug, userId);
5155
5156            // If a persistent preferred activity matched, use it.
5157            if (pri != null) {
5158                return pri;
5159            }
5160
5161            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5162            // Get the list of preferred activities that handle the intent
5163            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5164            List<PreferredActivity> prefs = pir != null
5165                    ? pir.queryIntent(intent, resolvedType,
5166                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5167                    : null;
5168            if (prefs != null && prefs.size() > 0) {
5169                boolean changed = false;
5170                try {
5171                    // First figure out how good the original match set is.
5172                    // We will only allow preferred activities that came
5173                    // from the same match quality.
5174                    int match = 0;
5175
5176                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5177
5178                    final int N = query.size();
5179                    for (int j=0; j<N; j++) {
5180                        final ResolveInfo ri = query.get(j);
5181                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5182                                + ": 0x" + Integer.toHexString(match));
5183                        if (ri.match > match) {
5184                            match = ri.match;
5185                        }
5186                    }
5187
5188                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5189                            + Integer.toHexString(match));
5190
5191                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5192                    final int M = prefs.size();
5193                    for (int i=0; i<M; i++) {
5194                        final PreferredActivity pa = prefs.get(i);
5195                        if (DEBUG_PREFERRED || debug) {
5196                            Slog.v(TAG, "Checking PreferredActivity ds="
5197                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5198                                    + "\n  component=" + pa.mPref.mComponent);
5199                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5200                        }
5201                        if (pa.mPref.mMatch != match) {
5202                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5203                                    + Integer.toHexString(pa.mPref.mMatch));
5204                            continue;
5205                        }
5206                        // If it's not an "always" type preferred activity and that's what we're
5207                        // looking for, skip it.
5208                        if (always && !pa.mPref.mAlways) {
5209                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5210                            continue;
5211                        }
5212                        final ActivityInfo ai = getActivityInfo(
5213                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5214                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5215                                userId);
5216                        if (DEBUG_PREFERRED || debug) {
5217                            Slog.v(TAG, "Found preferred activity:");
5218                            if (ai != null) {
5219                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5220                            } else {
5221                                Slog.v(TAG, "  null");
5222                            }
5223                        }
5224                        if (ai == null) {
5225                            // This previously registered preferred activity
5226                            // component is no longer known.  Most likely an update
5227                            // to the app was installed and in the new version this
5228                            // component no longer exists.  Clean it up by removing
5229                            // it from the preferred activities list, and skip it.
5230                            Slog.w(TAG, "Removing dangling preferred activity: "
5231                                    + pa.mPref.mComponent);
5232                            pir.removeFilter(pa);
5233                            changed = true;
5234                            continue;
5235                        }
5236                        for (int j=0; j<N; j++) {
5237                            final ResolveInfo ri = query.get(j);
5238                            if (!ri.activityInfo.applicationInfo.packageName
5239                                    .equals(ai.applicationInfo.packageName)) {
5240                                continue;
5241                            }
5242                            if (!ri.activityInfo.name.equals(ai.name)) {
5243                                continue;
5244                            }
5245
5246                            if (removeMatches) {
5247                                pir.removeFilter(pa);
5248                                changed = true;
5249                                if (DEBUG_PREFERRED) {
5250                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5251                                }
5252                                break;
5253                            }
5254
5255                            // Okay we found a previously set preferred or last chosen app.
5256                            // If the result set is different from when this
5257                            // was created, we need to clear it and re-ask the
5258                            // user their preference, if we're looking for an "always" type entry.
5259                            if (always && !pa.mPref.sameSet(query)) {
5260                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5261                                        + intent + " type " + resolvedType);
5262                                if (DEBUG_PREFERRED) {
5263                                    Slog.v(TAG, "Removing preferred activity since set changed "
5264                                            + pa.mPref.mComponent);
5265                                }
5266                                pir.removeFilter(pa);
5267                                // Re-add the filter as a "last chosen" entry (!always)
5268                                PreferredActivity lastChosen = new PreferredActivity(
5269                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5270                                pir.addFilter(lastChosen);
5271                                changed = true;
5272                                return null;
5273                            }
5274
5275                            // Yay! Either the set matched or we're looking for the last chosen
5276                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5277                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5278                            return ri;
5279                        }
5280                    }
5281                } finally {
5282                    if (changed) {
5283                        if (DEBUG_PREFERRED) {
5284                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5285                        }
5286                        scheduleWritePackageRestrictionsLocked(userId);
5287                    }
5288                }
5289            }
5290        }
5291        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5292        return null;
5293    }
5294
5295    /*
5296     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5297     */
5298    @Override
5299    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5300            int targetUserId) {
5301        mContext.enforceCallingOrSelfPermission(
5302                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5303        List<CrossProfileIntentFilter> matches =
5304                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5305        if (matches != null) {
5306            int size = matches.size();
5307            for (int i = 0; i < size; i++) {
5308                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5309            }
5310        }
5311        if (hasWebURI(intent)) {
5312            // cross-profile app linking works only towards the parent.
5313            final UserInfo parent = getProfileParent(sourceUserId);
5314            synchronized(mPackages) {
5315                int flags = updateFlagsForResolve(0, parent.id, intent);
5316                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5317                        intent, resolvedType, flags, sourceUserId, parent.id);
5318                return xpDomainInfo != null;
5319            }
5320        }
5321        return false;
5322    }
5323
5324    private UserInfo getProfileParent(int userId) {
5325        final long identity = Binder.clearCallingIdentity();
5326        try {
5327            return sUserManager.getProfileParent(userId);
5328        } finally {
5329            Binder.restoreCallingIdentity(identity);
5330        }
5331    }
5332
5333    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5334            String resolvedType, int userId) {
5335        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5336        if (resolver != null) {
5337            return resolver.queryIntent(intent, resolvedType, false, userId);
5338        }
5339        return null;
5340    }
5341
5342    @Override
5343    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5344            String resolvedType, int flags, int userId) {
5345        try {
5346            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5347
5348            return new ParceledListSlice<>(
5349                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5350        } finally {
5351            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5352        }
5353    }
5354
5355    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5356            String resolvedType, int flags, int userId) {
5357        if (!sUserManager.exists(userId)) return Collections.emptyList();
5358        flags = updateFlagsForResolve(flags, userId, intent);
5359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5360                false /* requireFullPermission */, false /* checkShell */,
5361                "query intent activities");
5362        ComponentName comp = intent.getComponent();
5363        if (comp == null) {
5364            if (intent.getSelector() != null) {
5365                intent = intent.getSelector();
5366                comp = intent.getComponent();
5367            }
5368        }
5369
5370        if (comp != null) {
5371            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5372            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5373            if (ai != null) {
5374                final ResolveInfo ri = new ResolveInfo();
5375                ri.activityInfo = ai;
5376                list.add(ri);
5377            }
5378            return list;
5379        }
5380
5381        // reader
5382        synchronized (mPackages) {
5383            final String pkgName = intent.getPackage();
5384            if (pkgName == null) {
5385                List<CrossProfileIntentFilter> matchingFilters =
5386                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5387                // Check for results that need to skip the current profile.
5388                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5389                        resolvedType, flags, userId);
5390                if (xpResolveInfo != null) {
5391                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5392                    result.add(xpResolveInfo);
5393                    return filterIfNotSystemUser(result, userId);
5394                }
5395
5396                // Check for results in the current profile.
5397                List<ResolveInfo> result = mActivities.queryIntent(
5398                        intent, resolvedType, flags, userId);
5399                result = filterIfNotSystemUser(result, userId);
5400
5401                // Check for cross profile results.
5402                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5403                xpResolveInfo = queryCrossProfileIntents(
5404                        matchingFilters, intent, resolvedType, flags, userId,
5405                        hasNonNegativePriorityResult);
5406                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5407                    boolean isVisibleToUser = filterIfNotSystemUser(
5408                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5409                    if (isVisibleToUser) {
5410                        result.add(xpResolveInfo);
5411                        Collections.sort(result, mResolvePrioritySorter);
5412                    }
5413                }
5414                if (hasWebURI(intent)) {
5415                    CrossProfileDomainInfo xpDomainInfo = null;
5416                    final UserInfo parent = getProfileParent(userId);
5417                    if (parent != null) {
5418                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5419                                flags, userId, parent.id);
5420                    }
5421                    if (xpDomainInfo != null) {
5422                        if (xpResolveInfo != null) {
5423                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5424                            // in the result.
5425                            result.remove(xpResolveInfo);
5426                        }
5427                        if (result.size() == 0) {
5428                            result.add(xpDomainInfo.resolveInfo);
5429                            return result;
5430                        }
5431                    } else if (result.size() <= 1) {
5432                        return result;
5433                    }
5434                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5435                            xpDomainInfo, userId);
5436                    Collections.sort(result, mResolvePrioritySorter);
5437                }
5438                return result;
5439            }
5440            final PackageParser.Package pkg = mPackages.get(pkgName);
5441            if (pkg != null) {
5442                return filterIfNotSystemUser(
5443                        mActivities.queryIntentForPackage(
5444                                intent, resolvedType, flags, pkg.activities, userId),
5445                        userId);
5446            }
5447            return new ArrayList<ResolveInfo>();
5448        }
5449    }
5450
5451    private static class CrossProfileDomainInfo {
5452        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5453        ResolveInfo resolveInfo;
5454        /* Best domain verification status of the activities found in the other profile */
5455        int bestDomainVerificationStatus;
5456    }
5457
5458    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5459            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5460        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5461                sourceUserId)) {
5462            return null;
5463        }
5464        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5465                resolvedType, flags, parentUserId);
5466
5467        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5468            return null;
5469        }
5470        CrossProfileDomainInfo result = null;
5471        int size = resultTargetUser.size();
5472        for (int i = 0; i < size; i++) {
5473            ResolveInfo riTargetUser = resultTargetUser.get(i);
5474            // Intent filter verification is only for filters that specify a host. So don't return
5475            // those that handle all web uris.
5476            if (riTargetUser.handleAllWebDataURI) {
5477                continue;
5478            }
5479            String packageName = riTargetUser.activityInfo.packageName;
5480            PackageSetting ps = mSettings.mPackages.get(packageName);
5481            if (ps == null) {
5482                continue;
5483            }
5484            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5485            int status = (int)(verificationState >> 32);
5486            if (result == null) {
5487                result = new CrossProfileDomainInfo();
5488                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5489                        sourceUserId, parentUserId);
5490                result.bestDomainVerificationStatus = status;
5491            } else {
5492                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5493                        result.bestDomainVerificationStatus);
5494            }
5495        }
5496        // Don't consider matches with status NEVER across profiles.
5497        if (result != null && result.bestDomainVerificationStatus
5498                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5499            return null;
5500        }
5501        return result;
5502    }
5503
5504    /**
5505     * Verification statuses are ordered from the worse to the best, except for
5506     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5507     */
5508    private int bestDomainVerificationStatus(int status1, int status2) {
5509        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5510            return status2;
5511        }
5512        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5513            return status1;
5514        }
5515        return (int) MathUtils.max(status1, status2);
5516    }
5517
5518    private boolean isUserEnabled(int userId) {
5519        long callingId = Binder.clearCallingIdentity();
5520        try {
5521            UserInfo userInfo = sUserManager.getUserInfo(userId);
5522            return userInfo != null && userInfo.isEnabled();
5523        } finally {
5524            Binder.restoreCallingIdentity(callingId);
5525        }
5526    }
5527
5528    /**
5529     * Filter out activities with systemUserOnly flag set, when current user is not System.
5530     *
5531     * @return filtered list
5532     */
5533    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5534        if (userId == UserHandle.USER_SYSTEM) {
5535            return resolveInfos;
5536        }
5537        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5538            ResolveInfo info = resolveInfos.get(i);
5539            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5540                resolveInfos.remove(i);
5541            }
5542        }
5543        return resolveInfos;
5544    }
5545
5546    /**
5547     * @param resolveInfos list of resolve infos in descending priority order
5548     * @return if the list contains a resolve info with non-negative priority
5549     */
5550    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5551        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5552    }
5553
5554    private static boolean hasWebURI(Intent intent) {
5555        if (intent.getData() == null) {
5556            return false;
5557        }
5558        final String scheme = intent.getScheme();
5559        if (TextUtils.isEmpty(scheme)) {
5560            return false;
5561        }
5562        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5563    }
5564
5565    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5566            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5567            int userId) {
5568        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5569
5570        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5571            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5572                    candidates.size());
5573        }
5574
5575        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5576        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5577        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5578        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5579        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5580        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5581
5582        synchronized (mPackages) {
5583            final int count = candidates.size();
5584            // First, try to use linked apps. Partition the candidates into four lists:
5585            // one for the final results, one for the "do not use ever", one for "undefined status"
5586            // and finally one for "browser app type".
5587            for (int n=0; n<count; n++) {
5588                ResolveInfo info = candidates.get(n);
5589                String packageName = info.activityInfo.packageName;
5590                PackageSetting ps = mSettings.mPackages.get(packageName);
5591                if (ps != null) {
5592                    // Add to the special match all list (Browser use case)
5593                    if (info.handleAllWebDataURI) {
5594                        matchAllList.add(info);
5595                        continue;
5596                    }
5597                    // Try to get the status from User settings first
5598                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5599                    int status = (int)(packedStatus >> 32);
5600                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5601                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5602                        if (DEBUG_DOMAIN_VERIFICATION) {
5603                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5604                                    + " : linkgen=" + linkGeneration);
5605                        }
5606                        // Use link-enabled generation as preferredOrder, i.e.
5607                        // prefer newly-enabled over earlier-enabled.
5608                        info.preferredOrder = linkGeneration;
5609                        alwaysList.add(info);
5610                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5611                        if (DEBUG_DOMAIN_VERIFICATION) {
5612                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5613                        }
5614                        neverList.add(info);
5615                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5616                        if (DEBUG_DOMAIN_VERIFICATION) {
5617                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5618                        }
5619                        alwaysAskList.add(info);
5620                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5621                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5622                        if (DEBUG_DOMAIN_VERIFICATION) {
5623                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5624                        }
5625                        undefinedList.add(info);
5626                    }
5627                }
5628            }
5629
5630            // We'll want to include browser possibilities in a few cases
5631            boolean includeBrowser = false;
5632
5633            // First try to add the "always" resolution(s) for the current user, if any
5634            if (alwaysList.size() > 0) {
5635                result.addAll(alwaysList);
5636            } else {
5637                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5638                result.addAll(undefinedList);
5639                // Maybe add one for the other profile.
5640                if (xpDomainInfo != null && (
5641                        xpDomainInfo.bestDomainVerificationStatus
5642                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5643                    result.add(xpDomainInfo.resolveInfo);
5644                }
5645                includeBrowser = true;
5646            }
5647
5648            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5649            // If there were 'always' entries their preferred order has been set, so we also
5650            // back that off to make the alternatives equivalent
5651            if (alwaysAskList.size() > 0) {
5652                for (ResolveInfo i : result) {
5653                    i.preferredOrder = 0;
5654                }
5655                result.addAll(alwaysAskList);
5656                includeBrowser = true;
5657            }
5658
5659            if (includeBrowser) {
5660                // Also add browsers (all of them or only the default one)
5661                if (DEBUG_DOMAIN_VERIFICATION) {
5662                    Slog.v(TAG, "   ...including browsers in candidate set");
5663                }
5664                if ((matchFlags & MATCH_ALL) != 0) {
5665                    result.addAll(matchAllList);
5666                } else {
5667                    // Browser/generic handling case.  If there's a default browser, go straight
5668                    // to that (but only if there is no other higher-priority match).
5669                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5670                    int maxMatchPrio = 0;
5671                    ResolveInfo defaultBrowserMatch = null;
5672                    final int numCandidates = matchAllList.size();
5673                    for (int n = 0; n < numCandidates; n++) {
5674                        ResolveInfo info = matchAllList.get(n);
5675                        // track the highest overall match priority...
5676                        if (info.priority > maxMatchPrio) {
5677                            maxMatchPrio = info.priority;
5678                        }
5679                        // ...and the highest-priority default browser match
5680                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5681                            if (defaultBrowserMatch == null
5682                                    || (defaultBrowserMatch.priority < info.priority)) {
5683                                if (debug) {
5684                                    Slog.v(TAG, "Considering default browser match " + info);
5685                                }
5686                                defaultBrowserMatch = info;
5687                            }
5688                        }
5689                    }
5690                    if (defaultBrowserMatch != null
5691                            && defaultBrowserMatch.priority >= maxMatchPrio
5692                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5693                    {
5694                        if (debug) {
5695                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5696                        }
5697                        result.add(defaultBrowserMatch);
5698                    } else {
5699                        result.addAll(matchAllList);
5700                    }
5701                }
5702
5703                // If there is nothing selected, add all candidates and remove the ones that the user
5704                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5705                if (result.size() == 0) {
5706                    result.addAll(candidates);
5707                    result.removeAll(neverList);
5708                }
5709            }
5710        }
5711        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5712            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5713                    result.size());
5714            for (ResolveInfo info : result) {
5715                Slog.v(TAG, "  + " + info.activityInfo);
5716            }
5717        }
5718        return result;
5719    }
5720
5721    // Returns a packed value as a long:
5722    //
5723    // high 'int'-sized word: link status: undefined/ask/never/always.
5724    // low 'int'-sized word: relative priority among 'always' results.
5725    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5726        long result = ps.getDomainVerificationStatusForUser(userId);
5727        // if none available, get the master status
5728        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5729            if (ps.getIntentFilterVerificationInfo() != null) {
5730                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5731            }
5732        }
5733        return result;
5734    }
5735
5736    private ResolveInfo querySkipCurrentProfileIntents(
5737            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5738            int flags, int sourceUserId) {
5739        if (matchingFilters != null) {
5740            int size = matchingFilters.size();
5741            for (int i = 0; i < size; i ++) {
5742                CrossProfileIntentFilter filter = matchingFilters.get(i);
5743                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5744                    // Checking if there are activities in the target user that can handle the
5745                    // intent.
5746                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5747                            resolvedType, flags, sourceUserId);
5748                    if (resolveInfo != null) {
5749                        return resolveInfo;
5750                    }
5751                }
5752            }
5753        }
5754        return null;
5755    }
5756
5757    // Return matching ResolveInfo in target user if any.
5758    private ResolveInfo queryCrossProfileIntents(
5759            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5760            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5761        if (matchingFilters != null) {
5762            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5763            // match the same intent. For performance reasons, it is better not to
5764            // run queryIntent twice for the same userId
5765            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5766            int size = matchingFilters.size();
5767            for (int i = 0; i < size; i++) {
5768                CrossProfileIntentFilter filter = matchingFilters.get(i);
5769                int targetUserId = filter.getTargetUserId();
5770                boolean skipCurrentProfile =
5771                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5772                boolean skipCurrentProfileIfNoMatchFound =
5773                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5774                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5775                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5776                    // Checking if there are activities in the target user that can handle the
5777                    // intent.
5778                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5779                            resolvedType, flags, sourceUserId);
5780                    if (resolveInfo != null) return resolveInfo;
5781                    alreadyTriedUserIds.put(targetUserId, true);
5782                }
5783            }
5784        }
5785        return null;
5786    }
5787
5788    /**
5789     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5790     * will forward the intent to the filter's target user.
5791     * Otherwise, returns null.
5792     */
5793    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5794            String resolvedType, int flags, int sourceUserId) {
5795        int targetUserId = filter.getTargetUserId();
5796        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5797                resolvedType, flags, targetUserId);
5798        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5799            // If all the matches in the target profile are suspended, return null.
5800            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5801                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5802                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5803                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5804                            targetUserId);
5805                }
5806            }
5807        }
5808        return null;
5809    }
5810
5811    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5812            int sourceUserId, int targetUserId) {
5813        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5814        long ident = Binder.clearCallingIdentity();
5815        boolean targetIsProfile;
5816        try {
5817            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5818        } finally {
5819            Binder.restoreCallingIdentity(ident);
5820        }
5821        String className;
5822        if (targetIsProfile) {
5823            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5824        } else {
5825            className = FORWARD_INTENT_TO_PARENT;
5826        }
5827        ComponentName forwardingActivityComponentName = new ComponentName(
5828                mAndroidApplication.packageName, className);
5829        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5830                sourceUserId);
5831        if (!targetIsProfile) {
5832            forwardingActivityInfo.showUserIcon = targetUserId;
5833            forwardingResolveInfo.noResourceId = true;
5834        }
5835        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5836        forwardingResolveInfo.priority = 0;
5837        forwardingResolveInfo.preferredOrder = 0;
5838        forwardingResolveInfo.match = 0;
5839        forwardingResolveInfo.isDefault = true;
5840        forwardingResolveInfo.filter = filter;
5841        forwardingResolveInfo.targetUserId = targetUserId;
5842        return forwardingResolveInfo;
5843    }
5844
5845    @Override
5846    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5847            Intent[] specifics, String[] specificTypes, Intent intent,
5848            String resolvedType, int flags, int userId) {
5849        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5850                specificTypes, intent, resolvedType, flags, userId));
5851    }
5852
5853    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5854            Intent[] specifics, String[] specificTypes, Intent intent,
5855            String resolvedType, int flags, int userId) {
5856        if (!sUserManager.exists(userId)) return Collections.emptyList();
5857        flags = updateFlagsForResolve(flags, userId, intent);
5858        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5859                false /* requireFullPermission */, false /* checkShell */,
5860                "query intent activity options");
5861        final String resultsAction = intent.getAction();
5862
5863        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5864                | PackageManager.GET_RESOLVED_FILTER, userId);
5865
5866        if (DEBUG_INTENT_MATCHING) {
5867            Log.v(TAG, "Query " + intent + ": " + results);
5868        }
5869
5870        int specificsPos = 0;
5871        int N;
5872
5873        // todo: note that the algorithm used here is O(N^2).  This
5874        // isn't a problem in our current environment, but if we start running
5875        // into situations where we have more than 5 or 10 matches then this
5876        // should probably be changed to something smarter...
5877
5878        // First we go through and resolve each of the specific items
5879        // that were supplied, taking care of removing any corresponding
5880        // duplicate items in the generic resolve list.
5881        if (specifics != null) {
5882            for (int i=0; i<specifics.length; i++) {
5883                final Intent sintent = specifics[i];
5884                if (sintent == null) {
5885                    continue;
5886                }
5887
5888                if (DEBUG_INTENT_MATCHING) {
5889                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5890                }
5891
5892                String action = sintent.getAction();
5893                if (resultsAction != null && resultsAction.equals(action)) {
5894                    // If this action was explicitly requested, then don't
5895                    // remove things that have it.
5896                    action = null;
5897                }
5898
5899                ResolveInfo ri = null;
5900                ActivityInfo ai = null;
5901
5902                ComponentName comp = sintent.getComponent();
5903                if (comp == null) {
5904                    ri = resolveIntent(
5905                        sintent,
5906                        specificTypes != null ? specificTypes[i] : null,
5907                            flags, userId);
5908                    if (ri == null) {
5909                        continue;
5910                    }
5911                    if (ri == mResolveInfo) {
5912                        // ACK!  Must do something better with this.
5913                    }
5914                    ai = ri.activityInfo;
5915                    comp = new ComponentName(ai.applicationInfo.packageName,
5916                            ai.name);
5917                } else {
5918                    ai = getActivityInfo(comp, flags, userId);
5919                    if (ai == null) {
5920                        continue;
5921                    }
5922                }
5923
5924                // Look for any generic query activities that are duplicates
5925                // of this specific one, and remove them from the results.
5926                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5927                N = results.size();
5928                int j;
5929                for (j=specificsPos; j<N; j++) {
5930                    ResolveInfo sri = results.get(j);
5931                    if ((sri.activityInfo.name.equals(comp.getClassName())
5932                            && sri.activityInfo.applicationInfo.packageName.equals(
5933                                    comp.getPackageName()))
5934                        || (action != null && sri.filter.matchAction(action))) {
5935                        results.remove(j);
5936                        if (DEBUG_INTENT_MATCHING) Log.v(
5937                            TAG, "Removing duplicate item from " + j
5938                            + " due to specific " + specificsPos);
5939                        if (ri == null) {
5940                            ri = sri;
5941                        }
5942                        j--;
5943                        N--;
5944                    }
5945                }
5946
5947                // Add this specific item to its proper place.
5948                if (ri == null) {
5949                    ri = new ResolveInfo();
5950                    ri.activityInfo = ai;
5951                }
5952                results.add(specificsPos, ri);
5953                ri.specificIndex = i;
5954                specificsPos++;
5955            }
5956        }
5957
5958        // Now we go through the remaining generic results and remove any
5959        // duplicate actions that are found here.
5960        N = results.size();
5961        for (int i=specificsPos; i<N-1; i++) {
5962            final ResolveInfo rii = results.get(i);
5963            if (rii.filter == null) {
5964                continue;
5965            }
5966
5967            // Iterate over all of the actions of this result's intent
5968            // filter...  typically this should be just one.
5969            final Iterator<String> it = rii.filter.actionsIterator();
5970            if (it == null) {
5971                continue;
5972            }
5973            while (it.hasNext()) {
5974                final String action = it.next();
5975                if (resultsAction != null && resultsAction.equals(action)) {
5976                    // If this action was explicitly requested, then don't
5977                    // remove things that have it.
5978                    continue;
5979                }
5980                for (int j=i+1; j<N; j++) {
5981                    final ResolveInfo rij = results.get(j);
5982                    if (rij.filter != null && rij.filter.hasAction(action)) {
5983                        results.remove(j);
5984                        if (DEBUG_INTENT_MATCHING) Log.v(
5985                            TAG, "Removing duplicate item from " + j
5986                            + " due to action " + action + " at " + i);
5987                        j--;
5988                        N--;
5989                    }
5990                }
5991            }
5992
5993            // If the caller didn't request filter information, drop it now
5994            // so we don't have to marshall/unmarshall it.
5995            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5996                rii.filter = null;
5997            }
5998        }
5999
6000        // Filter out the caller activity if so requested.
6001        if (caller != null) {
6002            N = results.size();
6003            for (int i=0; i<N; i++) {
6004                ActivityInfo ainfo = results.get(i).activityInfo;
6005                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6006                        && caller.getClassName().equals(ainfo.name)) {
6007                    results.remove(i);
6008                    break;
6009                }
6010            }
6011        }
6012
6013        // If the caller didn't request filter information,
6014        // drop them now so we don't have to
6015        // marshall/unmarshall it.
6016        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6017            N = results.size();
6018            for (int i=0; i<N; i++) {
6019                results.get(i).filter = null;
6020            }
6021        }
6022
6023        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6024        return results;
6025    }
6026
6027    @Override
6028    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6029            String resolvedType, int flags, int userId) {
6030        return new ParceledListSlice<>(
6031                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6032    }
6033
6034    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6035            String resolvedType, int flags, int userId) {
6036        if (!sUserManager.exists(userId)) return Collections.emptyList();
6037        flags = updateFlagsForResolve(flags, userId, intent);
6038        ComponentName comp = intent.getComponent();
6039        if (comp == null) {
6040            if (intent.getSelector() != null) {
6041                intent = intent.getSelector();
6042                comp = intent.getComponent();
6043            }
6044        }
6045        if (comp != null) {
6046            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6047            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6048            if (ai != null) {
6049                ResolveInfo ri = new ResolveInfo();
6050                ri.activityInfo = ai;
6051                list.add(ri);
6052            }
6053            return list;
6054        }
6055
6056        // reader
6057        synchronized (mPackages) {
6058            String pkgName = intent.getPackage();
6059            if (pkgName == null) {
6060                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6061            }
6062            final PackageParser.Package pkg = mPackages.get(pkgName);
6063            if (pkg != null) {
6064                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6065                        userId);
6066            }
6067            return Collections.emptyList();
6068        }
6069    }
6070
6071    @Override
6072    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6073        if (!sUserManager.exists(userId)) return null;
6074        flags = updateFlagsForResolve(flags, userId, intent);
6075        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6076        if (query != null) {
6077            if (query.size() >= 1) {
6078                // If there is more than one service with the same priority,
6079                // just arbitrarily pick the first one.
6080                return query.get(0);
6081            }
6082        }
6083        return null;
6084    }
6085
6086    @Override
6087    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6088            String resolvedType, int flags, int userId) {
6089        return new ParceledListSlice<>(
6090                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6091    }
6092
6093    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6094            String resolvedType, int flags, int userId) {
6095        if (!sUserManager.exists(userId)) return Collections.emptyList();
6096        flags = updateFlagsForResolve(flags, userId, intent);
6097        ComponentName comp = intent.getComponent();
6098        if (comp == null) {
6099            if (intent.getSelector() != null) {
6100                intent = intent.getSelector();
6101                comp = intent.getComponent();
6102            }
6103        }
6104        if (comp != null) {
6105            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6106            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6107            if (si != null) {
6108                final ResolveInfo ri = new ResolveInfo();
6109                ri.serviceInfo = si;
6110                list.add(ri);
6111            }
6112            return list;
6113        }
6114
6115        // reader
6116        synchronized (mPackages) {
6117            String pkgName = intent.getPackage();
6118            if (pkgName == null) {
6119                return mServices.queryIntent(intent, resolvedType, flags, userId);
6120            }
6121            final PackageParser.Package pkg = mPackages.get(pkgName);
6122            if (pkg != null) {
6123                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6124                        userId);
6125            }
6126            return Collections.emptyList();
6127        }
6128    }
6129
6130    @Override
6131    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6132            String resolvedType, int flags, int userId) {
6133        return new ParceledListSlice<>(
6134                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6135    }
6136
6137    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6138            Intent intent, String resolvedType, int flags, int userId) {
6139        if (!sUserManager.exists(userId)) return Collections.emptyList();
6140        flags = updateFlagsForResolve(flags, userId, intent);
6141        ComponentName comp = intent.getComponent();
6142        if (comp == null) {
6143            if (intent.getSelector() != null) {
6144                intent = intent.getSelector();
6145                comp = intent.getComponent();
6146            }
6147        }
6148        if (comp != null) {
6149            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6150            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6151            if (pi != null) {
6152                final ResolveInfo ri = new ResolveInfo();
6153                ri.providerInfo = pi;
6154                list.add(ri);
6155            }
6156            return list;
6157        }
6158
6159        // reader
6160        synchronized (mPackages) {
6161            String pkgName = intent.getPackage();
6162            if (pkgName == null) {
6163                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6164            }
6165            final PackageParser.Package pkg = mPackages.get(pkgName);
6166            if (pkg != null) {
6167                return mProviders.queryIntentForPackage(
6168                        intent, resolvedType, flags, pkg.providers, userId);
6169            }
6170            return Collections.emptyList();
6171        }
6172    }
6173
6174    @Override
6175    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6176        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6177        flags = updateFlagsForPackage(flags, userId, null);
6178        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6179        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6180                true /* requireFullPermission */, false /* checkShell */,
6181                "get installed packages");
6182
6183        // writer
6184        synchronized (mPackages) {
6185            ArrayList<PackageInfo> list;
6186            if (listUninstalled) {
6187                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6188                for (PackageSetting ps : mSettings.mPackages.values()) {
6189                    final PackageInfo pi;
6190                    if (ps.pkg != null) {
6191                        pi = generatePackageInfo(ps, flags, userId);
6192                    } else {
6193                        pi = generatePackageInfo(ps, flags, userId);
6194                    }
6195                    if (pi != null) {
6196                        list.add(pi);
6197                    }
6198                }
6199            } else {
6200                list = new ArrayList<PackageInfo>(mPackages.size());
6201                for (PackageParser.Package p : mPackages.values()) {
6202                    final PackageInfo pi =
6203                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6204                    if (pi != null) {
6205                        list.add(pi);
6206                    }
6207                }
6208            }
6209
6210            return new ParceledListSlice<PackageInfo>(list);
6211        }
6212    }
6213
6214    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6215            String[] permissions, boolean[] tmp, int flags, int userId) {
6216        int numMatch = 0;
6217        final PermissionsState permissionsState = ps.getPermissionsState();
6218        for (int i=0; i<permissions.length; i++) {
6219            final String permission = permissions[i];
6220            if (permissionsState.hasPermission(permission, userId)) {
6221                tmp[i] = true;
6222                numMatch++;
6223            } else {
6224                tmp[i] = false;
6225            }
6226        }
6227        if (numMatch == 0) {
6228            return;
6229        }
6230        final PackageInfo pi;
6231        if (ps.pkg != null) {
6232            pi = generatePackageInfo(ps, flags, userId);
6233        } else {
6234            pi = generatePackageInfo(ps, flags, userId);
6235        }
6236        // The above might return null in cases of uninstalled apps or install-state
6237        // skew across users/profiles.
6238        if (pi != null) {
6239            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6240                if (numMatch == permissions.length) {
6241                    pi.requestedPermissions = permissions;
6242                } else {
6243                    pi.requestedPermissions = new String[numMatch];
6244                    numMatch = 0;
6245                    for (int i=0; i<permissions.length; i++) {
6246                        if (tmp[i]) {
6247                            pi.requestedPermissions[numMatch] = permissions[i];
6248                            numMatch++;
6249                        }
6250                    }
6251                }
6252            }
6253            list.add(pi);
6254        }
6255    }
6256
6257    @Override
6258    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6259            String[] permissions, int flags, int userId) {
6260        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6261        flags = updateFlagsForPackage(flags, userId, permissions);
6262        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6263
6264        // writer
6265        synchronized (mPackages) {
6266            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6267            boolean[] tmpBools = new boolean[permissions.length];
6268            if (listUninstalled) {
6269                for (PackageSetting ps : mSettings.mPackages.values()) {
6270                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6271                }
6272            } else {
6273                for (PackageParser.Package pkg : mPackages.values()) {
6274                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6275                    if (ps != null) {
6276                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6277                                userId);
6278                    }
6279                }
6280            }
6281
6282            return new ParceledListSlice<PackageInfo>(list);
6283        }
6284    }
6285
6286    @Override
6287    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6288        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6289        flags = updateFlagsForApplication(flags, userId, null);
6290        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6291
6292        // writer
6293        synchronized (mPackages) {
6294            ArrayList<ApplicationInfo> list;
6295            if (listUninstalled) {
6296                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6297                for (PackageSetting ps : mSettings.mPackages.values()) {
6298                    ApplicationInfo ai;
6299                    if (ps.pkg != null) {
6300                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6301                                ps.readUserState(userId), userId);
6302                    } else {
6303                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6304                    }
6305                    if (ai != null) {
6306                        list.add(ai);
6307                    }
6308                }
6309            } else {
6310                list = new ArrayList<ApplicationInfo>(mPackages.size());
6311                for (PackageParser.Package p : mPackages.values()) {
6312                    if (p.mExtras != null) {
6313                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6314                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6315                        if (ai != null) {
6316                            list.add(ai);
6317                        }
6318                    }
6319                }
6320            }
6321
6322            return new ParceledListSlice<ApplicationInfo>(list);
6323        }
6324    }
6325
6326    @Override
6327    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6328        if (DISABLE_EPHEMERAL_APPS) {
6329            return null;
6330        }
6331
6332        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6333                "getEphemeralApplications");
6334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6335                true /* requireFullPermission */, false /* checkShell */,
6336                "getEphemeralApplications");
6337        synchronized (mPackages) {
6338            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6339                    .getEphemeralApplicationsLPw(userId);
6340            if (ephemeralApps != null) {
6341                return new ParceledListSlice<>(ephemeralApps);
6342            }
6343        }
6344        return null;
6345    }
6346
6347    @Override
6348    public boolean isEphemeralApplication(String packageName, int userId) {
6349        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6350                true /* requireFullPermission */, false /* checkShell */,
6351                "isEphemeral");
6352        if (DISABLE_EPHEMERAL_APPS) {
6353            return false;
6354        }
6355
6356        if (!isCallerSameApp(packageName)) {
6357            return false;
6358        }
6359        synchronized (mPackages) {
6360            PackageParser.Package pkg = mPackages.get(packageName);
6361            if (pkg != null) {
6362                return pkg.applicationInfo.isEphemeralApp();
6363            }
6364        }
6365        return false;
6366    }
6367
6368    @Override
6369    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6370        if (DISABLE_EPHEMERAL_APPS) {
6371            return null;
6372        }
6373
6374        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6375                true /* requireFullPermission */, false /* checkShell */,
6376                "getCookie");
6377        if (!isCallerSameApp(packageName)) {
6378            return null;
6379        }
6380        synchronized (mPackages) {
6381            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6382                    packageName, userId);
6383        }
6384    }
6385
6386    @Override
6387    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6388        if (DISABLE_EPHEMERAL_APPS) {
6389            return true;
6390        }
6391
6392        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6393                true /* requireFullPermission */, true /* checkShell */,
6394                "setCookie");
6395        if (!isCallerSameApp(packageName)) {
6396            return false;
6397        }
6398        synchronized (mPackages) {
6399            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6400                    packageName, cookie, userId);
6401        }
6402    }
6403
6404    @Override
6405    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6406        if (DISABLE_EPHEMERAL_APPS) {
6407            return null;
6408        }
6409
6410        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6411                "getEphemeralApplicationIcon");
6412        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6413                true /* requireFullPermission */, false /* checkShell */,
6414                "getEphemeralApplicationIcon");
6415        synchronized (mPackages) {
6416            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6417                    packageName, userId);
6418        }
6419    }
6420
6421    private boolean isCallerSameApp(String packageName) {
6422        PackageParser.Package pkg = mPackages.get(packageName);
6423        return pkg != null
6424                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6425    }
6426
6427    @Override
6428    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6429        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6430    }
6431
6432    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6433        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6434
6435        // reader
6436        synchronized (mPackages) {
6437            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6438            final int userId = UserHandle.getCallingUserId();
6439            while (i.hasNext()) {
6440                final PackageParser.Package p = i.next();
6441                if (p.applicationInfo == null) continue;
6442
6443                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6444                        && !p.applicationInfo.isDirectBootAware();
6445                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6446                        && p.applicationInfo.isDirectBootAware();
6447
6448                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6449                        && (!mSafeMode || isSystemApp(p))
6450                        && (matchesUnaware || matchesAware)) {
6451                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6452                    if (ps != null) {
6453                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6454                                ps.readUserState(userId), userId);
6455                        if (ai != null) {
6456                            finalList.add(ai);
6457                        }
6458                    }
6459                }
6460            }
6461        }
6462
6463        return finalList;
6464    }
6465
6466    @Override
6467    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6468        if (!sUserManager.exists(userId)) return null;
6469        flags = updateFlagsForComponent(flags, userId, name);
6470        // reader
6471        synchronized (mPackages) {
6472            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6473            PackageSetting ps = provider != null
6474                    ? mSettings.mPackages.get(provider.owner.packageName)
6475                    : null;
6476            return ps != null
6477                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6478                    ? PackageParser.generateProviderInfo(provider, flags,
6479                            ps.readUserState(userId), userId)
6480                    : null;
6481        }
6482    }
6483
6484    /**
6485     * @deprecated
6486     */
6487    @Deprecated
6488    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6489        // reader
6490        synchronized (mPackages) {
6491            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6492                    .entrySet().iterator();
6493            final int userId = UserHandle.getCallingUserId();
6494            while (i.hasNext()) {
6495                Map.Entry<String, PackageParser.Provider> entry = i.next();
6496                PackageParser.Provider p = entry.getValue();
6497                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6498
6499                if (ps != null && p.syncable
6500                        && (!mSafeMode || (p.info.applicationInfo.flags
6501                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6502                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6503                            ps.readUserState(userId), userId);
6504                    if (info != null) {
6505                        outNames.add(entry.getKey());
6506                        outInfo.add(info);
6507                    }
6508                }
6509            }
6510        }
6511    }
6512
6513    @Override
6514    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6515            int uid, int flags) {
6516        final int userId = processName != null ? UserHandle.getUserId(uid)
6517                : UserHandle.getCallingUserId();
6518        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6519        flags = updateFlagsForComponent(flags, userId, processName);
6520
6521        ArrayList<ProviderInfo> finalList = null;
6522        // reader
6523        synchronized (mPackages) {
6524            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6525            while (i.hasNext()) {
6526                final PackageParser.Provider p = i.next();
6527                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6528                if (ps != null && p.info.authority != null
6529                        && (processName == null
6530                                || (p.info.processName.equals(processName)
6531                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6532                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6533                    if (finalList == null) {
6534                        finalList = new ArrayList<ProviderInfo>(3);
6535                    }
6536                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6537                            ps.readUserState(userId), userId);
6538                    if (info != null) {
6539                        finalList.add(info);
6540                    }
6541                }
6542            }
6543        }
6544
6545        if (finalList != null) {
6546            Collections.sort(finalList, mProviderInitOrderSorter);
6547            return new ParceledListSlice<ProviderInfo>(finalList);
6548        }
6549
6550        return ParceledListSlice.emptyList();
6551    }
6552
6553    @Override
6554    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6555        // reader
6556        synchronized (mPackages) {
6557            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6558            return PackageParser.generateInstrumentationInfo(i, flags);
6559        }
6560    }
6561
6562    @Override
6563    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6564            String targetPackage, int flags) {
6565        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6566    }
6567
6568    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6569            int flags) {
6570        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6571
6572        // reader
6573        synchronized (mPackages) {
6574            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6575            while (i.hasNext()) {
6576                final PackageParser.Instrumentation p = i.next();
6577                if (targetPackage == null
6578                        || targetPackage.equals(p.info.targetPackage)) {
6579                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6580                            flags);
6581                    if (ii != null) {
6582                        finalList.add(ii);
6583                    }
6584                }
6585            }
6586        }
6587
6588        return finalList;
6589    }
6590
6591    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6592        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6593        if (overlays == null) {
6594            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6595            return;
6596        }
6597        for (PackageParser.Package opkg : overlays.values()) {
6598            // Not much to do if idmap fails: we already logged the error
6599            // and we certainly don't want to abort installation of pkg simply
6600            // because an overlay didn't fit properly. For these reasons,
6601            // ignore the return value of createIdmapForPackagePairLI.
6602            createIdmapForPackagePairLI(pkg, opkg);
6603        }
6604    }
6605
6606    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6607            PackageParser.Package opkg) {
6608        if (!opkg.mTrustedOverlay) {
6609            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6610                    opkg.baseCodePath + ": overlay not trusted");
6611            return false;
6612        }
6613        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6614        if (overlaySet == null) {
6615            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6616                    opkg.baseCodePath + " but target package has no known overlays");
6617            return false;
6618        }
6619        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6620        // TODO: generate idmap for split APKs
6621        try {
6622            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6623        } catch (InstallerException e) {
6624            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6625                    + opkg.baseCodePath);
6626            return false;
6627        }
6628        PackageParser.Package[] overlayArray =
6629            overlaySet.values().toArray(new PackageParser.Package[0]);
6630        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6631            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6632                return p1.mOverlayPriority - p2.mOverlayPriority;
6633            }
6634        };
6635        Arrays.sort(overlayArray, cmp);
6636
6637        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6638        int i = 0;
6639        for (PackageParser.Package p : overlayArray) {
6640            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6641        }
6642        return true;
6643    }
6644
6645    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6646        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6647        try {
6648            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6649        } finally {
6650            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6651        }
6652    }
6653
6654    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6655        final File[] files = dir.listFiles();
6656        if (ArrayUtils.isEmpty(files)) {
6657            Log.d(TAG, "No files in app dir " + dir);
6658            return;
6659        }
6660
6661        if (DEBUG_PACKAGE_SCANNING) {
6662            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6663                    + " flags=0x" + Integer.toHexString(parseFlags));
6664        }
6665
6666        for (File file : files) {
6667            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6668                    && !PackageInstallerService.isStageName(file.getName());
6669            if (!isPackage) {
6670                // Ignore entries which are not packages
6671                continue;
6672            }
6673            try {
6674                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6675                        scanFlags, currentTime, null);
6676            } catch (PackageManagerException e) {
6677                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6678
6679                // Delete invalid userdata apps
6680                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6681                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6682                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6683                    removeCodePathLI(file);
6684                }
6685            }
6686        }
6687    }
6688
6689    private static File getSettingsProblemFile() {
6690        File dataDir = Environment.getDataDirectory();
6691        File systemDir = new File(dataDir, "system");
6692        File fname = new File(systemDir, "uiderrors.txt");
6693        return fname;
6694    }
6695
6696    static void reportSettingsProblem(int priority, String msg) {
6697        logCriticalInfo(priority, msg);
6698    }
6699
6700    static void logCriticalInfo(int priority, String msg) {
6701        Slog.println(priority, TAG, msg);
6702        EventLogTags.writePmCriticalInfo(msg);
6703        try {
6704            File fname = getSettingsProblemFile();
6705            FileOutputStream out = new FileOutputStream(fname, true);
6706            PrintWriter pw = new FastPrintWriter(out);
6707            SimpleDateFormat formatter = new SimpleDateFormat();
6708            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6709            pw.println(dateString + ": " + msg);
6710            pw.close();
6711            FileUtils.setPermissions(
6712                    fname.toString(),
6713                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6714                    -1, -1);
6715        } catch (java.io.IOException e) {
6716        }
6717    }
6718
6719    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6720            final int policyFlags) throws PackageManagerException {
6721        if (ps != null
6722                && ps.codePath.equals(srcFile)
6723                && ps.timeStamp == srcFile.lastModified()
6724                && !isCompatSignatureUpdateNeeded(pkg)
6725                && !isRecoverSignatureUpdateNeeded(pkg)) {
6726            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6727            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6728            ArraySet<PublicKey> signingKs;
6729            synchronized (mPackages) {
6730                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6731            }
6732            if (ps.signatures.mSignatures != null
6733                    && ps.signatures.mSignatures.length != 0
6734                    && signingKs != null) {
6735                // Optimization: reuse the existing cached certificates
6736                // if the package appears to be unchanged.
6737                pkg.mSignatures = ps.signatures.mSignatures;
6738                pkg.mSigningKeys = signingKs;
6739                return;
6740            }
6741
6742            Slog.w(TAG, "PackageSetting for " + ps.name
6743                    + " is missing signatures.  Collecting certs again to recover them.");
6744        } else {
6745            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6746        }
6747
6748        try {
6749            PackageParser.collectCertificates(pkg, policyFlags);
6750        } catch (PackageParserException e) {
6751            throw PackageManagerException.from(e);
6752        }
6753    }
6754
6755    /**
6756     *  Traces a package scan.
6757     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6758     */
6759    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6760            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6761        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6762        try {
6763            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6764        } finally {
6765            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6766        }
6767    }
6768
6769    /**
6770     *  Scans a package and returns the newly parsed package.
6771     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6772     */
6773    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6774            long currentTime, UserHandle user) throws PackageManagerException {
6775        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6776        PackageParser pp = new PackageParser();
6777        pp.setSeparateProcesses(mSeparateProcesses);
6778        pp.setOnlyCoreApps(mOnlyCore);
6779        pp.setDisplayMetrics(mMetrics);
6780
6781        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6782            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6783        }
6784
6785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6786        final PackageParser.Package pkg;
6787        try {
6788            pkg = pp.parsePackage(scanFile, parseFlags);
6789        } catch (PackageParserException e) {
6790            throw PackageManagerException.from(e);
6791        } finally {
6792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6793        }
6794
6795        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6796    }
6797
6798    /**
6799     *  Scans a package and returns the newly parsed package.
6800     *  @throws PackageManagerException on a parse error.
6801     */
6802    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6803            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6804            throws PackageManagerException {
6805        // If the package has children and this is the first dive in the function
6806        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6807        // packages (parent and children) would be successfully scanned before the
6808        // actual scan since scanning mutates internal state and we want to atomically
6809        // install the package and its children.
6810        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6811            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6812                scanFlags |= SCAN_CHECK_ONLY;
6813            }
6814        } else {
6815            scanFlags &= ~SCAN_CHECK_ONLY;
6816        }
6817
6818        // Scan the parent
6819        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6820                scanFlags, currentTime, user);
6821
6822        // Scan the children
6823        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6824        for (int i = 0; i < childCount; i++) {
6825            PackageParser.Package childPackage = pkg.childPackages.get(i);
6826            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6827                    currentTime, user);
6828        }
6829
6830
6831        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6832            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6833        }
6834
6835        return scannedPkg;
6836    }
6837
6838    /**
6839     *  Scans a package and returns the newly parsed package.
6840     *  @throws PackageManagerException on a parse error.
6841     */
6842    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6843            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6844            throws PackageManagerException {
6845        PackageSetting ps = null;
6846        PackageSetting updatedPkg;
6847        // reader
6848        synchronized (mPackages) {
6849            // Look to see if we already know about this package.
6850            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6851            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6852                // This package has been renamed to its original name.  Let's
6853                // use that.
6854                ps = mSettings.peekPackageLPr(oldName);
6855            }
6856            // If there was no original package, see one for the real package name.
6857            if (ps == null) {
6858                ps = mSettings.peekPackageLPr(pkg.packageName);
6859            }
6860            // Check to see if this package could be hiding/updating a system
6861            // package.  Must look for it either under the original or real
6862            // package name depending on our state.
6863            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6864            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6865
6866            // If this is a package we don't know about on the system partition, we
6867            // may need to remove disabled child packages on the system partition
6868            // or may need to not add child packages if the parent apk is updated
6869            // on the data partition and no longer defines this child package.
6870            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6871                // If this is a parent package for an updated system app and this system
6872                // app got an OTA update which no longer defines some of the child packages
6873                // we have to prune them from the disabled system packages.
6874                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6875                if (disabledPs != null) {
6876                    final int scannedChildCount = (pkg.childPackages != null)
6877                            ? pkg.childPackages.size() : 0;
6878                    final int disabledChildCount = disabledPs.childPackageNames != null
6879                            ? disabledPs.childPackageNames.size() : 0;
6880                    for (int i = 0; i < disabledChildCount; i++) {
6881                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6882                        boolean disabledPackageAvailable = false;
6883                        for (int j = 0; j < scannedChildCount; j++) {
6884                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6885                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6886                                disabledPackageAvailable = true;
6887                                break;
6888                            }
6889                         }
6890                         if (!disabledPackageAvailable) {
6891                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6892                         }
6893                    }
6894                }
6895            }
6896        }
6897
6898        boolean updatedPkgBetter = false;
6899        // First check if this is a system package that may involve an update
6900        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6901            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6902            // it needs to drop FLAG_PRIVILEGED.
6903            if (locationIsPrivileged(scanFile)) {
6904                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6905            } else {
6906                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6907            }
6908
6909            if (ps != null && !ps.codePath.equals(scanFile)) {
6910                // The path has changed from what was last scanned...  check the
6911                // version of the new path against what we have stored to determine
6912                // what to do.
6913                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6914                if (pkg.mVersionCode <= ps.versionCode) {
6915                    // The system package has been updated and the code path does not match
6916                    // Ignore entry. Skip it.
6917                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6918                            + " ignored: updated version " + ps.versionCode
6919                            + " better than this " + pkg.mVersionCode);
6920                    if (!updatedPkg.codePath.equals(scanFile)) {
6921                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6922                                + ps.name + " changing from " + updatedPkg.codePathString
6923                                + " to " + scanFile);
6924                        updatedPkg.codePath = scanFile;
6925                        updatedPkg.codePathString = scanFile.toString();
6926                        updatedPkg.resourcePath = scanFile;
6927                        updatedPkg.resourcePathString = scanFile.toString();
6928                    }
6929                    updatedPkg.pkg = pkg;
6930                    updatedPkg.versionCode = pkg.mVersionCode;
6931
6932                    // Update the disabled system child packages to point to the package too.
6933                    final int childCount = updatedPkg.childPackageNames != null
6934                            ? updatedPkg.childPackageNames.size() : 0;
6935                    for (int i = 0; i < childCount; i++) {
6936                        String childPackageName = updatedPkg.childPackageNames.get(i);
6937                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6938                                childPackageName);
6939                        if (updatedChildPkg != null) {
6940                            updatedChildPkg.pkg = pkg;
6941                            updatedChildPkg.versionCode = pkg.mVersionCode;
6942                        }
6943                    }
6944
6945                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6946                            + scanFile + " ignored: updated version " + ps.versionCode
6947                            + " better than this " + pkg.mVersionCode);
6948                } else {
6949                    // The current app on the system partition is better than
6950                    // what we have updated to on the data partition; switch
6951                    // back to the system partition version.
6952                    // At this point, its safely assumed that package installation for
6953                    // apps in system partition will go through. If not there won't be a working
6954                    // version of the app
6955                    // writer
6956                    synchronized (mPackages) {
6957                        // Just remove the loaded entries from package lists.
6958                        mPackages.remove(ps.name);
6959                    }
6960
6961                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6962                            + " reverting from " + ps.codePathString
6963                            + ": new version " + pkg.mVersionCode
6964                            + " better than installed " + ps.versionCode);
6965
6966                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6967                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6968                    synchronized (mInstallLock) {
6969                        args.cleanUpResourcesLI();
6970                    }
6971                    synchronized (mPackages) {
6972                        mSettings.enableSystemPackageLPw(ps.name);
6973                    }
6974                    updatedPkgBetter = true;
6975                }
6976            }
6977        }
6978
6979        if (updatedPkg != null) {
6980            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6981            // initially
6982            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6983
6984            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6985            // flag set initially
6986            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6987                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6988            }
6989        }
6990
6991        // Verify certificates against what was last scanned
6992        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6993
6994        /*
6995         * A new system app appeared, but we already had a non-system one of the
6996         * same name installed earlier.
6997         */
6998        boolean shouldHideSystemApp = false;
6999        if (updatedPkg == null && ps != null
7000                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7001            /*
7002             * Check to make sure the signatures match first. If they don't,
7003             * wipe the installed application and its data.
7004             */
7005            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7006                    != PackageManager.SIGNATURE_MATCH) {
7007                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7008                        + " signatures don't match existing userdata copy; removing");
7009                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7010                        "scanPackageInternalLI")) {
7011                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7012                }
7013                ps = null;
7014            } else {
7015                /*
7016                 * If the newly-added system app is an older version than the
7017                 * already installed version, hide it. It will be scanned later
7018                 * and re-added like an update.
7019                 */
7020                if (pkg.mVersionCode <= ps.versionCode) {
7021                    shouldHideSystemApp = true;
7022                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7023                            + " but new version " + pkg.mVersionCode + " better than installed "
7024                            + ps.versionCode + "; hiding system");
7025                } else {
7026                    /*
7027                     * The newly found system app is a newer version that the
7028                     * one previously installed. Simply remove the
7029                     * already-installed application and replace it with our own
7030                     * while keeping the application data.
7031                     */
7032                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7033                            + " reverting from " + ps.codePathString + ": new version "
7034                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7035                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7036                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7037                    synchronized (mInstallLock) {
7038                        args.cleanUpResourcesLI();
7039                    }
7040                }
7041            }
7042        }
7043
7044        // The apk is forward locked (not public) if its code and resources
7045        // are kept in different files. (except for app in either system or
7046        // vendor path).
7047        // TODO grab this value from PackageSettings
7048        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7049            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7050                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7051            }
7052        }
7053
7054        // TODO: extend to support forward-locked splits
7055        String resourcePath = null;
7056        String baseResourcePath = null;
7057        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7058            if (ps != null && ps.resourcePathString != null) {
7059                resourcePath = ps.resourcePathString;
7060                baseResourcePath = ps.resourcePathString;
7061            } else {
7062                // Should not happen at all. Just log an error.
7063                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7064            }
7065        } else {
7066            resourcePath = pkg.codePath;
7067            baseResourcePath = pkg.baseCodePath;
7068        }
7069
7070        // Set application objects path explicitly.
7071        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7072        pkg.setApplicationInfoCodePath(pkg.codePath);
7073        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7074        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7075        pkg.setApplicationInfoResourcePath(resourcePath);
7076        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7077        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7078
7079        // Note that we invoke the following method only if we are about to unpack an application
7080        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7081                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7082
7083        /*
7084         * If the system app should be overridden by a previously installed
7085         * data, hide the system app now and let the /data/app scan pick it up
7086         * again.
7087         */
7088        if (shouldHideSystemApp) {
7089            synchronized (mPackages) {
7090                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7091            }
7092        }
7093
7094        return scannedPkg;
7095    }
7096
7097    private static String fixProcessName(String defProcessName,
7098            String processName, int uid) {
7099        if (processName == null) {
7100            return defProcessName;
7101        }
7102        return processName;
7103    }
7104
7105    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7106            throws PackageManagerException {
7107        if (pkgSetting.signatures.mSignatures != null) {
7108            // Already existing package. Make sure signatures match
7109            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7110                    == PackageManager.SIGNATURE_MATCH;
7111            if (!match) {
7112                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7113                        == PackageManager.SIGNATURE_MATCH;
7114            }
7115            if (!match) {
7116                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7117                        == PackageManager.SIGNATURE_MATCH;
7118            }
7119            if (!match) {
7120                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7121                        + pkg.packageName + " signatures do not match the "
7122                        + "previously installed version; ignoring!");
7123            }
7124        }
7125
7126        // Check for shared user signatures
7127        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7128            // Already existing package. Make sure signatures match
7129            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7130                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7131            if (!match) {
7132                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7133                        == PackageManager.SIGNATURE_MATCH;
7134            }
7135            if (!match) {
7136                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7137                        == PackageManager.SIGNATURE_MATCH;
7138            }
7139            if (!match) {
7140                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7141                        "Package " + pkg.packageName
7142                        + " has no signatures that match those in shared user "
7143                        + pkgSetting.sharedUser.name + "; ignoring!");
7144            }
7145        }
7146    }
7147
7148    /**
7149     * Enforces that only the system UID or root's UID can call a method exposed
7150     * via Binder.
7151     *
7152     * @param message used as message if SecurityException is thrown
7153     * @throws SecurityException if the caller is not system or root
7154     */
7155    private static final void enforceSystemOrRoot(String message) {
7156        final int uid = Binder.getCallingUid();
7157        if (uid != Process.SYSTEM_UID && uid != 0) {
7158            throw new SecurityException(message);
7159        }
7160    }
7161
7162    @Override
7163    public void performFstrimIfNeeded() {
7164        enforceSystemOrRoot("Only the system can request fstrim");
7165
7166        // Before everything else, see whether we need to fstrim.
7167        try {
7168            IMountService ms = PackageHelper.getMountService();
7169            if (ms != null) {
7170                final boolean isUpgrade = isUpgrade();
7171                boolean doTrim = isUpgrade;
7172                if (doTrim) {
7173                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7174                } else {
7175                    final long interval = android.provider.Settings.Global.getLong(
7176                            mContext.getContentResolver(),
7177                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7178                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7179                    if (interval > 0) {
7180                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7181                        if (timeSinceLast > interval) {
7182                            doTrim = true;
7183                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7184                                    + "; running immediately");
7185                        }
7186                    }
7187                }
7188                if (doTrim) {
7189                    if (!isFirstBoot()) {
7190                        try {
7191                            ActivityManagerNative.getDefault().showBootMessage(
7192                                    mContext.getResources().getString(
7193                                            R.string.android_upgrading_fstrim), true);
7194                        } catch (RemoteException e) {
7195                        }
7196                    }
7197                    ms.runMaintenance();
7198                }
7199            } else {
7200                Slog.e(TAG, "Mount service unavailable!");
7201            }
7202        } catch (RemoteException e) {
7203            // Can't happen; MountService is local
7204        }
7205    }
7206
7207    @Override
7208    public void updatePackagesIfNeeded() {
7209        enforceSystemOrRoot("Only the system can request package update");
7210
7211        // We need to re-extract after an OTA.
7212        boolean causeUpgrade = isUpgrade();
7213
7214        // First boot or factory reset.
7215        // Note: we also handle devices that are upgrading to N right now as if it is their
7216        //       first boot, as they do not have profile data.
7217        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7218
7219        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7220        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7221
7222        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7223            return;
7224        }
7225
7226        List<PackageParser.Package> pkgs;
7227        synchronized (mPackages) {
7228            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7229        }
7230
7231        int numberOfPackagesVisited = 0;
7232        int numberOfPackagesOptimized = 0;
7233        int numberOfPackagesSkipped = 0;
7234        int numberOfPackagesFailed = 0;
7235        final int numberOfPackagesToDexopt = pkgs.size();
7236        final long startTime = System.nanoTime();
7237
7238        for (PackageParser.Package pkg : pkgs) {
7239            numberOfPackagesVisited++;
7240
7241            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7242                if (DEBUG_DEXOPT) {
7243                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7244                }
7245                numberOfPackagesSkipped++;
7246                continue;
7247            }
7248
7249            if (DEBUG_DEXOPT) {
7250                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7251                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7252            }
7253
7254            if (mIsPreNUpgrade) {
7255                try {
7256                    ActivityManagerNative.getDefault().showBootMessage(
7257                            mContext.getResources().getString(R.string.android_upgrading_apk,
7258                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7259                } catch (RemoteException e) {
7260                }
7261            }
7262
7263            // checkProfiles is false to avoid merging profiles during boot which
7264            // might interfere with background compilation (b/28612421).
7265            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7266            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7267            // trade-off worth doing to save boot time work.
7268            int dexOptStatus = performDexOptTraced(pkg.packageName,
7269                    false /* checkProfiles */,
7270                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
7271                    false /* force */);
7272            switch (dexOptStatus) {
7273                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7274                    numberOfPackagesOptimized++;
7275                    break;
7276                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7277                    numberOfPackagesSkipped++;
7278                    break;
7279                case PackageDexOptimizer.DEX_OPT_FAILED:
7280                    numberOfPackagesFailed++;
7281                    break;
7282                default:
7283                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7284                    break;
7285            }
7286        }
7287
7288        final int elapsedTimeSeconds =
7289                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7290        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized);
7291        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped);
7292        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed);
7293        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7294        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7295    }
7296
7297    @Override
7298    public void notifyPackageUse(String packageName, int reason) {
7299        synchronized (mPackages) {
7300            PackageParser.Package p = mPackages.get(packageName);
7301            if (p == null) {
7302                return;
7303            }
7304            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7305        }
7306    }
7307
7308    // TODO: this is not used nor needed. Delete it.
7309    @Override
7310    public boolean performDexOptIfNeeded(String packageName) {
7311        int dexOptStatus = performDexOptTraced(packageName,
7312                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7313        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7314    }
7315
7316    @Override
7317    public boolean performDexOpt(String packageName,
7318            boolean checkProfiles, int compileReason, boolean force) {
7319        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7320                getCompilerFilterForReason(compileReason), force);
7321        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7322    }
7323
7324    @Override
7325    public boolean performDexOptMode(String packageName,
7326            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7327        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7328                targetCompilerFilter, force);
7329        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7330    }
7331
7332    private int performDexOptTraced(String packageName,
7333                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7334        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7335        try {
7336            return performDexOptInternal(packageName, checkProfiles,
7337                    targetCompilerFilter, force);
7338        } finally {
7339            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7340        }
7341    }
7342
7343    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7344    // if the package can now be considered up to date for the given filter.
7345    private int performDexOptInternal(String packageName,
7346                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7347        PackageParser.Package p;
7348        synchronized (mPackages) {
7349            p = mPackages.get(packageName);
7350            if (p == null) {
7351                // Package could not be found. Report failure.
7352                return PackageDexOptimizer.DEX_OPT_FAILED;
7353            }
7354            mPackageUsage.write(false);
7355        }
7356        long callingId = Binder.clearCallingIdentity();
7357        try {
7358            synchronized (mInstallLock) {
7359                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7360                        targetCompilerFilter, force);
7361            }
7362        } finally {
7363            Binder.restoreCallingIdentity(callingId);
7364        }
7365    }
7366
7367    public ArraySet<String> getOptimizablePackages() {
7368        ArraySet<String> pkgs = new ArraySet<String>();
7369        synchronized (mPackages) {
7370            for (PackageParser.Package p : mPackages.values()) {
7371                if (PackageDexOptimizer.canOptimizePackage(p)) {
7372                    pkgs.add(p.packageName);
7373                }
7374            }
7375        }
7376        return pkgs;
7377    }
7378
7379    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7380            boolean checkProfiles, String targetCompilerFilter,
7381            boolean force) {
7382        // Select the dex optimizer based on the force parameter.
7383        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7384        //       allocate an object here.
7385        PackageDexOptimizer pdo = force
7386                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7387                : mPackageDexOptimizer;
7388
7389        // Optimize all dependencies first. Note: we ignore the return value and march on
7390        // on errors.
7391        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7392        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7393        if (!deps.isEmpty()) {
7394            for (PackageParser.Package depPackage : deps) {
7395                // TODO: Analyze and investigate if we (should) profile libraries.
7396                // Currently this will do a full compilation of the library by default.
7397                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7398                        false /* checkProfiles */,
7399                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7400            }
7401        }
7402        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7403                targetCompilerFilter);
7404    }
7405
7406    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7407        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7408            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7409            Set<String> collectedNames = new HashSet<>();
7410            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7411
7412            retValue.remove(p);
7413
7414            return retValue;
7415        } else {
7416            return Collections.emptyList();
7417        }
7418    }
7419
7420    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7421            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7422        if (!collectedNames.contains(p.packageName)) {
7423            collectedNames.add(p.packageName);
7424            collected.add(p);
7425
7426            if (p.usesLibraries != null) {
7427                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7428            }
7429            if (p.usesOptionalLibraries != null) {
7430                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7431                        collectedNames);
7432            }
7433        }
7434    }
7435
7436    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7437            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7438        for (String libName : libs) {
7439            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7440            if (libPkg != null) {
7441                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7442            }
7443        }
7444    }
7445
7446    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7447        synchronized (mPackages) {
7448            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7449            if (lib != null && lib.apk != null) {
7450                return mPackages.get(lib.apk);
7451            }
7452        }
7453        return null;
7454    }
7455
7456    public void shutdown() {
7457        mPackageUsage.write(true);
7458    }
7459
7460    @Override
7461    public void dumpProfiles(String packageName) {
7462        PackageParser.Package pkg;
7463        synchronized (mPackages) {
7464            pkg = mPackages.get(packageName);
7465            if (pkg == null) {
7466                throw new IllegalArgumentException("Unknown package: " + packageName);
7467            }
7468        }
7469        /* Only the shell or the app user should be able to dump profiles. */
7470        int callingUid = Binder.getCallingUid();
7471        if (callingUid != Process.SHELL_UID && callingUid != pkg.applicationInfo.uid) {
7472            throw new SecurityException("dumpProfiles");
7473        }
7474
7475        synchronized (mInstallLock) {
7476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7477            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7478            try {
7479                final File codeFile = new File(pkg.applicationInfo.getCodePath());
7480                List<String> allCodePaths = Collections.EMPTY_LIST;
7481                if (codeFile != null && codeFile.exists()) {
7482                    try {
7483                        final PackageLite codePkg = PackageParser.parsePackageLite(codeFile, 0);
7484                        allCodePaths = codePkg.getAllCodePaths();
7485                    } catch (PackageParserException e) {
7486                        // Well, we tried.
7487                    }
7488                }
7489                String gid = Integer.toString(sharedGid);
7490                String codePaths = TextUtils.join(";", allCodePaths);
7491                mInstaller.dumpProfiles(gid, packageName, codePaths);
7492            } catch (InstallerException e) {
7493                Slog.w(TAG, "Failed to dump profiles", e);
7494            }
7495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7496        }
7497    }
7498
7499    @Override
7500    public void forceDexOpt(String packageName) {
7501        enforceSystemOrRoot("forceDexOpt");
7502
7503        PackageParser.Package pkg;
7504        synchronized (mPackages) {
7505            pkg = mPackages.get(packageName);
7506            if (pkg == null) {
7507                throw new IllegalArgumentException("Unknown package: " + packageName);
7508            }
7509        }
7510
7511        synchronized (mInstallLock) {
7512            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7513
7514            // Whoever is calling forceDexOpt wants a fully compiled package.
7515            // Don't use profiles since that may cause compilation to be skipped.
7516            final int res = performDexOptInternalWithDependenciesLI(pkg,
7517                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7518                    true /* force */);
7519
7520            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7521            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7522                throw new IllegalStateException("Failed to dexopt: " + res);
7523            }
7524        }
7525    }
7526
7527    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7528        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7529            Slog.w(TAG, "Unable to update from " + oldPkg.name
7530                    + " to " + newPkg.packageName
7531                    + ": old package not in system partition");
7532            return false;
7533        } else if (mPackages.get(oldPkg.name) != null) {
7534            Slog.w(TAG, "Unable to update from " + oldPkg.name
7535                    + " to " + newPkg.packageName
7536                    + ": old package still exists");
7537            return false;
7538        }
7539        return true;
7540    }
7541
7542    void removeCodePathLI(File codePath) {
7543        if (codePath.isDirectory()) {
7544            try {
7545                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7546            } catch (InstallerException e) {
7547                Slog.w(TAG, "Failed to remove code path", e);
7548            }
7549        } else {
7550            codePath.delete();
7551        }
7552    }
7553
7554    private int[] resolveUserIds(int userId) {
7555        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7556    }
7557
7558    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7559        if (pkg == null) {
7560            Slog.wtf(TAG, "Package was null!", new Throwable());
7561            return;
7562        }
7563        clearAppDataLeafLIF(pkg, userId, flags);
7564        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7565        for (int i = 0; i < childCount; i++) {
7566            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7567        }
7568    }
7569
7570    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7571        final PackageSetting ps;
7572        synchronized (mPackages) {
7573            ps = mSettings.mPackages.get(pkg.packageName);
7574        }
7575        for (int realUserId : resolveUserIds(userId)) {
7576            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7577            try {
7578                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7579                        ceDataInode);
7580            } catch (InstallerException e) {
7581                Slog.w(TAG, String.valueOf(e));
7582            }
7583        }
7584    }
7585
7586    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7587        if (pkg == null) {
7588            Slog.wtf(TAG, "Package was null!", new Throwable());
7589            return;
7590        }
7591        destroyAppDataLeafLIF(pkg, userId, flags);
7592        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7593        for (int i = 0; i < childCount; i++) {
7594            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7595        }
7596    }
7597
7598    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7599        final PackageSetting ps;
7600        synchronized (mPackages) {
7601            ps = mSettings.mPackages.get(pkg.packageName);
7602        }
7603        for (int realUserId : resolveUserIds(userId)) {
7604            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7605            try {
7606                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7607                        ceDataInode);
7608            } catch (InstallerException e) {
7609                Slog.w(TAG, String.valueOf(e));
7610            }
7611        }
7612    }
7613
7614    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7615        if (pkg == null) {
7616            Slog.wtf(TAG, "Package was null!", new Throwable());
7617            return;
7618        }
7619        destroyAppProfilesLeafLIF(pkg);
7620        destroyAppReferenceProfileLeafLIF(pkg, userId);
7621        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7622        for (int i = 0; i < childCount; i++) {
7623            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7624            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId);
7625        }
7626    }
7627
7628    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) {
7629        if (pkg.isForwardLocked()) {
7630            return;
7631        }
7632
7633        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7634            try {
7635                path = PackageManagerServiceUtils.realpath(new File(path));
7636            } catch (IOException e) {
7637                // TODO: Should we return early here ?
7638                Slog.w(TAG, "Failed to get canonical path", e);
7639                continue;
7640            }
7641
7642            final String useMarker = path.replace('/', '@');
7643            for (int realUserId : resolveUserIds(userId)) {
7644                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7645                File foreignUseMark = new File(profileDir, useMarker);
7646                if (foreignUseMark.exists()) {
7647                    if (!foreignUseMark.delete()) {
7648                        Slog.w(TAG, "Unable to delete foreign user mark for package: "
7649                            + pkg.packageName);
7650                    }
7651                }
7652
7653                File[] markers = profileDir.listFiles();
7654                if (markers != null) {
7655                    final String searchString = "@" + pkg.packageName + "@";
7656                    // We also delete all markers that contain the package name we're
7657                    // uninstalling. These are associated with secondary dex-files belonging
7658                    // to the package. Reconstructing the path of these dex files is messy
7659                    // in general.
7660                    for (File marker : markers) {
7661                        if (marker.getName().indexOf(searchString) > 0) {
7662                            if (!marker.delete()) {
7663                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7664                                    + pkg.packageName);
7665                            }
7666                        }
7667                    }
7668                }
7669            }
7670        }
7671    }
7672
7673    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7674        try {
7675            mInstaller.destroyAppProfiles(pkg.packageName);
7676        } catch (InstallerException e) {
7677            Slog.w(TAG, String.valueOf(e));
7678        }
7679    }
7680
7681    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7682        if (pkg == null) {
7683            Slog.wtf(TAG, "Package was null!", new Throwable());
7684            return;
7685        }
7686        clearAppProfilesLeafLIF(pkg);
7687        destroyAppReferenceProfileLeafLIF(pkg, userId);
7688        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7689        for (int i = 0; i < childCount; i++) {
7690            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7691        }
7692    }
7693
7694    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7695        try {
7696            mInstaller.clearAppProfiles(pkg.packageName);
7697        } catch (InstallerException e) {
7698            Slog.w(TAG, String.valueOf(e));
7699        }
7700    }
7701
7702    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7703            long lastUpdateTime) {
7704        // Set parent install/update time
7705        PackageSetting ps = (PackageSetting) pkg.mExtras;
7706        if (ps != null) {
7707            ps.firstInstallTime = firstInstallTime;
7708            ps.lastUpdateTime = lastUpdateTime;
7709        }
7710        // Set children install/update time
7711        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7712        for (int i = 0; i < childCount; i++) {
7713            PackageParser.Package childPkg = pkg.childPackages.get(i);
7714            ps = (PackageSetting) childPkg.mExtras;
7715            if (ps != null) {
7716                ps.firstInstallTime = firstInstallTime;
7717                ps.lastUpdateTime = lastUpdateTime;
7718            }
7719        }
7720    }
7721
7722    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7723            PackageParser.Package changingLib) {
7724        if (file.path != null) {
7725            usesLibraryFiles.add(file.path);
7726            return;
7727        }
7728        PackageParser.Package p = mPackages.get(file.apk);
7729        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7730            // If we are doing this while in the middle of updating a library apk,
7731            // then we need to make sure to use that new apk for determining the
7732            // dependencies here.  (We haven't yet finished committing the new apk
7733            // to the package manager state.)
7734            if (p == null || p.packageName.equals(changingLib.packageName)) {
7735                p = changingLib;
7736            }
7737        }
7738        if (p != null) {
7739            usesLibraryFiles.addAll(p.getAllCodePaths());
7740        }
7741    }
7742
7743    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7744            PackageParser.Package changingLib) throws PackageManagerException {
7745        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7746            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7747            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7748            for (int i=0; i<N; i++) {
7749                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7750                if (file == null) {
7751                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7752                            "Package " + pkg.packageName + " requires unavailable shared library "
7753                            + pkg.usesLibraries.get(i) + "; failing!");
7754                }
7755                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7756            }
7757            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7758            for (int i=0; i<N; i++) {
7759                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7760                if (file == null) {
7761                    Slog.w(TAG, "Package " + pkg.packageName
7762                            + " desires unavailable shared library "
7763                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7764                } else {
7765                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7766                }
7767            }
7768            N = usesLibraryFiles.size();
7769            if (N > 0) {
7770                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7771            } else {
7772                pkg.usesLibraryFiles = null;
7773            }
7774        }
7775    }
7776
7777    private static boolean hasString(List<String> list, List<String> which) {
7778        if (list == null) {
7779            return false;
7780        }
7781        for (int i=list.size()-1; i>=0; i--) {
7782            for (int j=which.size()-1; j>=0; j--) {
7783                if (which.get(j).equals(list.get(i))) {
7784                    return true;
7785                }
7786            }
7787        }
7788        return false;
7789    }
7790
7791    private void updateAllSharedLibrariesLPw() {
7792        for (PackageParser.Package pkg : mPackages.values()) {
7793            try {
7794                updateSharedLibrariesLPw(pkg, null);
7795            } catch (PackageManagerException e) {
7796                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7797            }
7798        }
7799    }
7800
7801    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7802            PackageParser.Package changingPkg) {
7803        ArrayList<PackageParser.Package> res = null;
7804        for (PackageParser.Package pkg : mPackages.values()) {
7805            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7806                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7807                if (res == null) {
7808                    res = new ArrayList<PackageParser.Package>();
7809                }
7810                res.add(pkg);
7811                try {
7812                    updateSharedLibrariesLPw(pkg, changingPkg);
7813                } catch (PackageManagerException e) {
7814                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7815                }
7816            }
7817        }
7818        return res;
7819    }
7820
7821    /**
7822     * Derive the value of the {@code cpuAbiOverride} based on the provided
7823     * value and an optional stored value from the package settings.
7824     */
7825    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7826        String cpuAbiOverride = null;
7827
7828        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7829            cpuAbiOverride = null;
7830        } else if (abiOverride != null) {
7831            cpuAbiOverride = abiOverride;
7832        } else if (settings != null) {
7833            cpuAbiOverride = settings.cpuAbiOverrideString;
7834        }
7835
7836        return cpuAbiOverride;
7837    }
7838
7839    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7840            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7841                    throws PackageManagerException {
7842        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7843        // If the package has children and this is the first dive in the function
7844        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7845        // whether all packages (parent and children) would be successfully scanned
7846        // before the actual scan since scanning mutates internal state and we want
7847        // to atomically install the package and its children.
7848        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7849            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7850                scanFlags |= SCAN_CHECK_ONLY;
7851            }
7852        } else {
7853            scanFlags &= ~SCAN_CHECK_ONLY;
7854        }
7855
7856        final PackageParser.Package scannedPkg;
7857        try {
7858            // Scan the parent
7859            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7860            // Scan the children
7861            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7862            for (int i = 0; i < childCount; i++) {
7863                PackageParser.Package childPkg = pkg.childPackages.get(i);
7864                scanPackageLI(childPkg, policyFlags,
7865                        scanFlags, currentTime, user);
7866            }
7867        } finally {
7868            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7869        }
7870
7871        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7872            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7873        }
7874
7875        return scannedPkg;
7876    }
7877
7878    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7879            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7880        boolean success = false;
7881        try {
7882            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7883                    currentTime, user);
7884            success = true;
7885            return res;
7886        } finally {
7887            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7888                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7889                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7890                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7891                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7892            }
7893        }
7894    }
7895
7896    /**
7897     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7898     */
7899    private static boolean apkHasCode(String fileName) {
7900        StrictJarFile jarFile = null;
7901        try {
7902            jarFile = new StrictJarFile(fileName,
7903                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7904            return jarFile.findEntry("classes.dex") != null;
7905        } catch (IOException ignore) {
7906        } finally {
7907            try {
7908                jarFile.close();
7909            } catch (IOException ignore) {}
7910        }
7911        return false;
7912    }
7913
7914    /**
7915     * Enforces code policy for the package. This ensures that if an APK has
7916     * declared hasCode="true" in its manifest that the APK actually contains
7917     * code.
7918     *
7919     * @throws PackageManagerException If bytecode could not be found when it should exist
7920     */
7921    private static void enforceCodePolicy(PackageParser.Package pkg)
7922            throws PackageManagerException {
7923        final boolean shouldHaveCode =
7924                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7925        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7926            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7927                    "Package " + pkg.baseCodePath + " code is missing");
7928        }
7929
7930        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7931            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7932                final boolean splitShouldHaveCode =
7933                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7934                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7935                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7936                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7937                }
7938            }
7939        }
7940    }
7941
7942    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7943            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7944            throws PackageManagerException {
7945        final File scanFile = new File(pkg.codePath);
7946        if (pkg.applicationInfo.getCodePath() == null ||
7947                pkg.applicationInfo.getResourcePath() == null) {
7948            // Bail out. The resource and code paths haven't been set.
7949            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7950                    "Code and resource paths haven't been set correctly");
7951        }
7952
7953        // Apply policy
7954        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7955            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7956            if (pkg.applicationInfo.isDirectBootAware()) {
7957                // we're direct boot aware; set for all components
7958                for (PackageParser.Service s : pkg.services) {
7959                    s.info.encryptionAware = s.info.directBootAware = true;
7960                }
7961                for (PackageParser.Provider p : pkg.providers) {
7962                    p.info.encryptionAware = p.info.directBootAware = true;
7963                }
7964                for (PackageParser.Activity a : pkg.activities) {
7965                    a.info.encryptionAware = a.info.directBootAware = true;
7966                }
7967                for (PackageParser.Activity r : pkg.receivers) {
7968                    r.info.encryptionAware = r.info.directBootAware = true;
7969                }
7970            }
7971        } else {
7972            // Only allow system apps to be flagged as core apps.
7973            pkg.coreApp = false;
7974            // clear flags not applicable to regular apps
7975            pkg.applicationInfo.privateFlags &=
7976                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7977            pkg.applicationInfo.privateFlags &=
7978                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7979        }
7980        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7981
7982        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7983            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7984        }
7985
7986        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7987            enforceCodePolicy(pkg);
7988        }
7989
7990        if (mCustomResolverComponentName != null &&
7991                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7992            setUpCustomResolverActivity(pkg);
7993        }
7994
7995        if (pkg.packageName.equals("android")) {
7996            synchronized (mPackages) {
7997                if (mAndroidApplication != null) {
7998                    Slog.w(TAG, "*************************************************");
7999                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8000                    Slog.w(TAG, " file=" + scanFile);
8001                    Slog.w(TAG, "*************************************************");
8002                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8003                            "Core android package being redefined.  Skipping.");
8004                }
8005
8006                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8007                    // Set up information for our fall-back user intent resolution activity.
8008                    mPlatformPackage = pkg;
8009                    pkg.mVersionCode = mSdkVersion;
8010                    mAndroidApplication = pkg.applicationInfo;
8011
8012                    if (!mResolverReplaced) {
8013                        mResolveActivity.applicationInfo = mAndroidApplication;
8014                        mResolveActivity.name = ResolverActivity.class.getName();
8015                        mResolveActivity.packageName = mAndroidApplication.packageName;
8016                        mResolveActivity.processName = "system:ui";
8017                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8018                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8019                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8020                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8021                        mResolveActivity.exported = true;
8022                        mResolveActivity.enabled = true;
8023                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8024                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8025                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8026                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8027                                | ActivityInfo.CONFIG_ORIENTATION
8028                                | ActivityInfo.CONFIG_KEYBOARD
8029                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8030                        mResolveInfo.activityInfo = mResolveActivity;
8031                        mResolveInfo.priority = 0;
8032                        mResolveInfo.preferredOrder = 0;
8033                        mResolveInfo.match = 0;
8034                        mResolveComponentName = new ComponentName(
8035                                mAndroidApplication.packageName, mResolveActivity.name);
8036                    }
8037                }
8038            }
8039        }
8040
8041        if (DEBUG_PACKAGE_SCANNING) {
8042            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8043                Log.d(TAG, "Scanning package " + pkg.packageName);
8044        }
8045
8046        synchronized (mPackages) {
8047            if (mPackages.containsKey(pkg.packageName)
8048                    || mSharedLibraries.containsKey(pkg.packageName)) {
8049                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8050                        "Application package " + pkg.packageName
8051                                + " already installed.  Skipping duplicate.");
8052            }
8053
8054            // If we're only installing presumed-existing packages, require that the
8055            // scanned APK is both already known and at the path previously established
8056            // for it.  Previously unknown packages we pick up normally, but if we have an
8057            // a priori expectation about this package's install presence, enforce it.
8058            // With a singular exception for new system packages. When an OTA contains
8059            // a new system package, we allow the codepath to change from a system location
8060            // to the user-installed location. If we don't allow this change, any newer,
8061            // user-installed version of the application will be ignored.
8062            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8063                if (mExpectingBetter.containsKey(pkg.packageName)) {
8064                    logCriticalInfo(Log.WARN,
8065                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8066                } else {
8067                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8068                    if (known != null) {
8069                        if (DEBUG_PACKAGE_SCANNING) {
8070                            Log.d(TAG, "Examining " + pkg.codePath
8071                                    + " and requiring known paths " + known.codePathString
8072                                    + " & " + known.resourcePathString);
8073                        }
8074                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8075                                || !pkg.applicationInfo.getResourcePath().equals(
8076                                known.resourcePathString)) {
8077                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8078                                    "Application package " + pkg.packageName
8079                                            + " found at " + pkg.applicationInfo.getCodePath()
8080                                            + " but expected at " + known.codePathString
8081                                            + "; ignoring.");
8082                        }
8083                    }
8084                }
8085            }
8086        }
8087
8088        // Initialize package source and resource directories
8089        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8090        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8091
8092        SharedUserSetting suid = null;
8093        PackageSetting pkgSetting = null;
8094
8095        if (!isSystemApp(pkg)) {
8096            // Only system apps can use these features.
8097            pkg.mOriginalPackages = null;
8098            pkg.mRealPackage = null;
8099            pkg.mAdoptPermissions = null;
8100        }
8101
8102        // Getting the package setting may have a side-effect, so if we
8103        // are only checking if scan would succeed, stash a copy of the
8104        // old setting to restore at the end.
8105        PackageSetting nonMutatedPs = null;
8106
8107        // writer
8108        synchronized (mPackages) {
8109            if (pkg.mSharedUserId != null) {
8110                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8111                if (suid == null) {
8112                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8113                            "Creating application package " + pkg.packageName
8114                            + " for shared user failed");
8115                }
8116                if (DEBUG_PACKAGE_SCANNING) {
8117                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8118                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8119                                + "): packages=" + suid.packages);
8120                }
8121            }
8122
8123            // Check if we are renaming from an original package name.
8124            PackageSetting origPackage = null;
8125            String realName = null;
8126            if (pkg.mOriginalPackages != null) {
8127                // This package may need to be renamed to a previously
8128                // installed name.  Let's check on that...
8129                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8130                if (pkg.mOriginalPackages.contains(renamed)) {
8131                    // This package had originally been installed as the
8132                    // original name, and we have already taken care of
8133                    // transitioning to the new one.  Just update the new
8134                    // one to continue using the old name.
8135                    realName = pkg.mRealPackage;
8136                    if (!pkg.packageName.equals(renamed)) {
8137                        // Callers into this function may have already taken
8138                        // care of renaming the package; only do it here if
8139                        // it is not already done.
8140                        pkg.setPackageName(renamed);
8141                    }
8142
8143                } else {
8144                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8145                        if ((origPackage = mSettings.peekPackageLPr(
8146                                pkg.mOriginalPackages.get(i))) != null) {
8147                            // We do have the package already installed under its
8148                            // original name...  should we use it?
8149                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8150                                // New package is not compatible with original.
8151                                origPackage = null;
8152                                continue;
8153                            } else if (origPackage.sharedUser != null) {
8154                                // Make sure uid is compatible between packages.
8155                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8156                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8157                                            + " to " + pkg.packageName + ": old uid "
8158                                            + origPackage.sharedUser.name
8159                                            + " differs from " + pkg.mSharedUserId);
8160                                    origPackage = null;
8161                                    continue;
8162                                }
8163                                // TODO: Add case when shared user id is added [b/28144775]
8164                            } else {
8165                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8166                                        + pkg.packageName + " to old name " + origPackage.name);
8167                            }
8168                            break;
8169                        }
8170                    }
8171                }
8172            }
8173
8174            if (mTransferedPackages.contains(pkg.packageName)) {
8175                Slog.w(TAG, "Package " + pkg.packageName
8176                        + " was transferred to another, but its .apk remains");
8177            }
8178
8179            // See comments in nonMutatedPs declaration
8180            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8181                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8182                if (foundPs != null) {
8183                    nonMutatedPs = new PackageSetting(foundPs);
8184                }
8185            }
8186
8187            // Just create the setting, don't add it yet. For already existing packages
8188            // the PkgSetting exists already and doesn't have to be created.
8189            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8190                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8191                    pkg.applicationInfo.primaryCpuAbi,
8192                    pkg.applicationInfo.secondaryCpuAbi,
8193                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8194                    user, false);
8195            if (pkgSetting == null) {
8196                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8197                        "Creating application package " + pkg.packageName + " failed");
8198            }
8199
8200            if (pkgSetting.origPackage != null) {
8201                // If we are first transitioning from an original package,
8202                // fix up the new package's name now.  We need to do this after
8203                // looking up the package under its new name, so getPackageLP
8204                // can take care of fiddling things correctly.
8205                pkg.setPackageName(origPackage.name);
8206
8207                // File a report about this.
8208                String msg = "New package " + pkgSetting.realName
8209                        + " renamed to replace old package " + pkgSetting.name;
8210                reportSettingsProblem(Log.WARN, msg);
8211
8212                // Make a note of it.
8213                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8214                    mTransferedPackages.add(origPackage.name);
8215                }
8216
8217                // No longer need to retain this.
8218                pkgSetting.origPackage = null;
8219            }
8220
8221            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8222                // Make a note of it.
8223                mTransferedPackages.add(pkg.packageName);
8224            }
8225
8226            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8227                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8228            }
8229
8230            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8231                // Check all shared libraries and map to their actual file path.
8232                // We only do this here for apps not on a system dir, because those
8233                // are the only ones that can fail an install due to this.  We
8234                // will take care of the system apps by updating all of their
8235                // library paths after the scan is done.
8236                updateSharedLibrariesLPw(pkg, null);
8237            }
8238
8239            if (mFoundPolicyFile) {
8240                SELinuxMMAC.assignSeinfoValue(pkg);
8241            }
8242
8243            pkg.applicationInfo.uid = pkgSetting.appId;
8244            pkg.mExtras = pkgSetting;
8245            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8246                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8247                    // We just determined the app is signed correctly, so bring
8248                    // over the latest parsed certs.
8249                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8250                } else {
8251                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8252                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8253                                "Package " + pkg.packageName + " upgrade keys do not match the "
8254                                + "previously installed version");
8255                    } else {
8256                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8257                        String msg = "System package " + pkg.packageName
8258                            + " signature changed; retaining data.";
8259                        reportSettingsProblem(Log.WARN, msg);
8260                    }
8261                }
8262            } else {
8263                try {
8264                    verifySignaturesLP(pkgSetting, pkg);
8265                    // We just determined the app is signed correctly, so bring
8266                    // over the latest parsed certs.
8267                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8268                } catch (PackageManagerException e) {
8269                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8270                        throw e;
8271                    }
8272                    // The signature has changed, but this package is in the system
8273                    // image...  let's recover!
8274                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8275                    // However...  if this package is part of a shared user, but it
8276                    // doesn't match the signature of the shared user, let's fail.
8277                    // What this means is that you can't change the signatures
8278                    // associated with an overall shared user, which doesn't seem all
8279                    // that unreasonable.
8280                    if (pkgSetting.sharedUser != null) {
8281                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8282                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8283                            throw new PackageManagerException(
8284                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8285                                            "Signature mismatch for shared user: "
8286                                            + pkgSetting.sharedUser);
8287                        }
8288                    }
8289                    // File a report about this.
8290                    String msg = "System package " + pkg.packageName
8291                        + " signature changed; retaining data.";
8292                    reportSettingsProblem(Log.WARN, msg);
8293                }
8294            }
8295            // Verify that this new package doesn't have any content providers
8296            // that conflict with existing packages.  Only do this if the
8297            // package isn't already installed, since we don't want to break
8298            // things that are installed.
8299            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8300                final int N = pkg.providers.size();
8301                int i;
8302                for (i=0; i<N; i++) {
8303                    PackageParser.Provider p = pkg.providers.get(i);
8304                    if (p.info.authority != null) {
8305                        String names[] = p.info.authority.split(";");
8306                        for (int j = 0; j < names.length; j++) {
8307                            if (mProvidersByAuthority.containsKey(names[j])) {
8308                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8309                                final String otherPackageName =
8310                                        ((other != null && other.getComponentName() != null) ?
8311                                                other.getComponentName().getPackageName() : "?");
8312                                throw new PackageManagerException(
8313                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8314                                                "Can't install because provider name " + names[j]
8315                                                + " (in package " + pkg.applicationInfo.packageName
8316                                                + ") is already used by " + otherPackageName);
8317                            }
8318                        }
8319                    }
8320                }
8321            }
8322
8323            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8324                // This package wants to adopt ownership of permissions from
8325                // another package.
8326                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8327                    final String origName = pkg.mAdoptPermissions.get(i);
8328                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8329                    if (orig != null) {
8330                        if (verifyPackageUpdateLPr(orig, pkg)) {
8331                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8332                                    + pkg.packageName);
8333                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8334                        }
8335                    }
8336                }
8337            }
8338        }
8339
8340        final String pkgName = pkg.packageName;
8341
8342        final long scanFileTime = scanFile.lastModified();
8343        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8344        pkg.applicationInfo.processName = fixProcessName(
8345                pkg.applicationInfo.packageName,
8346                pkg.applicationInfo.processName,
8347                pkg.applicationInfo.uid);
8348
8349        if (pkg != mPlatformPackage) {
8350            // Get all of our default paths setup
8351            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8352        }
8353
8354        final String path = scanFile.getPath();
8355        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8356
8357        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8358            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8359
8360            // Some system apps still use directory structure for native libraries
8361            // in which case we might end up not detecting abi solely based on apk
8362            // structure. Try to detect abi based on directory structure.
8363            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8364                    pkg.applicationInfo.primaryCpuAbi == null) {
8365                setBundledAppAbisAndRoots(pkg, pkgSetting);
8366                setNativeLibraryPaths(pkg);
8367            }
8368
8369        } else {
8370            if ((scanFlags & SCAN_MOVE) != 0) {
8371                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8372                // but we already have this packages package info in the PackageSetting. We just
8373                // use that and derive the native library path based on the new codepath.
8374                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8375                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8376            }
8377
8378            // Set native library paths again. For moves, the path will be updated based on the
8379            // ABIs we've determined above. For non-moves, the path will be updated based on the
8380            // ABIs we determined during compilation, but the path will depend on the final
8381            // package path (after the rename away from the stage path).
8382            setNativeLibraryPaths(pkg);
8383        }
8384
8385        // This is a special case for the "system" package, where the ABI is
8386        // dictated by the zygote configuration (and init.rc). We should keep track
8387        // of this ABI so that we can deal with "normal" applications that run under
8388        // the same UID correctly.
8389        if (mPlatformPackage == pkg) {
8390            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8391                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8392        }
8393
8394        // If there's a mismatch between the abi-override in the package setting
8395        // and the abiOverride specified for the install. Warn about this because we
8396        // would've already compiled the app without taking the package setting into
8397        // account.
8398        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8399            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8400                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8401                        " for package " + pkg.packageName);
8402            }
8403        }
8404
8405        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8406        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8407        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8408
8409        // Copy the derived override back to the parsed package, so that we can
8410        // update the package settings accordingly.
8411        pkg.cpuAbiOverride = cpuAbiOverride;
8412
8413        if (DEBUG_ABI_SELECTION) {
8414            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8415                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8416                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8417        }
8418
8419        // Push the derived path down into PackageSettings so we know what to
8420        // clean up at uninstall time.
8421        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8422
8423        if (DEBUG_ABI_SELECTION) {
8424            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8425                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8426                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8427        }
8428
8429        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8430            // We don't do this here during boot because we can do it all
8431            // at once after scanning all existing packages.
8432            //
8433            // We also do this *before* we perform dexopt on this package, so that
8434            // we can avoid redundant dexopts, and also to make sure we've got the
8435            // code and package path correct.
8436            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8437                    pkg, true /* boot complete */);
8438        }
8439
8440        if (mFactoryTest && pkg.requestedPermissions.contains(
8441                android.Manifest.permission.FACTORY_TEST)) {
8442            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8443        }
8444
8445        ArrayList<PackageParser.Package> clientLibPkgs = null;
8446
8447        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8448            if (nonMutatedPs != null) {
8449                synchronized (mPackages) {
8450                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8451                }
8452            }
8453            return pkg;
8454        }
8455
8456        // Only privileged apps and updated privileged apps can add child packages.
8457        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8458            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8459                throw new PackageManagerException("Only privileged apps and updated "
8460                        + "privileged apps can add child packages. Ignoring package "
8461                        + pkg.packageName);
8462            }
8463            final int childCount = pkg.childPackages.size();
8464            for (int i = 0; i < childCount; i++) {
8465                PackageParser.Package childPkg = pkg.childPackages.get(i);
8466                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8467                        childPkg.packageName)) {
8468                    throw new PackageManagerException("Cannot override a child package of "
8469                            + "another disabled system app. Ignoring package " + pkg.packageName);
8470                }
8471            }
8472        }
8473
8474        // writer
8475        synchronized (mPackages) {
8476            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8477                // Only system apps can add new shared libraries.
8478                if (pkg.libraryNames != null) {
8479                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8480                        String name = pkg.libraryNames.get(i);
8481                        boolean allowed = false;
8482                        if (pkg.isUpdatedSystemApp()) {
8483                            // New library entries can only be added through the
8484                            // system image.  This is important to get rid of a lot
8485                            // of nasty edge cases: for example if we allowed a non-
8486                            // system update of the app to add a library, then uninstalling
8487                            // the update would make the library go away, and assumptions
8488                            // we made such as through app install filtering would now
8489                            // have allowed apps on the device which aren't compatible
8490                            // with it.  Better to just have the restriction here, be
8491                            // conservative, and create many fewer cases that can negatively
8492                            // impact the user experience.
8493                            final PackageSetting sysPs = mSettings
8494                                    .getDisabledSystemPkgLPr(pkg.packageName);
8495                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8496                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8497                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8498                                        allowed = true;
8499                                        break;
8500                                    }
8501                                }
8502                            }
8503                        } else {
8504                            allowed = true;
8505                        }
8506                        if (allowed) {
8507                            if (!mSharedLibraries.containsKey(name)) {
8508                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8509                            } else if (!name.equals(pkg.packageName)) {
8510                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8511                                        + name + " already exists; skipping");
8512                            }
8513                        } else {
8514                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8515                                    + name + " that is not declared on system image; skipping");
8516                        }
8517                    }
8518                    if ((scanFlags & SCAN_BOOTING) == 0) {
8519                        // If we are not booting, we need to update any applications
8520                        // that are clients of our shared library.  If we are booting,
8521                        // this will all be done once the scan is complete.
8522                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8523                    }
8524                }
8525            }
8526        }
8527
8528        if ((scanFlags & SCAN_BOOTING) != 0) {
8529            // No apps can run during boot scan, so they don't need to be frozen
8530        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8531            // Caller asked to not kill app, so it's probably not frozen
8532        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8533            // Caller asked us to ignore frozen check for some reason; they
8534            // probably didn't know the package name
8535        } else {
8536            // We're doing major surgery on this package, so it better be frozen
8537            // right now to keep it from launching
8538            checkPackageFrozen(pkgName);
8539        }
8540
8541        // Also need to kill any apps that are dependent on the library.
8542        if (clientLibPkgs != null) {
8543            for (int i=0; i<clientLibPkgs.size(); i++) {
8544                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8545                killApplication(clientPkg.applicationInfo.packageName,
8546                        clientPkg.applicationInfo.uid, "update lib");
8547            }
8548        }
8549
8550        // Make sure we're not adding any bogus keyset info
8551        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8552        ksms.assertScannedPackageValid(pkg);
8553
8554        // writer
8555        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8556
8557        boolean createIdmapFailed = false;
8558        synchronized (mPackages) {
8559            // We don't expect installation to fail beyond this point
8560
8561            // Add the new setting to mSettings
8562            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8563            // Add the new setting to mPackages
8564            mPackages.put(pkg.applicationInfo.packageName, pkg);
8565            // Make sure we don't accidentally delete its data.
8566            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8567            while (iter.hasNext()) {
8568                PackageCleanItem item = iter.next();
8569                if (pkgName.equals(item.packageName)) {
8570                    iter.remove();
8571                }
8572            }
8573
8574            // Take care of first install / last update times.
8575            if (currentTime != 0) {
8576                if (pkgSetting.firstInstallTime == 0) {
8577                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8578                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8579                    pkgSetting.lastUpdateTime = currentTime;
8580                }
8581            } else if (pkgSetting.firstInstallTime == 0) {
8582                // We need *something*.  Take time time stamp of the file.
8583                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8584            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8585                if (scanFileTime != pkgSetting.timeStamp) {
8586                    // A package on the system image has changed; consider this
8587                    // to be an update.
8588                    pkgSetting.lastUpdateTime = scanFileTime;
8589                }
8590            }
8591
8592            // Add the package's KeySets to the global KeySetManagerService
8593            ksms.addScannedPackageLPw(pkg);
8594
8595            int N = pkg.providers.size();
8596            StringBuilder r = null;
8597            int i;
8598            for (i=0; i<N; i++) {
8599                PackageParser.Provider p = pkg.providers.get(i);
8600                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8601                        p.info.processName, pkg.applicationInfo.uid);
8602                mProviders.addProvider(p);
8603                p.syncable = p.info.isSyncable;
8604                if (p.info.authority != null) {
8605                    String names[] = p.info.authority.split(";");
8606                    p.info.authority = null;
8607                    for (int j = 0; j < names.length; j++) {
8608                        if (j == 1 && p.syncable) {
8609                            // We only want the first authority for a provider to possibly be
8610                            // syncable, so if we already added this provider using a different
8611                            // authority clear the syncable flag. We copy the provider before
8612                            // changing it because the mProviders object contains a reference
8613                            // to a provider that we don't want to change.
8614                            // Only do this for the second authority since the resulting provider
8615                            // object can be the same for all future authorities for this provider.
8616                            p = new PackageParser.Provider(p);
8617                            p.syncable = false;
8618                        }
8619                        if (!mProvidersByAuthority.containsKey(names[j])) {
8620                            mProvidersByAuthority.put(names[j], p);
8621                            if (p.info.authority == null) {
8622                                p.info.authority = names[j];
8623                            } else {
8624                                p.info.authority = p.info.authority + ";" + names[j];
8625                            }
8626                            if (DEBUG_PACKAGE_SCANNING) {
8627                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8628                                    Log.d(TAG, "Registered content provider: " + names[j]
8629                                            + ", className = " + p.info.name + ", isSyncable = "
8630                                            + p.info.isSyncable);
8631                            }
8632                        } else {
8633                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8634                            Slog.w(TAG, "Skipping provider name " + names[j] +
8635                                    " (in package " + pkg.applicationInfo.packageName +
8636                                    "): name already used by "
8637                                    + ((other != null && other.getComponentName() != null)
8638                                            ? other.getComponentName().getPackageName() : "?"));
8639                        }
8640                    }
8641                }
8642                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8643                    if (r == null) {
8644                        r = new StringBuilder(256);
8645                    } else {
8646                        r.append(' ');
8647                    }
8648                    r.append(p.info.name);
8649                }
8650            }
8651            if (r != null) {
8652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8653            }
8654
8655            N = pkg.services.size();
8656            r = null;
8657            for (i=0; i<N; i++) {
8658                PackageParser.Service s = pkg.services.get(i);
8659                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8660                        s.info.processName, pkg.applicationInfo.uid);
8661                mServices.addService(s);
8662                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8663                    if (r == null) {
8664                        r = new StringBuilder(256);
8665                    } else {
8666                        r.append(' ');
8667                    }
8668                    r.append(s.info.name);
8669                }
8670            }
8671            if (r != null) {
8672                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8673            }
8674
8675            N = pkg.receivers.size();
8676            r = null;
8677            for (i=0; i<N; i++) {
8678                PackageParser.Activity a = pkg.receivers.get(i);
8679                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8680                        a.info.processName, pkg.applicationInfo.uid);
8681                mReceivers.addActivity(a, "receiver");
8682                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8683                    if (r == null) {
8684                        r = new StringBuilder(256);
8685                    } else {
8686                        r.append(' ');
8687                    }
8688                    r.append(a.info.name);
8689                }
8690            }
8691            if (r != null) {
8692                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8693            }
8694
8695            N = pkg.activities.size();
8696            r = null;
8697            for (i=0; i<N; i++) {
8698                PackageParser.Activity a = pkg.activities.get(i);
8699                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8700                        a.info.processName, pkg.applicationInfo.uid);
8701                mActivities.addActivity(a, "activity");
8702                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8703                    if (r == null) {
8704                        r = new StringBuilder(256);
8705                    } else {
8706                        r.append(' ');
8707                    }
8708                    r.append(a.info.name);
8709                }
8710            }
8711            if (r != null) {
8712                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8713            }
8714
8715            N = pkg.permissionGroups.size();
8716            r = null;
8717            for (i=0; i<N; i++) {
8718                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8719                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8720                if (cur == null) {
8721                    mPermissionGroups.put(pg.info.name, pg);
8722                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8723                        if (r == null) {
8724                            r = new StringBuilder(256);
8725                        } else {
8726                            r.append(' ');
8727                        }
8728                        r.append(pg.info.name);
8729                    }
8730                } else {
8731                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8732                            + pg.info.packageName + " ignored: original from "
8733                            + cur.info.packageName);
8734                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8735                        if (r == null) {
8736                            r = new StringBuilder(256);
8737                        } else {
8738                            r.append(' ');
8739                        }
8740                        r.append("DUP:");
8741                        r.append(pg.info.name);
8742                    }
8743                }
8744            }
8745            if (r != null) {
8746                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8747            }
8748
8749            N = pkg.permissions.size();
8750            r = null;
8751            for (i=0; i<N; i++) {
8752                PackageParser.Permission p = pkg.permissions.get(i);
8753
8754                // Assume by default that we did not install this permission into the system.
8755                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8756
8757                // Now that permission groups have a special meaning, we ignore permission
8758                // groups for legacy apps to prevent unexpected behavior. In particular,
8759                // permissions for one app being granted to someone just becase they happen
8760                // to be in a group defined by another app (before this had no implications).
8761                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8762                    p.group = mPermissionGroups.get(p.info.group);
8763                    // Warn for a permission in an unknown group.
8764                    if (p.info.group != null && p.group == null) {
8765                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8766                                + p.info.packageName + " in an unknown group " + p.info.group);
8767                    }
8768                }
8769
8770                ArrayMap<String, BasePermission> permissionMap =
8771                        p.tree ? mSettings.mPermissionTrees
8772                                : mSettings.mPermissions;
8773                BasePermission bp = permissionMap.get(p.info.name);
8774
8775                // Allow system apps to redefine non-system permissions
8776                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8777                    final boolean currentOwnerIsSystem = (bp.perm != null
8778                            && isSystemApp(bp.perm.owner));
8779                    if (isSystemApp(p.owner)) {
8780                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8781                            // It's a built-in permission and no owner, take ownership now
8782                            bp.packageSetting = pkgSetting;
8783                            bp.perm = p;
8784                            bp.uid = pkg.applicationInfo.uid;
8785                            bp.sourcePackage = p.info.packageName;
8786                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8787                        } else if (!currentOwnerIsSystem) {
8788                            String msg = "New decl " + p.owner + " of permission  "
8789                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8790                            reportSettingsProblem(Log.WARN, msg);
8791                            bp = null;
8792                        }
8793                    }
8794                }
8795
8796                if (bp == null) {
8797                    bp = new BasePermission(p.info.name, p.info.packageName,
8798                            BasePermission.TYPE_NORMAL);
8799                    permissionMap.put(p.info.name, bp);
8800                }
8801
8802                if (bp.perm == null) {
8803                    if (bp.sourcePackage == null
8804                            || bp.sourcePackage.equals(p.info.packageName)) {
8805                        BasePermission tree = findPermissionTreeLP(p.info.name);
8806                        if (tree == null
8807                                || tree.sourcePackage.equals(p.info.packageName)) {
8808                            bp.packageSetting = pkgSetting;
8809                            bp.perm = p;
8810                            bp.uid = pkg.applicationInfo.uid;
8811                            bp.sourcePackage = p.info.packageName;
8812                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8813                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8814                                if (r == null) {
8815                                    r = new StringBuilder(256);
8816                                } else {
8817                                    r.append(' ');
8818                                }
8819                                r.append(p.info.name);
8820                            }
8821                        } else {
8822                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8823                                    + p.info.packageName + " ignored: base tree "
8824                                    + tree.name + " is from package "
8825                                    + tree.sourcePackage);
8826                        }
8827                    } else {
8828                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8829                                + p.info.packageName + " ignored: original from "
8830                                + bp.sourcePackage);
8831                    }
8832                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8833                    if (r == null) {
8834                        r = new StringBuilder(256);
8835                    } else {
8836                        r.append(' ');
8837                    }
8838                    r.append("DUP:");
8839                    r.append(p.info.name);
8840                }
8841                if (bp.perm == p) {
8842                    bp.protectionLevel = p.info.protectionLevel;
8843                }
8844            }
8845
8846            if (r != null) {
8847                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8848            }
8849
8850            N = pkg.instrumentation.size();
8851            r = null;
8852            for (i=0; i<N; i++) {
8853                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8854                a.info.packageName = pkg.applicationInfo.packageName;
8855                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8856                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8857                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8858                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8859                a.info.dataDir = pkg.applicationInfo.dataDir;
8860                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8861                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8862
8863                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8864                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8865                mInstrumentation.put(a.getComponentName(), a);
8866                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8867                    if (r == null) {
8868                        r = new StringBuilder(256);
8869                    } else {
8870                        r.append(' ');
8871                    }
8872                    r.append(a.info.name);
8873                }
8874            }
8875            if (r != null) {
8876                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8877            }
8878
8879            if (pkg.protectedBroadcasts != null) {
8880                N = pkg.protectedBroadcasts.size();
8881                for (i=0; i<N; i++) {
8882                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8883                }
8884            }
8885
8886            pkgSetting.setTimeStamp(scanFileTime);
8887
8888            // Create idmap files for pairs of (packages, overlay packages).
8889            // Note: "android", ie framework-res.apk, is handled by native layers.
8890            if (pkg.mOverlayTarget != null) {
8891                // This is an overlay package.
8892                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8893                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8894                        mOverlays.put(pkg.mOverlayTarget,
8895                                new ArrayMap<String, PackageParser.Package>());
8896                    }
8897                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8898                    map.put(pkg.packageName, pkg);
8899                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8900                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8901                        createIdmapFailed = true;
8902                    }
8903                }
8904            } else if (mOverlays.containsKey(pkg.packageName) &&
8905                    !pkg.packageName.equals("android")) {
8906                // This is a regular package, with one or more known overlay packages.
8907                createIdmapsForPackageLI(pkg);
8908            }
8909        }
8910
8911        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8912
8913        if (createIdmapFailed) {
8914            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8915                    "scanPackageLI failed to createIdmap");
8916        }
8917        return pkg;
8918    }
8919
8920    /**
8921     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8922     * is derived purely on the basis of the contents of {@code scanFile} and
8923     * {@code cpuAbiOverride}.
8924     *
8925     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8926     */
8927    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8928                                 String cpuAbiOverride, boolean extractLibs)
8929            throws PackageManagerException {
8930        // TODO: We can probably be smarter about this stuff. For installed apps,
8931        // we can calculate this information at install time once and for all. For
8932        // system apps, we can probably assume that this information doesn't change
8933        // after the first boot scan. As things stand, we do lots of unnecessary work.
8934
8935        // Give ourselves some initial paths; we'll come back for another
8936        // pass once we've determined ABI below.
8937        setNativeLibraryPaths(pkg);
8938
8939        // We would never need to extract libs for forward-locked and external packages,
8940        // since the container service will do it for us. We shouldn't attempt to
8941        // extract libs from system app when it was not updated.
8942        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8943                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8944            extractLibs = false;
8945        }
8946
8947        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8948        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8949
8950        NativeLibraryHelper.Handle handle = null;
8951        try {
8952            handle = NativeLibraryHelper.Handle.create(pkg);
8953            // TODO(multiArch): This can be null for apps that didn't go through the
8954            // usual installation process. We can calculate it again, like we
8955            // do during install time.
8956            //
8957            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8958            // unnecessary.
8959            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8960
8961            // Null out the abis so that they can be recalculated.
8962            pkg.applicationInfo.primaryCpuAbi = null;
8963            pkg.applicationInfo.secondaryCpuAbi = null;
8964            if (isMultiArch(pkg.applicationInfo)) {
8965                // Warn if we've set an abiOverride for multi-lib packages..
8966                // By definition, we need to copy both 32 and 64 bit libraries for
8967                // such packages.
8968                if (pkg.cpuAbiOverride != null
8969                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8970                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8971                }
8972
8973                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8974                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8975                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8976                    if (extractLibs) {
8977                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8978                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8979                                useIsaSpecificSubdirs);
8980                    } else {
8981                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8982                    }
8983                }
8984
8985                maybeThrowExceptionForMultiArchCopy(
8986                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8987
8988                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8989                    if (extractLibs) {
8990                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8991                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8992                                useIsaSpecificSubdirs);
8993                    } else {
8994                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8995                    }
8996                }
8997
8998                maybeThrowExceptionForMultiArchCopy(
8999                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9000
9001                if (abi64 >= 0) {
9002                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9003                }
9004
9005                if (abi32 >= 0) {
9006                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9007                    if (abi64 >= 0) {
9008                        if (pkg.use32bitAbi) {
9009                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9010                            pkg.applicationInfo.primaryCpuAbi = abi;
9011                        } else {
9012                            pkg.applicationInfo.secondaryCpuAbi = abi;
9013                        }
9014                    } else {
9015                        pkg.applicationInfo.primaryCpuAbi = abi;
9016                    }
9017                }
9018
9019            } else {
9020                String[] abiList = (cpuAbiOverride != null) ?
9021                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9022
9023                // Enable gross and lame hacks for apps that are built with old
9024                // SDK tools. We must scan their APKs for renderscript bitcode and
9025                // not launch them if it's present. Don't bother checking on devices
9026                // that don't have 64 bit support.
9027                boolean needsRenderScriptOverride = false;
9028                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9029                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9030                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9031                    needsRenderScriptOverride = true;
9032                }
9033
9034                final int copyRet;
9035                if (extractLibs) {
9036                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9037                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9038                } else {
9039                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9040                }
9041
9042                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9043                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9044                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9045                }
9046
9047                if (copyRet >= 0) {
9048                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9049                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9050                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9051                } else if (needsRenderScriptOverride) {
9052                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9053                }
9054            }
9055        } catch (IOException ioe) {
9056            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9057        } finally {
9058            IoUtils.closeQuietly(handle);
9059        }
9060
9061        // Now that we've calculated the ABIs and determined if it's an internal app,
9062        // we will go ahead and populate the nativeLibraryPath.
9063        setNativeLibraryPaths(pkg);
9064    }
9065
9066    /**
9067     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9068     * i.e, so that all packages can be run inside a single process if required.
9069     *
9070     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9071     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9072     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9073     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9074     * updating a package that belongs to a shared user.
9075     *
9076     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9077     * adds unnecessary complexity.
9078     */
9079    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9080            PackageParser.Package scannedPackage, boolean bootComplete) {
9081        String requiredInstructionSet = null;
9082        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9083            requiredInstructionSet = VMRuntime.getInstructionSet(
9084                     scannedPackage.applicationInfo.primaryCpuAbi);
9085        }
9086
9087        PackageSetting requirer = null;
9088        for (PackageSetting ps : packagesForUser) {
9089            // If packagesForUser contains scannedPackage, we skip it. This will happen
9090            // when scannedPackage is an update of an existing package. Without this check,
9091            // we will never be able to change the ABI of any package belonging to a shared
9092            // user, even if it's compatible with other packages.
9093            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9094                if (ps.primaryCpuAbiString == null) {
9095                    continue;
9096                }
9097
9098                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9099                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9100                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9101                    // this but there's not much we can do.
9102                    String errorMessage = "Instruction set mismatch, "
9103                            + ((requirer == null) ? "[caller]" : requirer)
9104                            + " requires " + requiredInstructionSet + " whereas " + ps
9105                            + " requires " + instructionSet;
9106                    Slog.w(TAG, errorMessage);
9107                }
9108
9109                if (requiredInstructionSet == null) {
9110                    requiredInstructionSet = instructionSet;
9111                    requirer = ps;
9112                }
9113            }
9114        }
9115
9116        if (requiredInstructionSet != null) {
9117            String adjustedAbi;
9118            if (requirer != null) {
9119                // requirer != null implies that either scannedPackage was null or that scannedPackage
9120                // did not require an ABI, in which case we have to adjust scannedPackage to match
9121                // the ABI of the set (which is the same as requirer's ABI)
9122                adjustedAbi = requirer.primaryCpuAbiString;
9123                if (scannedPackage != null) {
9124                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9125                }
9126            } else {
9127                // requirer == null implies that we're updating all ABIs in the set to
9128                // match scannedPackage.
9129                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9130            }
9131
9132            for (PackageSetting ps : packagesForUser) {
9133                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9134                    if (ps.primaryCpuAbiString != null) {
9135                        continue;
9136                    }
9137
9138                    ps.primaryCpuAbiString = adjustedAbi;
9139                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9140                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9141                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9142                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9143                                + " (requirer="
9144                                + (requirer == null ? "null" : requirer.pkg.packageName)
9145                                + ", scannedPackage="
9146                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9147                                + ")");
9148                        try {
9149                            mInstaller.rmdex(ps.codePathString,
9150                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9151                        } catch (InstallerException ignored) {
9152                        }
9153                    }
9154                }
9155            }
9156        }
9157    }
9158
9159    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9160        synchronized (mPackages) {
9161            mResolverReplaced = true;
9162            // Set up information for custom user intent resolution activity.
9163            mResolveActivity.applicationInfo = pkg.applicationInfo;
9164            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9165            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9166            mResolveActivity.processName = pkg.applicationInfo.packageName;
9167            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9168            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9169                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9170            mResolveActivity.theme = 0;
9171            mResolveActivity.exported = true;
9172            mResolveActivity.enabled = true;
9173            mResolveInfo.activityInfo = mResolveActivity;
9174            mResolveInfo.priority = 0;
9175            mResolveInfo.preferredOrder = 0;
9176            mResolveInfo.match = 0;
9177            mResolveComponentName = mCustomResolverComponentName;
9178            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9179                    mResolveComponentName);
9180        }
9181    }
9182
9183    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9184        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9185
9186        // Set up information for ephemeral installer activity
9187        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9188        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9189        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9190        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9191        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9192        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9193                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9194        mEphemeralInstallerActivity.theme = 0;
9195        mEphemeralInstallerActivity.exported = true;
9196        mEphemeralInstallerActivity.enabled = true;
9197        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9198        mEphemeralInstallerInfo.priority = 0;
9199        mEphemeralInstallerInfo.preferredOrder = 0;
9200        mEphemeralInstallerInfo.match = 0;
9201
9202        if (DEBUG_EPHEMERAL) {
9203            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9204        }
9205    }
9206
9207    private static String calculateBundledApkRoot(final String codePathString) {
9208        final File codePath = new File(codePathString);
9209        final File codeRoot;
9210        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9211            codeRoot = Environment.getRootDirectory();
9212        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9213            codeRoot = Environment.getOemDirectory();
9214        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9215            codeRoot = Environment.getVendorDirectory();
9216        } else {
9217            // Unrecognized code path; take its top real segment as the apk root:
9218            // e.g. /something/app/blah.apk => /something
9219            try {
9220                File f = codePath.getCanonicalFile();
9221                File parent = f.getParentFile();    // non-null because codePath is a file
9222                File tmp;
9223                while ((tmp = parent.getParentFile()) != null) {
9224                    f = parent;
9225                    parent = tmp;
9226                }
9227                codeRoot = f;
9228                Slog.w(TAG, "Unrecognized code path "
9229                        + codePath + " - using " + codeRoot);
9230            } catch (IOException e) {
9231                // Can't canonicalize the code path -- shenanigans?
9232                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9233                return Environment.getRootDirectory().getPath();
9234            }
9235        }
9236        return codeRoot.getPath();
9237    }
9238
9239    /**
9240     * Derive and set the location of native libraries for the given package,
9241     * which varies depending on where and how the package was installed.
9242     */
9243    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9244        final ApplicationInfo info = pkg.applicationInfo;
9245        final String codePath = pkg.codePath;
9246        final File codeFile = new File(codePath);
9247        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9248        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9249
9250        info.nativeLibraryRootDir = null;
9251        info.nativeLibraryRootRequiresIsa = false;
9252        info.nativeLibraryDir = null;
9253        info.secondaryNativeLibraryDir = null;
9254
9255        if (isApkFile(codeFile)) {
9256            // Monolithic install
9257            if (bundledApp) {
9258                // If "/system/lib64/apkname" exists, assume that is the per-package
9259                // native library directory to use; otherwise use "/system/lib/apkname".
9260                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9261                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9262                        getPrimaryInstructionSet(info));
9263
9264                // This is a bundled system app so choose the path based on the ABI.
9265                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9266                // is just the default path.
9267                final String apkName = deriveCodePathName(codePath);
9268                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9269                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9270                        apkName).getAbsolutePath();
9271
9272                if (info.secondaryCpuAbi != null) {
9273                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9274                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9275                            secondaryLibDir, apkName).getAbsolutePath();
9276                }
9277            } else if (asecApp) {
9278                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9279                        .getAbsolutePath();
9280            } else {
9281                final String apkName = deriveCodePathName(codePath);
9282                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9283                        .getAbsolutePath();
9284            }
9285
9286            info.nativeLibraryRootRequiresIsa = false;
9287            info.nativeLibraryDir = info.nativeLibraryRootDir;
9288        } else {
9289            // Cluster install
9290            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9291            info.nativeLibraryRootRequiresIsa = true;
9292
9293            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9294                    getPrimaryInstructionSet(info)).getAbsolutePath();
9295
9296            if (info.secondaryCpuAbi != null) {
9297                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9298                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9299            }
9300        }
9301    }
9302
9303    /**
9304     * Calculate the abis and roots for a bundled app. These can uniquely
9305     * be determined from the contents of the system partition, i.e whether
9306     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9307     * of this information, and instead assume that the system was built
9308     * sensibly.
9309     */
9310    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9311                                           PackageSetting pkgSetting) {
9312        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9313
9314        // If "/system/lib64/apkname" exists, assume that is the per-package
9315        // native library directory to use; otherwise use "/system/lib/apkname".
9316        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9317        setBundledAppAbi(pkg, apkRoot, apkName);
9318        // pkgSetting might be null during rescan following uninstall of updates
9319        // to a bundled app, so accommodate that possibility.  The settings in
9320        // that case will be established later from the parsed package.
9321        //
9322        // If the settings aren't null, sync them up with what we've just derived.
9323        // note that apkRoot isn't stored in the package settings.
9324        if (pkgSetting != null) {
9325            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9326            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9327        }
9328    }
9329
9330    /**
9331     * Deduces the ABI of a bundled app and sets the relevant fields on the
9332     * parsed pkg object.
9333     *
9334     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9335     *        under which system libraries are installed.
9336     * @param apkName the name of the installed package.
9337     */
9338    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9339        final File codeFile = new File(pkg.codePath);
9340
9341        final boolean has64BitLibs;
9342        final boolean has32BitLibs;
9343        if (isApkFile(codeFile)) {
9344            // Monolithic install
9345            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9346            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9347        } else {
9348            // Cluster install
9349            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9350            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9351                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9352                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9353                has64BitLibs = (new File(rootDir, isa)).exists();
9354            } else {
9355                has64BitLibs = false;
9356            }
9357            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9358                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9359                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9360                has32BitLibs = (new File(rootDir, isa)).exists();
9361            } else {
9362                has32BitLibs = false;
9363            }
9364        }
9365
9366        if (has64BitLibs && !has32BitLibs) {
9367            // The package has 64 bit libs, but not 32 bit libs. Its primary
9368            // ABI should be 64 bit. We can safely assume here that the bundled
9369            // native libraries correspond to the most preferred ABI in the list.
9370
9371            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9372            pkg.applicationInfo.secondaryCpuAbi = null;
9373        } else if (has32BitLibs && !has64BitLibs) {
9374            // The package has 32 bit libs but not 64 bit libs. Its primary
9375            // ABI should be 32 bit.
9376
9377            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9378            pkg.applicationInfo.secondaryCpuAbi = null;
9379        } else if (has32BitLibs && has64BitLibs) {
9380            // The application has both 64 and 32 bit bundled libraries. We check
9381            // here that the app declares multiArch support, and warn if it doesn't.
9382            //
9383            // We will be lenient here and record both ABIs. The primary will be the
9384            // ABI that's higher on the list, i.e, a device that's configured to prefer
9385            // 64 bit apps will see a 64 bit primary ABI,
9386
9387            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9388                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9389            }
9390
9391            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9392                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9393                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9394            } else {
9395                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9396                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9397            }
9398        } else {
9399            pkg.applicationInfo.primaryCpuAbi = null;
9400            pkg.applicationInfo.secondaryCpuAbi = null;
9401        }
9402    }
9403
9404    private void killApplication(String pkgName, int appId, String reason) {
9405        // Request the ActivityManager to kill the process(only for existing packages)
9406        // so that we do not end up in a confused state while the user is still using the older
9407        // version of the application while the new one gets installed.
9408        final long token = Binder.clearCallingIdentity();
9409        try {
9410            IActivityManager am = ActivityManagerNative.getDefault();
9411            if (am != null) {
9412                try {
9413                    am.killApplicationWithAppId(pkgName, appId, reason);
9414                } catch (RemoteException e) {
9415                }
9416            }
9417        } finally {
9418            Binder.restoreCallingIdentity(token);
9419        }
9420    }
9421
9422    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9423        // Remove the parent package setting
9424        PackageSetting ps = (PackageSetting) pkg.mExtras;
9425        if (ps != null) {
9426            removePackageLI(ps, chatty);
9427        }
9428        // Remove the child package setting
9429        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9430        for (int i = 0; i < childCount; i++) {
9431            PackageParser.Package childPkg = pkg.childPackages.get(i);
9432            ps = (PackageSetting) childPkg.mExtras;
9433            if (ps != null) {
9434                removePackageLI(ps, chatty);
9435            }
9436        }
9437    }
9438
9439    void removePackageLI(PackageSetting ps, boolean chatty) {
9440        if (DEBUG_INSTALL) {
9441            if (chatty)
9442                Log.d(TAG, "Removing package " + ps.name);
9443        }
9444
9445        // writer
9446        synchronized (mPackages) {
9447            mPackages.remove(ps.name);
9448            final PackageParser.Package pkg = ps.pkg;
9449            if (pkg != null) {
9450                cleanPackageDataStructuresLILPw(pkg, chatty);
9451            }
9452        }
9453    }
9454
9455    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9456        if (DEBUG_INSTALL) {
9457            if (chatty)
9458                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9459        }
9460
9461        // writer
9462        synchronized (mPackages) {
9463            // Remove the parent package
9464            mPackages.remove(pkg.applicationInfo.packageName);
9465            cleanPackageDataStructuresLILPw(pkg, chatty);
9466
9467            // Remove the child packages
9468            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9469            for (int i = 0; i < childCount; i++) {
9470                PackageParser.Package childPkg = pkg.childPackages.get(i);
9471                mPackages.remove(childPkg.applicationInfo.packageName);
9472                cleanPackageDataStructuresLILPw(childPkg, chatty);
9473            }
9474        }
9475    }
9476
9477    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9478        int N = pkg.providers.size();
9479        StringBuilder r = null;
9480        int i;
9481        for (i=0; i<N; i++) {
9482            PackageParser.Provider p = pkg.providers.get(i);
9483            mProviders.removeProvider(p);
9484            if (p.info.authority == null) {
9485
9486                /* There was another ContentProvider with this authority when
9487                 * this app was installed so this authority is null,
9488                 * Ignore it as we don't have to unregister the provider.
9489                 */
9490                continue;
9491            }
9492            String names[] = p.info.authority.split(";");
9493            for (int j = 0; j < names.length; j++) {
9494                if (mProvidersByAuthority.get(names[j]) == p) {
9495                    mProvidersByAuthority.remove(names[j]);
9496                    if (DEBUG_REMOVE) {
9497                        if (chatty)
9498                            Log.d(TAG, "Unregistered content provider: " + names[j]
9499                                    + ", className = " + p.info.name + ", isSyncable = "
9500                                    + p.info.isSyncable);
9501                    }
9502                }
9503            }
9504            if (DEBUG_REMOVE && chatty) {
9505                if (r == null) {
9506                    r = new StringBuilder(256);
9507                } else {
9508                    r.append(' ');
9509                }
9510                r.append(p.info.name);
9511            }
9512        }
9513        if (r != null) {
9514            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9515        }
9516
9517        N = pkg.services.size();
9518        r = null;
9519        for (i=0; i<N; i++) {
9520            PackageParser.Service s = pkg.services.get(i);
9521            mServices.removeService(s);
9522            if (chatty) {
9523                if (r == null) {
9524                    r = new StringBuilder(256);
9525                } else {
9526                    r.append(' ');
9527                }
9528                r.append(s.info.name);
9529            }
9530        }
9531        if (r != null) {
9532            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9533        }
9534
9535        N = pkg.receivers.size();
9536        r = null;
9537        for (i=0; i<N; i++) {
9538            PackageParser.Activity a = pkg.receivers.get(i);
9539            mReceivers.removeActivity(a, "receiver");
9540            if (DEBUG_REMOVE && chatty) {
9541                if (r == null) {
9542                    r = new StringBuilder(256);
9543                } else {
9544                    r.append(' ');
9545                }
9546                r.append(a.info.name);
9547            }
9548        }
9549        if (r != null) {
9550            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9551        }
9552
9553        N = pkg.activities.size();
9554        r = null;
9555        for (i=0; i<N; i++) {
9556            PackageParser.Activity a = pkg.activities.get(i);
9557            mActivities.removeActivity(a, "activity");
9558            if (DEBUG_REMOVE && chatty) {
9559                if (r == null) {
9560                    r = new StringBuilder(256);
9561                } else {
9562                    r.append(' ');
9563                }
9564                r.append(a.info.name);
9565            }
9566        }
9567        if (r != null) {
9568            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9569        }
9570
9571        N = pkg.permissions.size();
9572        r = null;
9573        for (i=0; i<N; i++) {
9574            PackageParser.Permission p = pkg.permissions.get(i);
9575            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9576            if (bp == null) {
9577                bp = mSettings.mPermissionTrees.get(p.info.name);
9578            }
9579            if (bp != null && bp.perm == p) {
9580                bp.perm = null;
9581                if (DEBUG_REMOVE && chatty) {
9582                    if (r == null) {
9583                        r = new StringBuilder(256);
9584                    } else {
9585                        r.append(' ');
9586                    }
9587                    r.append(p.info.name);
9588                }
9589            }
9590            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9591                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9592                if (appOpPkgs != null) {
9593                    appOpPkgs.remove(pkg.packageName);
9594                }
9595            }
9596        }
9597        if (r != null) {
9598            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9599        }
9600
9601        N = pkg.requestedPermissions.size();
9602        r = null;
9603        for (i=0; i<N; i++) {
9604            String perm = pkg.requestedPermissions.get(i);
9605            BasePermission bp = mSettings.mPermissions.get(perm);
9606            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9607                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9608                if (appOpPkgs != null) {
9609                    appOpPkgs.remove(pkg.packageName);
9610                    if (appOpPkgs.isEmpty()) {
9611                        mAppOpPermissionPackages.remove(perm);
9612                    }
9613                }
9614            }
9615        }
9616        if (r != null) {
9617            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9618        }
9619
9620        N = pkg.instrumentation.size();
9621        r = null;
9622        for (i=0; i<N; i++) {
9623            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9624            mInstrumentation.remove(a.getComponentName());
9625            if (DEBUG_REMOVE && chatty) {
9626                if (r == null) {
9627                    r = new StringBuilder(256);
9628                } else {
9629                    r.append(' ');
9630                }
9631                r.append(a.info.name);
9632            }
9633        }
9634        if (r != null) {
9635            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9636        }
9637
9638        r = null;
9639        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9640            // Only system apps can hold shared libraries.
9641            if (pkg.libraryNames != null) {
9642                for (i=0; i<pkg.libraryNames.size(); i++) {
9643                    String name = pkg.libraryNames.get(i);
9644                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9645                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9646                        mSharedLibraries.remove(name);
9647                        if (DEBUG_REMOVE && chatty) {
9648                            if (r == null) {
9649                                r = new StringBuilder(256);
9650                            } else {
9651                                r.append(' ');
9652                            }
9653                            r.append(name);
9654                        }
9655                    }
9656                }
9657            }
9658        }
9659        if (r != null) {
9660            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9661        }
9662    }
9663
9664    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9665        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9666            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9667                return true;
9668            }
9669        }
9670        return false;
9671    }
9672
9673    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9674    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9675    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9676
9677    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9678        // Update the parent permissions
9679        updatePermissionsLPw(pkg.packageName, pkg, flags);
9680        // Update the child permissions
9681        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9682        for (int i = 0; i < childCount; i++) {
9683            PackageParser.Package childPkg = pkg.childPackages.get(i);
9684            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9685        }
9686    }
9687
9688    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9689            int flags) {
9690        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9691        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9692    }
9693
9694    private void updatePermissionsLPw(String changingPkg,
9695            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9696        // Make sure there are no dangling permission trees.
9697        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9698        while (it.hasNext()) {
9699            final BasePermission bp = it.next();
9700            if (bp.packageSetting == null) {
9701                // We may not yet have parsed the package, so just see if
9702                // we still know about its settings.
9703                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9704            }
9705            if (bp.packageSetting == null) {
9706                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9707                        + " from package " + bp.sourcePackage);
9708                it.remove();
9709            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9710                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9711                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9712                            + " from package " + bp.sourcePackage);
9713                    flags |= UPDATE_PERMISSIONS_ALL;
9714                    it.remove();
9715                }
9716            }
9717        }
9718
9719        // Make sure all dynamic permissions have been assigned to a package,
9720        // and make sure there are no dangling permissions.
9721        it = mSettings.mPermissions.values().iterator();
9722        while (it.hasNext()) {
9723            final BasePermission bp = it.next();
9724            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9725                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9726                        + bp.name + " pkg=" + bp.sourcePackage
9727                        + " info=" + bp.pendingInfo);
9728                if (bp.packageSetting == null && bp.pendingInfo != null) {
9729                    final BasePermission tree = findPermissionTreeLP(bp.name);
9730                    if (tree != null && tree.perm != null) {
9731                        bp.packageSetting = tree.packageSetting;
9732                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9733                                new PermissionInfo(bp.pendingInfo));
9734                        bp.perm.info.packageName = tree.perm.info.packageName;
9735                        bp.perm.info.name = bp.name;
9736                        bp.uid = tree.uid;
9737                    }
9738                }
9739            }
9740            if (bp.packageSetting == null) {
9741                // We may not yet have parsed the package, so just see if
9742                // we still know about its settings.
9743                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9744            }
9745            if (bp.packageSetting == null) {
9746                Slog.w(TAG, "Removing dangling permission: " + bp.name
9747                        + " from package " + bp.sourcePackage);
9748                it.remove();
9749            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9750                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9751                    Slog.i(TAG, "Removing old permission: " + bp.name
9752                            + " from package " + bp.sourcePackage);
9753                    flags |= UPDATE_PERMISSIONS_ALL;
9754                    it.remove();
9755                }
9756            }
9757        }
9758
9759        // Now update the permissions for all packages, in particular
9760        // replace the granted permissions of the system packages.
9761        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9762            for (PackageParser.Package pkg : mPackages.values()) {
9763                if (pkg != pkgInfo) {
9764                    // Only replace for packages on requested volume
9765                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9766                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9767                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9768                    grantPermissionsLPw(pkg, replace, changingPkg);
9769                }
9770            }
9771        }
9772
9773        if (pkgInfo != null) {
9774            // Only replace for packages on requested volume
9775            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9776            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9777                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9778            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9779        }
9780    }
9781
9782    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9783            String packageOfInterest) {
9784        // IMPORTANT: There are two types of permissions: install and runtime.
9785        // Install time permissions are granted when the app is installed to
9786        // all device users and users added in the future. Runtime permissions
9787        // are granted at runtime explicitly to specific users. Normal and signature
9788        // protected permissions are install time permissions. Dangerous permissions
9789        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9790        // otherwise they are runtime permissions. This function does not manage
9791        // runtime permissions except for the case an app targeting Lollipop MR1
9792        // being upgraded to target a newer SDK, in which case dangerous permissions
9793        // are transformed from install time to runtime ones.
9794
9795        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9796        if (ps == null) {
9797            return;
9798        }
9799
9800        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9801
9802        PermissionsState permissionsState = ps.getPermissionsState();
9803        PermissionsState origPermissions = permissionsState;
9804
9805        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9806
9807        boolean runtimePermissionsRevoked = false;
9808        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9809
9810        boolean changedInstallPermission = false;
9811
9812        if (replace) {
9813            ps.installPermissionsFixed = false;
9814            if (!ps.isSharedUser()) {
9815                origPermissions = new PermissionsState(permissionsState);
9816                permissionsState.reset();
9817            } else {
9818                // We need to know only about runtime permission changes since the
9819                // calling code always writes the install permissions state but
9820                // the runtime ones are written only if changed. The only cases of
9821                // changed runtime permissions here are promotion of an install to
9822                // runtime and revocation of a runtime from a shared user.
9823                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9824                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9825                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9826                    runtimePermissionsRevoked = true;
9827                }
9828            }
9829        }
9830
9831        permissionsState.setGlobalGids(mGlobalGids);
9832
9833        final int N = pkg.requestedPermissions.size();
9834        for (int i=0; i<N; i++) {
9835            final String name = pkg.requestedPermissions.get(i);
9836            final BasePermission bp = mSettings.mPermissions.get(name);
9837
9838            if (DEBUG_INSTALL) {
9839                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9840            }
9841
9842            if (bp == null || bp.packageSetting == null) {
9843                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9844                    Slog.w(TAG, "Unknown permission " + name
9845                            + " in package " + pkg.packageName);
9846                }
9847                continue;
9848            }
9849
9850            final String perm = bp.name;
9851            boolean allowedSig = false;
9852            int grant = GRANT_DENIED;
9853
9854            // Keep track of app op permissions.
9855            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9856                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9857                if (pkgs == null) {
9858                    pkgs = new ArraySet<>();
9859                    mAppOpPermissionPackages.put(bp.name, pkgs);
9860                }
9861                pkgs.add(pkg.packageName);
9862            }
9863
9864            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9865            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9866                    >= Build.VERSION_CODES.M;
9867            switch (level) {
9868                case PermissionInfo.PROTECTION_NORMAL: {
9869                    // For all apps normal permissions are install time ones.
9870                    grant = GRANT_INSTALL;
9871                } break;
9872
9873                case PermissionInfo.PROTECTION_DANGEROUS: {
9874                    // If a permission review is required for legacy apps we represent
9875                    // their permissions as always granted runtime ones since we need
9876                    // to keep the review required permission flag per user while an
9877                    // install permission's state is shared across all users.
9878                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9879                        // For legacy apps dangerous permissions are install time ones.
9880                        grant = GRANT_INSTALL;
9881                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9882                        // For legacy apps that became modern, install becomes runtime.
9883                        grant = GRANT_UPGRADE;
9884                    } else if (mPromoteSystemApps
9885                            && isSystemApp(ps)
9886                            && mExistingSystemPackages.contains(ps.name)) {
9887                        // For legacy system apps, install becomes runtime.
9888                        // We cannot check hasInstallPermission() for system apps since those
9889                        // permissions were granted implicitly and not persisted pre-M.
9890                        grant = GRANT_UPGRADE;
9891                    } else {
9892                        // For modern apps keep runtime permissions unchanged.
9893                        grant = GRANT_RUNTIME;
9894                    }
9895                } break;
9896
9897                case PermissionInfo.PROTECTION_SIGNATURE: {
9898                    // For all apps signature permissions are install time ones.
9899                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9900                    if (allowedSig) {
9901                        grant = GRANT_INSTALL;
9902                    }
9903                } break;
9904            }
9905
9906            if (DEBUG_INSTALL) {
9907                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9908            }
9909
9910            if (grant != GRANT_DENIED) {
9911                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9912                    // If this is an existing, non-system package, then
9913                    // we can't add any new permissions to it.
9914                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9915                        // Except...  if this is a permission that was added
9916                        // to the platform (note: need to only do this when
9917                        // updating the platform).
9918                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9919                            grant = GRANT_DENIED;
9920                        }
9921                    }
9922                }
9923
9924                switch (grant) {
9925                    case GRANT_INSTALL: {
9926                        // Revoke this as runtime permission to handle the case of
9927                        // a runtime permission being downgraded to an install one.
9928                        // Also in permission review mode we keep dangerous permissions
9929                        // for legacy apps
9930                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9931                            if (origPermissions.getRuntimePermissionState(
9932                                    bp.name, userId) != null) {
9933                                // Revoke the runtime permission and clear the flags.
9934                                origPermissions.revokeRuntimePermission(bp, userId);
9935                                origPermissions.updatePermissionFlags(bp, userId,
9936                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9937                                // If we revoked a permission permission, we have to write.
9938                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9939                                        changedRuntimePermissionUserIds, userId);
9940                            }
9941                        }
9942                        // Grant an install permission.
9943                        if (permissionsState.grantInstallPermission(bp) !=
9944                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9945                            changedInstallPermission = true;
9946                        }
9947                    } break;
9948
9949                    case GRANT_RUNTIME: {
9950                        // Grant previously granted runtime permissions.
9951                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9952                            PermissionState permissionState = origPermissions
9953                                    .getRuntimePermissionState(bp.name, userId);
9954                            int flags = permissionState != null
9955                                    ? permissionState.getFlags() : 0;
9956                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9957                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9958                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9959                                    // If we cannot put the permission as it was, we have to write.
9960                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9961                                            changedRuntimePermissionUserIds, userId);
9962                                }
9963                                // If the app supports runtime permissions no need for a review.
9964                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9965                                        && appSupportsRuntimePermissions
9966                                        && (flags & PackageManager
9967                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9968                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9969                                    // Since we changed the flags, we have to write.
9970                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9971                                            changedRuntimePermissionUserIds, userId);
9972                                }
9973                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9974                                    && !appSupportsRuntimePermissions) {
9975                                // For legacy apps that need a permission review, every new
9976                                // runtime permission is granted but it is pending a review.
9977                                // We also need to review only platform defined runtime
9978                                // permissions as these are the only ones the platform knows
9979                                // how to disable the API to simulate revocation as legacy
9980                                // apps don't expect to run with revoked permissions.
9981                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9982                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9983                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9984                                        // We changed the flags, hence have to write.
9985                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9986                                                changedRuntimePermissionUserIds, userId);
9987                                    }
9988                                }
9989                                if (permissionsState.grantRuntimePermission(bp, userId)
9990                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9991                                    // We changed the permission, hence have to write.
9992                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9993                                            changedRuntimePermissionUserIds, userId);
9994                                }
9995                            }
9996                            // Propagate the permission flags.
9997                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9998                        }
9999                    } break;
10000
10001                    case GRANT_UPGRADE: {
10002                        // Grant runtime permissions for a previously held install permission.
10003                        PermissionState permissionState = origPermissions
10004                                .getInstallPermissionState(bp.name);
10005                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10006
10007                        if (origPermissions.revokeInstallPermission(bp)
10008                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10009                            // We will be transferring the permission flags, so clear them.
10010                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10011                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10012                            changedInstallPermission = true;
10013                        }
10014
10015                        // If the permission is not to be promoted to runtime we ignore it and
10016                        // also its other flags as they are not applicable to install permissions.
10017                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10018                            for (int userId : currentUserIds) {
10019                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10020                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10021                                    // Transfer the permission flags.
10022                                    permissionsState.updatePermissionFlags(bp, userId,
10023                                            flags, flags);
10024                                    // If we granted the permission, we have to write.
10025                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10026                                            changedRuntimePermissionUserIds, userId);
10027                                }
10028                            }
10029                        }
10030                    } break;
10031
10032                    default: {
10033                        if (packageOfInterest == null
10034                                || packageOfInterest.equals(pkg.packageName)) {
10035                            Slog.w(TAG, "Not granting permission " + perm
10036                                    + " to package " + pkg.packageName
10037                                    + " because it was previously installed without");
10038                        }
10039                    } break;
10040                }
10041            } else {
10042                if (permissionsState.revokeInstallPermission(bp) !=
10043                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10044                    // Also drop the permission flags.
10045                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10046                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10047                    changedInstallPermission = true;
10048                    Slog.i(TAG, "Un-granting permission " + perm
10049                            + " from package " + pkg.packageName
10050                            + " (protectionLevel=" + bp.protectionLevel
10051                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10052                            + ")");
10053                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10054                    // Don't print warning for app op permissions, since it is fine for them
10055                    // not to be granted, there is a UI for the user to decide.
10056                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10057                        Slog.w(TAG, "Not granting permission " + perm
10058                                + " to package " + pkg.packageName
10059                                + " (protectionLevel=" + bp.protectionLevel
10060                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10061                                + ")");
10062                    }
10063                }
10064            }
10065        }
10066
10067        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10068                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10069            // This is the first that we have heard about this package, so the
10070            // permissions we have now selected are fixed until explicitly
10071            // changed.
10072            ps.installPermissionsFixed = true;
10073        }
10074
10075        // Persist the runtime permissions state for users with changes. If permissions
10076        // were revoked because no app in the shared user declares them we have to
10077        // write synchronously to avoid losing runtime permissions state.
10078        for (int userId : changedRuntimePermissionUserIds) {
10079            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10080        }
10081
10082        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10083    }
10084
10085    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10086        boolean allowed = false;
10087        final int NP = PackageParser.NEW_PERMISSIONS.length;
10088        for (int ip=0; ip<NP; ip++) {
10089            final PackageParser.NewPermissionInfo npi
10090                    = PackageParser.NEW_PERMISSIONS[ip];
10091            if (npi.name.equals(perm)
10092                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10093                allowed = true;
10094                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10095                        + pkg.packageName);
10096                break;
10097            }
10098        }
10099        return allowed;
10100    }
10101
10102    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10103            BasePermission bp, PermissionsState origPermissions) {
10104        boolean allowed;
10105        allowed = (compareSignatures(
10106                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10107                        == PackageManager.SIGNATURE_MATCH)
10108                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10109                        == PackageManager.SIGNATURE_MATCH);
10110        if (!allowed && (bp.protectionLevel
10111                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10112            if (isSystemApp(pkg)) {
10113                // For updated system applications, a system permission
10114                // is granted only if it had been defined by the original application.
10115                if (pkg.isUpdatedSystemApp()) {
10116                    final PackageSetting sysPs = mSettings
10117                            .getDisabledSystemPkgLPr(pkg.packageName);
10118                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10119                        // If the original was granted this permission, we take
10120                        // that grant decision as read and propagate it to the
10121                        // update.
10122                        if (sysPs.isPrivileged()) {
10123                            allowed = true;
10124                        }
10125                    } else {
10126                        // The system apk may have been updated with an older
10127                        // version of the one on the data partition, but which
10128                        // granted a new system permission that it didn't have
10129                        // before.  In this case we do want to allow the app to
10130                        // now get the new permission if the ancestral apk is
10131                        // privileged to get it.
10132                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10133                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10134                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10135                                    allowed = true;
10136                                    break;
10137                                }
10138                            }
10139                        }
10140                        // Also if a privileged parent package on the system image or any of
10141                        // its children requested a privileged permission, the updated child
10142                        // packages can also get the permission.
10143                        if (pkg.parentPackage != null) {
10144                            final PackageSetting disabledSysParentPs = mSettings
10145                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10146                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10147                                    && disabledSysParentPs.isPrivileged()) {
10148                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10149                                    allowed = true;
10150                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10151                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10152                                    for (int i = 0; i < count; i++) {
10153                                        PackageParser.Package disabledSysChildPkg =
10154                                                disabledSysParentPs.pkg.childPackages.get(i);
10155                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10156                                                perm)) {
10157                                            allowed = true;
10158                                            break;
10159                                        }
10160                                    }
10161                                }
10162                            }
10163                        }
10164                    }
10165                } else {
10166                    allowed = isPrivilegedApp(pkg);
10167                }
10168            }
10169        }
10170        if (!allowed) {
10171            if (!allowed && (bp.protectionLevel
10172                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10173                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10174                // If this was a previously normal/dangerous permission that got moved
10175                // to a system permission as part of the runtime permission redesign, then
10176                // we still want to blindly grant it to old apps.
10177                allowed = true;
10178            }
10179            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10180                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10181                // If this permission is to be granted to the system installer and
10182                // this app is an installer, then it gets the permission.
10183                allowed = true;
10184            }
10185            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10186                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10187                // If this permission is to be granted to the system verifier and
10188                // this app is a verifier, then it gets the permission.
10189                allowed = true;
10190            }
10191            if (!allowed && (bp.protectionLevel
10192                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10193                    && isSystemApp(pkg)) {
10194                // Any pre-installed system app is allowed to get this permission.
10195                allowed = true;
10196            }
10197            if (!allowed && (bp.protectionLevel
10198                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10199                // For development permissions, a development permission
10200                // is granted only if it was already granted.
10201                allowed = origPermissions.hasInstallPermission(perm);
10202            }
10203            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10204                    && pkg.packageName.equals(mSetupWizardPackage)) {
10205                // If this permission is to be granted to the system setup wizard and
10206                // this app is a setup wizard, then it gets the permission.
10207                allowed = true;
10208            }
10209        }
10210        return allowed;
10211    }
10212
10213    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10214        final int permCount = pkg.requestedPermissions.size();
10215        for (int j = 0; j < permCount; j++) {
10216            String requestedPermission = pkg.requestedPermissions.get(j);
10217            if (permission.equals(requestedPermission)) {
10218                return true;
10219            }
10220        }
10221        return false;
10222    }
10223
10224    final class ActivityIntentResolver
10225            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10226        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10227                boolean defaultOnly, int userId) {
10228            if (!sUserManager.exists(userId)) return null;
10229            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10230            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10231        }
10232
10233        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10234                int userId) {
10235            if (!sUserManager.exists(userId)) return null;
10236            mFlags = flags;
10237            return super.queryIntent(intent, resolvedType,
10238                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10239        }
10240
10241        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10242                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10243            if (!sUserManager.exists(userId)) return null;
10244            if (packageActivities == null) {
10245                return null;
10246            }
10247            mFlags = flags;
10248            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10249            final int N = packageActivities.size();
10250            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10251                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10252
10253            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10254            for (int i = 0; i < N; ++i) {
10255                intentFilters = packageActivities.get(i).intents;
10256                if (intentFilters != null && intentFilters.size() > 0) {
10257                    PackageParser.ActivityIntentInfo[] array =
10258                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10259                    intentFilters.toArray(array);
10260                    listCut.add(array);
10261                }
10262            }
10263            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10264        }
10265
10266        /**
10267         * Finds a privileged activity that matches the specified activity names.
10268         */
10269        private PackageParser.Activity findMatchingActivity(
10270                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10271            for (PackageParser.Activity sysActivity : activityList) {
10272                if (sysActivity.info.name.equals(activityInfo.name)) {
10273                    return sysActivity;
10274                }
10275                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10276                    return sysActivity;
10277                }
10278                if (sysActivity.info.targetActivity != null) {
10279                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10280                        return sysActivity;
10281                    }
10282                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10283                        return sysActivity;
10284                    }
10285                }
10286            }
10287            return null;
10288        }
10289
10290        public class IterGenerator<E> {
10291            public Iterator<E> generate(ActivityIntentInfo info) {
10292                return null;
10293            }
10294        }
10295
10296        public class ActionIterGenerator extends IterGenerator<String> {
10297            @Override
10298            public Iterator<String> generate(ActivityIntentInfo info) {
10299                return info.actionsIterator();
10300            }
10301        }
10302
10303        public class CategoriesIterGenerator extends IterGenerator<String> {
10304            @Override
10305            public Iterator<String> generate(ActivityIntentInfo info) {
10306                return info.categoriesIterator();
10307            }
10308        }
10309
10310        public class SchemesIterGenerator extends IterGenerator<String> {
10311            @Override
10312            public Iterator<String> generate(ActivityIntentInfo info) {
10313                return info.schemesIterator();
10314            }
10315        }
10316
10317        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10318            @Override
10319            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10320                return info.authoritiesIterator();
10321            }
10322        }
10323
10324        /**
10325         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10326         * MODIFIED. Do not pass in a list that should not be changed.
10327         */
10328        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10329                IterGenerator<T> generator, Iterator<T> searchIterator) {
10330            // loop through the set of actions; every one must be found in the intent filter
10331            while (searchIterator.hasNext()) {
10332                // we must have at least one filter in the list to consider a match
10333                if (intentList.size() == 0) {
10334                    break;
10335                }
10336
10337                final T searchAction = searchIterator.next();
10338
10339                // loop through the set of intent filters
10340                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10341                while (intentIter.hasNext()) {
10342                    final ActivityIntentInfo intentInfo = intentIter.next();
10343                    boolean selectionFound = false;
10344
10345                    // loop through the intent filter's selection criteria; at least one
10346                    // of them must match the searched criteria
10347                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10348                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10349                        final T intentSelection = intentSelectionIter.next();
10350                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10351                            selectionFound = true;
10352                            break;
10353                        }
10354                    }
10355
10356                    // the selection criteria wasn't found in this filter's set; this filter
10357                    // is not a potential match
10358                    if (!selectionFound) {
10359                        intentIter.remove();
10360                    }
10361                }
10362            }
10363        }
10364
10365        private boolean isProtectedAction(ActivityIntentInfo filter) {
10366            final Iterator<String> actionsIter = filter.actionsIterator();
10367            while (actionsIter != null && actionsIter.hasNext()) {
10368                final String filterAction = actionsIter.next();
10369                if (PROTECTED_ACTIONS.contains(filterAction)) {
10370                    return true;
10371                }
10372            }
10373            return false;
10374        }
10375
10376        /**
10377         * Adjusts the priority of the given intent filter according to policy.
10378         * <p>
10379         * <ul>
10380         * <li>The priority for non privileged applications is capped to '0'</li>
10381         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10382         * <li>The priority for unbundled updates to privileged applications is capped to the
10383         *      priority defined on the system partition</li>
10384         * </ul>
10385         * <p>
10386         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10387         * allowed to obtain any priority on any action.
10388         */
10389        private void adjustPriority(
10390                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10391            // nothing to do; priority is fine as-is
10392            if (intent.getPriority() <= 0) {
10393                return;
10394            }
10395
10396            final ActivityInfo activityInfo = intent.activity.info;
10397            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10398
10399            final boolean privilegedApp =
10400                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10401            if (!privilegedApp) {
10402                // non-privileged applications can never define a priority >0
10403                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10404                        + " package: " + applicationInfo.packageName
10405                        + " activity: " + intent.activity.className
10406                        + " origPrio: " + intent.getPriority());
10407                intent.setPriority(0);
10408                return;
10409            }
10410
10411            if (systemActivities == null) {
10412                // the system package is not disabled; we're parsing the system partition
10413                if (isProtectedAction(intent)) {
10414                    if (mDeferProtectedFilters) {
10415                        // We can't deal with these just yet. No component should ever obtain a
10416                        // >0 priority for a protected actions, with ONE exception -- the setup
10417                        // wizard. The setup wizard, however, cannot be known until we're able to
10418                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10419                        // until all intent filters have been processed. Chicken, meet egg.
10420                        // Let the filter temporarily have a high priority and rectify the
10421                        // priorities after all system packages have been scanned.
10422                        mProtectedFilters.add(intent);
10423                        if (DEBUG_FILTERS) {
10424                            Slog.i(TAG, "Protected action; save for later;"
10425                                    + " package: " + applicationInfo.packageName
10426                                    + " activity: " + intent.activity.className
10427                                    + " origPrio: " + intent.getPriority());
10428                        }
10429                        return;
10430                    } else {
10431                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10432                            Slog.i(TAG, "No setup wizard;"
10433                                + " All protected intents capped to priority 0");
10434                        }
10435                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10436                            if (DEBUG_FILTERS) {
10437                                Slog.i(TAG, "Found setup wizard;"
10438                                    + " allow priority " + intent.getPriority() + ";"
10439                                    + " package: " + intent.activity.info.packageName
10440                                    + " activity: " + intent.activity.className
10441                                    + " priority: " + intent.getPriority());
10442                            }
10443                            // setup wizard gets whatever it wants
10444                            return;
10445                        }
10446                        Slog.w(TAG, "Protected action; cap priority to 0;"
10447                                + " package: " + intent.activity.info.packageName
10448                                + " activity: " + intent.activity.className
10449                                + " origPrio: " + intent.getPriority());
10450                        intent.setPriority(0);
10451                        return;
10452                    }
10453                }
10454                // privileged apps on the system image get whatever priority they request
10455                return;
10456            }
10457
10458            // privileged app unbundled update ... try to find the same activity
10459            final PackageParser.Activity foundActivity =
10460                    findMatchingActivity(systemActivities, activityInfo);
10461            if (foundActivity == null) {
10462                // this is a new activity; it cannot obtain >0 priority
10463                if (DEBUG_FILTERS) {
10464                    Slog.i(TAG, "New activity; cap priority to 0;"
10465                            + " package: " + applicationInfo.packageName
10466                            + " activity: " + intent.activity.className
10467                            + " origPrio: " + intent.getPriority());
10468                }
10469                intent.setPriority(0);
10470                return;
10471            }
10472
10473            // found activity, now check for filter equivalence
10474
10475            // a shallow copy is enough; we modify the list, not its contents
10476            final List<ActivityIntentInfo> intentListCopy =
10477                    new ArrayList<>(foundActivity.intents);
10478            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10479
10480            // find matching action subsets
10481            final Iterator<String> actionsIterator = intent.actionsIterator();
10482            if (actionsIterator != null) {
10483                getIntentListSubset(
10484                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10485                if (intentListCopy.size() == 0) {
10486                    // no more intents to match; we're not equivalent
10487                    if (DEBUG_FILTERS) {
10488                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10489                                + " package: " + applicationInfo.packageName
10490                                + " activity: " + intent.activity.className
10491                                + " origPrio: " + intent.getPriority());
10492                    }
10493                    intent.setPriority(0);
10494                    return;
10495                }
10496            }
10497
10498            // find matching category subsets
10499            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10500            if (categoriesIterator != null) {
10501                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10502                        categoriesIterator);
10503                if (intentListCopy.size() == 0) {
10504                    // no more intents to match; we're not equivalent
10505                    if (DEBUG_FILTERS) {
10506                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10507                                + " package: " + applicationInfo.packageName
10508                                + " activity: " + intent.activity.className
10509                                + " origPrio: " + intent.getPriority());
10510                    }
10511                    intent.setPriority(0);
10512                    return;
10513                }
10514            }
10515
10516            // find matching schemes subsets
10517            final Iterator<String> schemesIterator = intent.schemesIterator();
10518            if (schemesIterator != null) {
10519                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10520                        schemesIterator);
10521                if (intentListCopy.size() == 0) {
10522                    // no more intents to match; we're not equivalent
10523                    if (DEBUG_FILTERS) {
10524                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10525                                + " package: " + applicationInfo.packageName
10526                                + " activity: " + intent.activity.className
10527                                + " origPrio: " + intent.getPriority());
10528                    }
10529                    intent.setPriority(0);
10530                    return;
10531                }
10532            }
10533
10534            // find matching authorities subsets
10535            final Iterator<IntentFilter.AuthorityEntry>
10536                    authoritiesIterator = intent.authoritiesIterator();
10537            if (authoritiesIterator != null) {
10538                getIntentListSubset(intentListCopy,
10539                        new AuthoritiesIterGenerator(),
10540                        authoritiesIterator);
10541                if (intentListCopy.size() == 0) {
10542                    // no more intents to match; we're not equivalent
10543                    if (DEBUG_FILTERS) {
10544                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10545                                + " package: " + applicationInfo.packageName
10546                                + " activity: " + intent.activity.className
10547                                + " origPrio: " + intent.getPriority());
10548                    }
10549                    intent.setPriority(0);
10550                    return;
10551                }
10552            }
10553
10554            // we found matching filter(s); app gets the max priority of all intents
10555            int cappedPriority = 0;
10556            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10557                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10558            }
10559            if (intent.getPriority() > cappedPriority) {
10560                if (DEBUG_FILTERS) {
10561                    Slog.i(TAG, "Found matching filter(s);"
10562                            + " cap priority to " + cappedPriority + ";"
10563                            + " package: " + applicationInfo.packageName
10564                            + " activity: " + intent.activity.className
10565                            + " origPrio: " + intent.getPriority());
10566                }
10567                intent.setPriority(cappedPriority);
10568                return;
10569            }
10570            // all this for nothing; the requested priority was <= what was on the system
10571        }
10572
10573        public final void addActivity(PackageParser.Activity a, String type) {
10574            mActivities.put(a.getComponentName(), a);
10575            if (DEBUG_SHOW_INFO)
10576                Log.v(
10577                TAG, "  " + type + " " +
10578                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10579            if (DEBUG_SHOW_INFO)
10580                Log.v(TAG, "    Class=" + a.info.name);
10581            final int NI = a.intents.size();
10582            for (int j=0; j<NI; j++) {
10583                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10584                if ("activity".equals(type)) {
10585                    final PackageSetting ps =
10586                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10587                    final List<PackageParser.Activity> systemActivities =
10588                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10589                    adjustPriority(systemActivities, intent);
10590                }
10591                if (DEBUG_SHOW_INFO) {
10592                    Log.v(TAG, "    IntentFilter:");
10593                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10594                }
10595                if (!intent.debugCheck()) {
10596                    Log.w(TAG, "==> For Activity " + a.info.name);
10597                }
10598                addFilter(intent);
10599            }
10600        }
10601
10602        public final void removeActivity(PackageParser.Activity a, String type) {
10603            mActivities.remove(a.getComponentName());
10604            if (DEBUG_SHOW_INFO) {
10605                Log.v(TAG, "  " + type + " "
10606                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10607                                : a.info.name) + ":");
10608                Log.v(TAG, "    Class=" + a.info.name);
10609            }
10610            final int NI = a.intents.size();
10611            for (int j=0; j<NI; j++) {
10612                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10613                if (DEBUG_SHOW_INFO) {
10614                    Log.v(TAG, "    IntentFilter:");
10615                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10616                }
10617                removeFilter(intent);
10618            }
10619        }
10620
10621        @Override
10622        protected boolean allowFilterResult(
10623                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10624            ActivityInfo filterAi = filter.activity.info;
10625            for (int i=dest.size()-1; i>=0; i--) {
10626                ActivityInfo destAi = dest.get(i).activityInfo;
10627                if (destAi.name == filterAi.name
10628                        && destAi.packageName == filterAi.packageName) {
10629                    return false;
10630                }
10631            }
10632            return true;
10633        }
10634
10635        @Override
10636        protected ActivityIntentInfo[] newArray(int size) {
10637            return new ActivityIntentInfo[size];
10638        }
10639
10640        @Override
10641        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10642            if (!sUserManager.exists(userId)) return true;
10643            PackageParser.Package p = filter.activity.owner;
10644            if (p != null) {
10645                PackageSetting ps = (PackageSetting)p.mExtras;
10646                if (ps != null) {
10647                    // System apps are never considered stopped for purposes of
10648                    // filtering, because there may be no way for the user to
10649                    // actually re-launch them.
10650                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10651                            && ps.getStopped(userId);
10652                }
10653            }
10654            return false;
10655        }
10656
10657        @Override
10658        protected boolean isPackageForFilter(String packageName,
10659                PackageParser.ActivityIntentInfo info) {
10660            return packageName.equals(info.activity.owner.packageName);
10661        }
10662
10663        @Override
10664        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10665                int match, int userId) {
10666            if (!sUserManager.exists(userId)) return null;
10667            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10668                return null;
10669            }
10670            final PackageParser.Activity activity = info.activity;
10671            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10672            if (ps == null) {
10673                return null;
10674            }
10675            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10676                    ps.readUserState(userId), userId);
10677            if (ai == null) {
10678                return null;
10679            }
10680            final ResolveInfo res = new ResolveInfo();
10681            res.activityInfo = ai;
10682            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10683                res.filter = info;
10684            }
10685            if (info != null) {
10686                res.handleAllWebDataURI = info.handleAllWebDataURI();
10687            }
10688            res.priority = info.getPriority();
10689            res.preferredOrder = activity.owner.mPreferredOrder;
10690            //System.out.println("Result: " + res.activityInfo.className +
10691            //                   " = " + res.priority);
10692            res.match = match;
10693            res.isDefault = info.hasDefault;
10694            res.labelRes = info.labelRes;
10695            res.nonLocalizedLabel = info.nonLocalizedLabel;
10696            if (userNeedsBadging(userId)) {
10697                res.noResourceId = true;
10698            } else {
10699                res.icon = info.icon;
10700            }
10701            res.iconResourceId = info.icon;
10702            res.system = res.activityInfo.applicationInfo.isSystemApp();
10703            return res;
10704        }
10705
10706        @Override
10707        protected void sortResults(List<ResolveInfo> results) {
10708            Collections.sort(results, mResolvePrioritySorter);
10709        }
10710
10711        @Override
10712        protected void dumpFilter(PrintWriter out, String prefix,
10713                PackageParser.ActivityIntentInfo filter) {
10714            out.print(prefix); out.print(
10715                    Integer.toHexString(System.identityHashCode(filter.activity)));
10716                    out.print(' ');
10717                    filter.activity.printComponentShortName(out);
10718                    out.print(" filter ");
10719                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10720        }
10721
10722        @Override
10723        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10724            return filter.activity;
10725        }
10726
10727        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10728            PackageParser.Activity activity = (PackageParser.Activity)label;
10729            out.print(prefix); out.print(
10730                    Integer.toHexString(System.identityHashCode(activity)));
10731                    out.print(' ');
10732                    activity.printComponentShortName(out);
10733            if (count > 1) {
10734                out.print(" ("); out.print(count); out.print(" filters)");
10735            }
10736            out.println();
10737        }
10738
10739        // Keys are String (activity class name), values are Activity.
10740        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10741                = new ArrayMap<ComponentName, PackageParser.Activity>();
10742        private int mFlags;
10743    }
10744
10745    private final class ServiceIntentResolver
10746            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10747        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10748                boolean defaultOnly, int userId) {
10749            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10750            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10751        }
10752
10753        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10754                int userId) {
10755            if (!sUserManager.exists(userId)) return null;
10756            mFlags = flags;
10757            return super.queryIntent(intent, resolvedType,
10758                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10759        }
10760
10761        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10762                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10763            if (!sUserManager.exists(userId)) return null;
10764            if (packageServices == null) {
10765                return null;
10766            }
10767            mFlags = flags;
10768            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10769            final int N = packageServices.size();
10770            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10771                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10772
10773            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10774            for (int i = 0; i < N; ++i) {
10775                intentFilters = packageServices.get(i).intents;
10776                if (intentFilters != null && intentFilters.size() > 0) {
10777                    PackageParser.ServiceIntentInfo[] array =
10778                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10779                    intentFilters.toArray(array);
10780                    listCut.add(array);
10781                }
10782            }
10783            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10784        }
10785
10786        public final void addService(PackageParser.Service s) {
10787            mServices.put(s.getComponentName(), s);
10788            if (DEBUG_SHOW_INFO) {
10789                Log.v(TAG, "  "
10790                        + (s.info.nonLocalizedLabel != null
10791                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10792                Log.v(TAG, "    Class=" + s.info.name);
10793            }
10794            final int NI = s.intents.size();
10795            int j;
10796            for (j=0; j<NI; j++) {
10797                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10798                if (DEBUG_SHOW_INFO) {
10799                    Log.v(TAG, "    IntentFilter:");
10800                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10801                }
10802                if (!intent.debugCheck()) {
10803                    Log.w(TAG, "==> For Service " + s.info.name);
10804                }
10805                addFilter(intent);
10806            }
10807        }
10808
10809        public final void removeService(PackageParser.Service s) {
10810            mServices.remove(s.getComponentName());
10811            if (DEBUG_SHOW_INFO) {
10812                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10813                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10814                Log.v(TAG, "    Class=" + s.info.name);
10815            }
10816            final int NI = s.intents.size();
10817            int j;
10818            for (j=0; j<NI; j++) {
10819                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10820                if (DEBUG_SHOW_INFO) {
10821                    Log.v(TAG, "    IntentFilter:");
10822                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10823                }
10824                removeFilter(intent);
10825            }
10826        }
10827
10828        @Override
10829        protected boolean allowFilterResult(
10830                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10831            ServiceInfo filterSi = filter.service.info;
10832            for (int i=dest.size()-1; i>=0; i--) {
10833                ServiceInfo destAi = dest.get(i).serviceInfo;
10834                if (destAi.name == filterSi.name
10835                        && destAi.packageName == filterSi.packageName) {
10836                    return false;
10837                }
10838            }
10839            return true;
10840        }
10841
10842        @Override
10843        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10844            return new PackageParser.ServiceIntentInfo[size];
10845        }
10846
10847        @Override
10848        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10849            if (!sUserManager.exists(userId)) return true;
10850            PackageParser.Package p = filter.service.owner;
10851            if (p != null) {
10852                PackageSetting ps = (PackageSetting)p.mExtras;
10853                if (ps != null) {
10854                    // System apps are never considered stopped for purposes of
10855                    // filtering, because there may be no way for the user to
10856                    // actually re-launch them.
10857                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10858                            && ps.getStopped(userId);
10859                }
10860            }
10861            return false;
10862        }
10863
10864        @Override
10865        protected boolean isPackageForFilter(String packageName,
10866                PackageParser.ServiceIntentInfo info) {
10867            return packageName.equals(info.service.owner.packageName);
10868        }
10869
10870        @Override
10871        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10872                int match, int userId) {
10873            if (!sUserManager.exists(userId)) return null;
10874            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10875            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10876                return null;
10877            }
10878            final PackageParser.Service service = info.service;
10879            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10880            if (ps == null) {
10881                return null;
10882            }
10883            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10884                    ps.readUserState(userId), userId);
10885            if (si == null) {
10886                return null;
10887            }
10888            final ResolveInfo res = new ResolveInfo();
10889            res.serviceInfo = si;
10890            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10891                res.filter = filter;
10892            }
10893            res.priority = info.getPriority();
10894            res.preferredOrder = service.owner.mPreferredOrder;
10895            res.match = match;
10896            res.isDefault = info.hasDefault;
10897            res.labelRes = info.labelRes;
10898            res.nonLocalizedLabel = info.nonLocalizedLabel;
10899            res.icon = info.icon;
10900            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10901            return res;
10902        }
10903
10904        @Override
10905        protected void sortResults(List<ResolveInfo> results) {
10906            Collections.sort(results, mResolvePrioritySorter);
10907        }
10908
10909        @Override
10910        protected void dumpFilter(PrintWriter out, String prefix,
10911                PackageParser.ServiceIntentInfo filter) {
10912            out.print(prefix); out.print(
10913                    Integer.toHexString(System.identityHashCode(filter.service)));
10914                    out.print(' ');
10915                    filter.service.printComponentShortName(out);
10916                    out.print(" filter ");
10917                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10918        }
10919
10920        @Override
10921        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10922            return filter.service;
10923        }
10924
10925        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10926            PackageParser.Service service = (PackageParser.Service)label;
10927            out.print(prefix); out.print(
10928                    Integer.toHexString(System.identityHashCode(service)));
10929                    out.print(' ');
10930                    service.printComponentShortName(out);
10931            if (count > 1) {
10932                out.print(" ("); out.print(count); out.print(" filters)");
10933            }
10934            out.println();
10935        }
10936
10937//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10938//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10939//            final List<ResolveInfo> retList = Lists.newArrayList();
10940//            while (i.hasNext()) {
10941//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10942//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10943//                    retList.add(resolveInfo);
10944//                }
10945//            }
10946//            return retList;
10947//        }
10948
10949        // Keys are String (activity class name), values are Activity.
10950        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10951                = new ArrayMap<ComponentName, PackageParser.Service>();
10952        private int mFlags;
10953    };
10954
10955    private final class ProviderIntentResolver
10956            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10957        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10958                boolean defaultOnly, int userId) {
10959            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10960            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10961        }
10962
10963        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10964                int userId) {
10965            if (!sUserManager.exists(userId))
10966                return null;
10967            mFlags = flags;
10968            return super.queryIntent(intent, resolvedType,
10969                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10970        }
10971
10972        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10973                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10974            if (!sUserManager.exists(userId))
10975                return null;
10976            if (packageProviders == null) {
10977                return null;
10978            }
10979            mFlags = flags;
10980            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10981            final int N = packageProviders.size();
10982            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10983                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10984
10985            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10986            for (int i = 0; i < N; ++i) {
10987                intentFilters = packageProviders.get(i).intents;
10988                if (intentFilters != null && intentFilters.size() > 0) {
10989                    PackageParser.ProviderIntentInfo[] array =
10990                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10991                    intentFilters.toArray(array);
10992                    listCut.add(array);
10993                }
10994            }
10995            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10996        }
10997
10998        public final void addProvider(PackageParser.Provider p) {
10999            if (mProviders.containsKey(p.getComponentName())) {
11000                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11001                return;
11002            }
11003
11004            mProviders.put(p.getComponentName(), p);
11005            if (DEBUG_SHOW_INFO) {
11006                Log.v(TAG, "  "
11007                        + (p.info.nonLocalizedLabel != null
11008                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11009                Log.v(TAG, "    Class=" + p.info.name);
11010            }
11011            final int NI = p.intents.size();
11012            int j;
11013            for (j = 0; j < NI; j++) {
11014                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11015                if (DEBUG_SHOW_INFO) {
11016                    Log.v(TAG, "    IntentFilter:");
11017                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11018                }
11019                if (!intent.debugCheck()) {
11020                    Log.w(TAG, "==> For Provider " + p.info.name);
11021                }
11022                addFilter(intent);
11023            }
11024        }
11025
11026        public final void removeProvider(PackageParser.Provider p) {
11027            mProviders.remove(p.getComponentName());
11028            if (DEBUG_SHOW_INFO) {
11029                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11030                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11031                Log.v(TAG, "    Class=" + p.info.name);
11032            }
11033            final int NI = p.intents.size();
11034            int j;
11035            for (j = 0; j < NI; j++) {
11036                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11037                if (DEBUG_SHOW_INFO) {
11038                    Log.v(TAG, "    IntentFilter:");
11039                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11040                }
11041                removeFilter(intent);
11042            }
11043        }
11044
11045        @Override
11046        protected boolean allowFilterResult(
11047                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11048            ProviderInfo filterPi = filter.provider.info;
11049            for (int i = dest.size() - 1; i >= 0; i--) {
11050                ProviderInfo destPi = dest.get(i).providerInfo;
11051                if (destPi.name == filterPi.name
11052                        && destPi.packageName == filterPi.packageName) {
11053                    return false;
11054                }
11055            }
11056            return true;
11057        }
11058
11059        @Override
11060        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11061            return new PackageParser.ProviderIntentInfo[size];
11062        }
11063
11064        @Override
11065        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11066            if (!sUserManager.exists(userId))
11067                return true;
11068            PackageParser.Package p = filter.provider.owner;
11069            if (p != null) {
11070                PackageSetting ps = (PackageSetting) p.mExtras;
11071                if (ps != null) {
11072                    // System apps are never considered stopped for purposes of
11073                    // filtering, because there may be no way for the user to
11074                    // actually re-launch them.
11075                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11076                            && ps.getStopped(userId);
11077                }
11078            }
11079            return false;
11080        }
11081
11082        @Override
11083        protected boolean isPackageForFilter(String packageName,
11084                PackageParser.ProviderIntentInfo info) {
11085            return packageName.equals(info.provider.owner.packageName);
11086        }
11087
11088        @Override
11089        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11090                int match, int userId) {
11091            if (!sUserManager.exists(userId))
11092                return null;
11093            final PackageParser.ProviderIntentInfo info = filter;
11094            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11095                return null;
11096            }
11097            final PackageParser.Provider provider = info.provider;
11098            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11099            if (ps == null) {
11100                return null;
11101            }
11102            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11103                    ps.readUserState(userId), userId);
11104            if (pi == null) {
11105                return null;
11106            }
11107            final ResolveInfo res = new ResolveInfo();
11108            res.providerInfo = pi;
11109            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11110                res.filter = filter;
11111            }
11112            res.priority = info.getPriority();
11113            res.preferredOrder = provider.owner.mPreferredOrder;
11114            res.match = match;
11115            res.isDefault = info.hasDefault;
11116            res.labelRes = info.labelRes;
11117            res.nonLocalizedLabel = info.nonLocalizedLabel;
11118            res.icon = info.icon;
11119            res.system = res.providerInfo.applicationInfo.isSystemApp();
11120            return res;
11121        }
11122
11123        @Override
11124        protected void sortResults(List<ResolveInfo> results) {
11125            Collections.sort(results, mResolvePrioritySorter);
11126        }
11127
11128        @Override
11129        protected void dumpFilter(PrintWriter out, String prefix,
11130                PackageParser.ProviderIntentInfo filter) {
11131            out.print(prefix);
11132            out.print(
11133                    Integer.toHexString(System.identityHashCode(filter.provider)));
11134            out.print(' ');
11135            filter.provider.printComponentShortName(out);
11136            out.print(" filter ");
11137            out.println(Integer.toHexString(System.identityHashCode(filter)));
11138        }
11139
11140        @Override
11141        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11142            return filter.provider;
11143        }
11144
11145        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11146            PackageParser.Provider provider = (PackageParser.Provider)label;
11147            out.print(prefix); out.print(
11148                    Integer.toHexString(System.identityHashCode(provider)));
11149                    out.print(' ');
11150                    provider.printComponentShortName(out);
11151            if (count > 1) {
11152                out.print(" ("); out.print(count); out.print(" filters)");
11153            }
11154            out.println();
11155        }
11156
11157        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11158                = new ArrayMap<ComponentName, PackageParser.Provider>();
11159        private int mFlags;
11160    }
11161
11162    private static final class EphemeralIntentResolver
11163            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11164        @Override
11165        protected EphemeralResolveIntentInfo[] newArray(int size) {
11166            return new EphemeralResolveIntentInfo[size];
11167        }
11168
11169        @Override
11170        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11171            return true;
11172        }
11173
11174        @Override
11175        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11176                int userId) {
11177            if (!sUserManager.exists(userId)) {
11178                return null;
11179            }
11180            return info.getEphemeralResolveInfo();
11181        }
11182    }
11183
11184    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11185            new Comparator<ResolveInfo>() {
11186        public int compare(ResolveInfo r1, ResolveInfo r2) {
11187            int v1 = r1.priority;
11188            int v2 = r2.priority;
11189            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11190            if (v1 != v2) {
11191                return (v1 > v2) ? -1 : 1;
11192            }
11193            v1 = r1.preferredOrder;
11194            v2 = r2.preferredOrder;
11195            if (v1 != v2) {
11196                return (v1 > v2) ? -1 : 1;
11197            }
11198            if (r1.isDefault != r2.isDefault) {
11199                return r1.isDefault ? -1 : 1;
11200            }
11201            v1 = r1.match;
11202            v2 = r2.match;
11203            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11204            if (v1 != v2) {
11205                return (v1 > v2) ? -1 : 1;
11206            }
11207            if (r1.system != r2.system) {
11208                return r1.system ? -1 : 1;
11209            }
11210            if (r1.activityInfo != null) {
11211                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11212            }
11213            if (r1.serviceInfo != null) {
11214                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11215            }
11216            if (r1.providerInfo != null) {
11217                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11218            }
11219            return 0;
11220        }
11221    };
11222
11223    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11224            new Comparator<ProviderInfo>() {
11225        public int compare(ProviderInfo p1, ProviderInfo p2) {
11226            final int v1 = p1.initOrder;
11227            final int v2 = p2.initOrder;
11228            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11229        }
11230    };
11231
11232    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11233            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11234            final int[] userIds) {
11235        mHandler.post(new Runnable() {
11236            @Override
11237            public void run() {
11238                try {
11239                    final IActivityManager am = ActivityManagerNative.getDefault();
11240                    if (am == null) return;
11241                    final int[] resolvedUserIds;
11242                    if (userIds == null) {
11243                        resolvedUserIds = am.getRunningUserIds();
11244                    } else {
11245                        resolvedUserIds = userIds;
11246                    }
11247                    for (int id : resolvedUserIds) {
11248                        final Intent intent = new Intent(action,
11249                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11250                        if (extras != null) {
11251                            intent.putExtras(extras);
11252                        }
11253                        if (targetPkg != null) {
11254                            intent.setPackage(targetPkg);
11255                        }
11256                        // Modify the UID when posting to other users
11257                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11258                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11259                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11260                            intent.putExtra(Intent.EXTRA_UID, uid);
11261                        }
11262                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11263                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11264                        if (DEBUG_BROADCASTS) {
11265                            RuntimeException here = new RuntimeException("here");
11266                            here.fillInStackTrace();
11267                            Slog.d(TAG, "Sending to user " + id + ": "
11268                                    + intent.toShortString(false, true, false, false)
11269                                    + " " + intent.getExtras(), here);
11270                        }
11271                        am.broadcastIntent(null, intent, null, finishedReceiver,
11272                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11273                                null, finishedReceiver != null, false, id);
11274                    }
11275                } catch (RemoteException ex) {
11276                }
11277            }
11278        });
11279    }
11280
11281    /**
11282     * Check if the external storage media is available. This is true if there
11283     * is a mounted external storage medium or if the external storage is
11284     * emulated.
11285     */
11286    private boolean isExternalMediaAvailable() {
11287        return mMediaMounted || Environment.isExternalStorageEmulated();
11288    }
11289
11290    @Override
11291    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11292        // writer
11293        synchronized (mPackages) {
11294            if (!isExternalMediaAvailable()) {
11295                // If the external storage is no longer mounted at this point,
11296                // the caller may not have been able to delete all of this
11297                // packages files and can not delete any more.  Bail.
11298                return null;
11299            }
11300            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11301            if (lastPackage != null) {
11302                pkgs.remove(lastPackage);
11303            }
11304            if (pkgs.size() > 0) {
11305                return pkgs.get(0);
11306            }
11307        }
11308        return null;
11309    }
11310
11311    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11312        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11313                userId, andCode ? 1 : 0, packageName);
11314        if (mSystemReady) {
11315            msg.sendToTarget();
11316        } else {
11317            if (mPostSystemReadyMessages == null) {
11318                mPostSystemReadyMessages = new ArrayList<>();
11319            }
11320            mPostSystemReadyMessages.add(msg);
11321        }
11322    }
11323
11324    void startCleaningPackages() {
11325        // reader
11326        if (!isExternalMediaAvailable()) {
11327            return;
11328        }
11329        synchronized (mPackages) {
11330            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11331                return;
11332            }
11333        }
11334        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11335        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11336        IActivityManager am = ActivityManagerNative.getDefault();
11337        if (am != null) {
11338            try {
11339                am.startService(null, intent, null, mContext.getOpPackageName(),
11340                        UserHandle.USER_SYSTEM);
11341            } catch (RemoteException e) {
11342            }
11343        }
11344    }
11345
11346    @Override
11347    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11348            int installFlags, String installerPackageName, int userId) {
11349        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11350
11351        final int callingUid = Binder.getCallingUid();
11352        enforceCrossUserPermission(callingUid, userId,
11353                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11354
11355        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11356            try {
11357                if (observer != null) {
11358                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11359                }
11360            } catch (RemoteException re) {
11361            }
11362            return;
11363        }
11364
11365        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11366            installFlags |= PackageManager.INSTALL_FROM_ADB;
11367
11368        } else {
11369            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11370            // about installerPackageName.
11371
11372            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11373            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11374        }
11375
11376        UserHandle user;
11377        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11378            user = UserHandle.ALL;
11379        } else {
11380            user = new UserHandle(userId);
11381        }
11382
11383        // Only system components can circumvent runtime permissions when installing.
11384        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11385                && mContext.checkCallingOrSelfPermission(Manifest.permission
11386                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11387            throw new SecurityException("You need the "
11388                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11389                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11390        }
11391
11392        final File originFile = new File(originPath);
11393        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11394
11395        final Message msg = mHandler.obtainMessage(INIT_COPY);
11396        final VerificationInfo verificationInfo = new VerificationInfo(
11397                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11398        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11399                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11400                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11401                null /*certificates*/);
11402        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11403        msg.obj = params;
11404
11405        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11406                System.identityHashCode(msg.obj));
11407        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11408                System.identityHashCode(msg.obj));
11409
11410        mHandler.sendMessage(msg);
11411    }
11412
11413    void installStage(String packageName, File stagedDir, String stagedCid,
11414            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11415            String installerPackageName, int installerUid, UserHandle user,
11416            Certificate[][] certificates) {
11417        if (DEBUG_EPHEMERAL) {
11418            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11419                Slog.d(TAG, "Ephemeral install of " + packageName);
11420            }
11421        }
11422        final VerificationInfo verificationInfo = new VerificationInfo(
11423                sessionParams.originatingUri, sessionParams.referrerUri,
11424                sessionParams.originatingUid, installerUid);
11425
11426        final OriginInfo origin;
11427        if (stagedDir != null) {
11428            origin = OriginInfo.fromStagedFile(stagedDir);
11429        } else {
11430            origin = OriginInfo.fromStagedContainer(stagedCid);
11431        }
11432
11433        final Message msg = mHandler.obtainMessage(INIT_COPY);
11434        final InstallParams params = new InstallParams(origin, null, observer,
11435                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11436                verificationInfo, user, sessionParams.abiOverride,
11437                sessionParams.grantedRuntimePermissions, certificates);
11438        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11439        msg.obj = params;
11440
11441        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11442                System.identityHashCode(msg.obj));
11443        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11444                System.identityHashCode(msg.obj));
11445
11446        mHandler.sendMessage(msg);
11447    }
11448
11449    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11450            int userId) {
11451        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11452        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11453    }
11454
11455    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11456            int appId, int userId) {
11457        Bundle extras = new Bundle(1);
11458        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11459
11460        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11461                packageName, extras, 0, null, null, new int[] {userId});
11462        try {
11463            IActivityManager am = ActivityManagerNative.getDefault();
11464            if (isSystem && am.isUserRunning(userId, 0)) {
11465                // The just-installed/enabled app is bundled on the system, so presumed
11466                // to be able to run automatically without needing an explicit launch.
11467                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11468                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11469                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11470                        .setPackage(packageName);
11471                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11472                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11473            }
11474        } catch (RemoteException e) {
11475            // shouldn't happen
11476            Slog.w(TAG, "Unable to bootstrap installed package", e);
11477        }
11478    }
11479
11480    @Override
11481    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11482            int userId) {
11483        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11484        PackageSetting pkgSetting;
11485        final int uid = Binder.getCallingUid();
11486        enforceCrossUserPermission(uid, userId,
11487                true /* requireFullPermission */, true /* checkShell */,
11488                "setApplicationHiddenSetting for user " + userId);
11489
11490        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11491            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11492            return false;
11493        }
11494
11495        long callingId = Binder.clearCallingIdentity();
11496        try {
11497            boolean sendAdded = false;
11498            boolean sendRemoved = false;
11499            // writer
11500            synchronized (mPackages) {
11501                pkgSetting = mSettings.mPackages.get(packageName);
11502                if (pkgSetting == null) {
11503                    return false;
11504                }
11505                if (pkgSetting.getHidden(userId) != hidden) {
11506                    pkgSetting.setHidden(hidden, userId);
11507                    mSettings.writePackageRestrictionsLPr(userId);
11508                    if (hidden) {
11509                        sendRemoved = true;
11510                    } else {
11511                        sendAdded = true;
11512                    }
11513                }
11514            }
11515            if (sendAdded) {
11516                sendPackageAddedForUser(packageName, pkgSetting, userId);
11517                return true;
11518            }
11519            if (sendRemoved) {
11520                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11521                        "hiding pkg");
11522                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11523                return true;
11524            }
11525        } finally {
11526            Binder.restoreCallingIdentity(callingId);
11527        }
11528        return false;
11529    }
11530
11531    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11532            int userId) {
11533        final PackageRemovedInfo info = new PackageRemovedInfo();
11534        info.removedPackage = packageName;
11535        info.removedUsers = new int[] {userId};
11536        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11537        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11538    }
11539
11540    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11541        if (pkgList.length > 0) {
11542            Bundle extras = new Bundle(1);
11543            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11544
11545            sendPackageBroadcast(
11546                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11547                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11548                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11549                    new int[] {userId});
11550        }
11551    }
11552
11553    /**
11554     * Returns true if application is not found or there was an error. Otherwise it returns
11555     * the hidden state of the package for the given user.
11556     */
11557    @Override
11558    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11559        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11560        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11561                true /* requireFullPermission */, false /* checkShell */,
11562                "getApplicationHidden for user " + userId);
11563        PackageSetting pkgSetting;
11564        long callingId = Binder.clearCallingIdentity();
11565        try {
11566            // writer
11567            synchronized (mPackages) {
11568                pkgSetting = mSettings.mPackages.get(packageName);
11569                if (pkgSetting == null) {
11570                    return true;
11571                }
11572                return pkgSetting.getHidden(userId);
11573            }
11574        } finally {
11575            Binder.restoreCallingIdentity(callingId);
11576        }
11577    }
11578
11579    /**
11580     * @hide
11581     */
11582    @Override
11583    public int installExistingPackageAsUser(String packageName, int userId) {
11584        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11585                null);
11586        PackageSetting pkgSetting;
11587        final int uid = Binder.getCallingUid();
11588        enforceCrossUserPermission(uid, userId,
11589                true /* requireFullPermission */, true /* checkShell */,
11590                "installExistingPackage for user " + userId);
11591        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11592            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11593        }
11594
11595        long callingId = Binder.clearCallingIdentity();
11596        try {
11597            boolean installed = false;
11598
11599            // writer
11600            synchronized (mPackages) {
11601                pkgSetting = mSettings.mPackages.get(packageName);
11602                if (pkgSetting == null) {
11603                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11604                }
11605                if (!pkgSetting.getInstalled(userId)) {
11606                    pkgSetting.setInstalled(true, userId);
11607                    pkgSetting.setHidden(false, userId);
11608                    mSettings.writePackageRestrictionsLPr(userId);
11609                    installed = true;
11610                }
11611            }
11612
11613            if (installed) {
11614                if (pkgSetting.pkg != null) {
11615                    synchronized (mInstallLock) {
11616                        // We don't need to freeze for a brand new install
11617                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11618                    }
11619                }
11620                sendPackageAddedForUser(packageName, pkgSetting, userId);
11621            }
11622        } finally {
11623            Binder.restoreCallingIdentity(callingId);
11624        }
11625
11626        return PackageManager.INSTALL_SUCCEEDED;
11627    }
11628
11629    boolean isUserRestricted(int userId, String restrictionKey) {
11630        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11631        if (restrictions.getBoolean(restrictionKey, false)) {
11632            Log.w(TAG, "User is restricted: " + restrictionKey);
11633            return true;
11634        }
11635        return false;
11636    }
11637
11638    @Override
11639    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11640            int userId) {
11641        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11642        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11643                true /* requireFullPermission */, true /* checkShell */,
11644                "setPackagesSuspended for user " + userId);
11645
11646        if (ArrayUtils.isEmpty(packageNames)) {
11647            return packageNames;
11648        }
11649
11650        // List of package names for whom the suspended state has changed.
11651        List<String> changedPackages = new ArrayList<>(packageNames.length);
11652        // List of package names for whom the suspended state is not set as requested in this
11653        // method.
11654        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11655        long callingId = Binder.clearCallingIdentity();
11656        try {
11657            for (int i = 0; i < packageNames.length; i++) {
11658                String packageName = packageNames[i];
11659                boolean changed = false;
11660                final int appId;
11661                synchronized (mPackages) {
11662                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11663                    if (pkgSetting == null) {
11664                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11665                                + "\". Skipping suspending/un-suspending.");
11666                        unactionedPackages.add(packageName);
11667                        continue;
11668                    }
11669                    appId = pkgSetting.appId;
11670                    if (pkgSetting.getSuspended(userId) != suspended) {
11671                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11672                            unactionedPackages.add(packageName);
11673                            continue;
11674                        }
11675                        pkgSetting.setSuspended(suspended, userId);
11676                        mSettings.writePackageRestrictionsLPr(userId);
11677                        changed = true;
11678                        changedPackages.add(packageName);
11679                    }
11680                }
11681
11682                if (changed && suspended) {
11683                    killApplication(packageName, UserHandle.getUid(userId, appId),
11684                            "suspending package");
11685                }
11686            }
11687        } finally {
11688            Binder.restoreCallingIdentity(callingId);
11689        }
11690
11691        if (!changedPackages.isEmpty()) {
11692            sendPackagesSuspendedForUser(changedPackages.toArray(
11693                    new String[changedPackages.size()]), userId, suspended);
11694        }
11695
11696        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11697    }
11698
11699    @Override
11700    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11701        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11702                true /* requireFullPermission */, false /* checkShell */,
11703                "isPackageSuspendedForUser for user " + userId);
11704        synchronized (mPackages) {
11705            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11706            if (pkgSetting == null) {
11707                throw new IllegalArgumentException("Unknown target package: " + packageName);
11708            }
11709            return pkgSetting.getSuspended(userId);
11710        }
11711    }
11712
11713    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11714        if (isPackageDeviceAdmin(packageName, userId)) {
11715            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11716                    + "\": has an active device admin");
11717            return false;
11718        }
11719
11720        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11721        if (packageName.equals(activeLauncherPackageName)) {
11722            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11723                    + "\": contains the active launcher");
11724            return false;
11725        }
11726
11727        if (packageName.equals(mRequiredInstallerPackage)) {
11728            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11729                    + "\": required for package installation");
11730            return false;
11731        }
11732
11733        if (packageName.equals(mRequiredVerifierPackage)) {
11734            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11735                    + "\": required for package verification");
11736            return false;
11737        }
11738
11739        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11740            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11741                    + "\": is the default dialer");
11742            return false;
11743        }
11744
11745        return true;
11746    }
11747
11748    private String getActiveLauncherPackageName(int userId) {
11749        Intent intent = new Intent(Intent.ACTION_MAIN);
11750        intent.addCategory(Intent.CATEGORY_HOME);
11751        ResolveInfo resolveInfo = resolveIntent(
11752                intent,
11753                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11754                PackageManager.MATCH_DEFAULT_ONLY,
11755                userId);
11756
11757        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11758    }
11759
11760    private String getDefaultDialerPackageName(int userId) {
11761        synchronized (mPackages) {
11762            return mSettings.getDefaultDialerPackageNameLPw(userId);
11763        }
11764    }
11765
11766    @Override
11767    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11768        mContext.enforceCallingOrSelfPermission(
11769                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11770                "Only package verification agents can verify applications");
11771
11772        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11773        final PackageVerificationResponse response = new PackageVerificationResponse(
11774                verificationCode, Binder.getCallingUid());
11775        msg.arg1 = id;
11776        msg.obj = response;
11777        mHandler.sendMessage(msg);
11778    }
11779
11780    @Override
11781    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11782            long millisecondsToDelay) {
11783        mContext.enforceCallingOrSelfPermission(
11784                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11785                "Only package verification agents can extend verification timeouts");
11786
11787        final PackageVerificationState state = mPendingVerification.get(id);
11788        final PackageVerificationResponse response = new PackageVerificationResponse(
11789                verificationCodeAtTimeout, Binder.getCallingUid());
11790
11791        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11792            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11793        }
11794        if (millisecondsToDelay < 0) {
11795            millisecondsToDelay = 0;
11796        }
11797        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11798                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11799            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11800        }
11801
11802        if ((state != null) && !state.timeoutExtended()) {
11803            state.extendTimeout();
11804
11805            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11806            msg.arg1 = id;
11807            msg.obj = response;
11808            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11809        }
11810    }
11811
11812    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11813            int verificationCode, UserHandle user) {
11814        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11815        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11816        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11817        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11818        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11819
11820        mContext.sendBroadcastAsUser(intent, user,
11821                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11822    }
11823
11824    private ComponentName matchComponentForVerifier(String packageName,
11825            List<ResolveInfo> receivers) {
11826        ActivityInfo targetReceiver = null;
11827
11828        final int NR = receivers.size();
11829        for (int i = 0; i < NR; i++) {
11830            final ResolveInfo info = receivers.get(i);
11831            if (info.activityInfo == null) {
11832                continue;
11833            }
11834
11835            if (packageName.equals(info.activityInfo.packageName)) {
11836                targetReceiver = info.activityInfo;
11837                break;
11838            }
11839        }
11840
11841        if (targetReceiver == null) {
11842            return null;
11843        }
11844
11845        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11846    }
11847
11848    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11849            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11850        if (pkgInfo.verifiers.length == 0) {
11851            return null;
11852        }
11853
11854        final int N = pkgInfo.verifiers.length;
11855        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11856        for (int i = 0; i < N; i++) {
11857            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11858
11859            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11860                    receivers);
11861            if (comp == null) {
11862                continue;
11863            }
11864
11865            final int verifierUid = getUidForVerifier(verifierInfo);
11866            if (verifierUid == -1) {
11867                continue;
11868            }
11869
11870            if (DEBUG_VERIFY) {
11871                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11872                        + " with the correct signature");
11873            }
11874            sufficientVerifiers.add(comp);
11875            verificationState.addSufficientVerifier(verifierUid);
11876        }
11877
11878        return sufficientVerifiers;
11879    }
11880
11881    private int getUidForVerifier(VerifierInfo verifierInfo) {
11882        synchronized (mPackages) {
11883            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11884            if (pkg == null) {
11885                return -1;
11886            } else if (pkg.mSignatures.length != 1) {
11887                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11888                        + " has more than one signature; ignoring");
11889                return -1;
11890            }
11891
11892            /*
11893             * If the public key of the package's signature does not match
11894             * our expected public key, then this is a different package and
11895             * we should skip.
11896             */
11897
11898            final byte[] expectedPublicKey;
11899            try {
11900                final Signature verifierSig = pkg.mSignatures[0];
11901                final PublicKey publicKey = verifierSig.getPublicKey();
11902                expectedPublicKey = publicKey.getEncoded();
11903            } catch (CertificateException e) {
11904                return -1;
11905            }
11906
11907            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11908
11909            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11910                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11911                        + " does not have the expected public key; ignoring");
11912                return -1;
11913            }
11914
11915            return pkg.applicationInfo.uid;
11916        }
11917    }
11918
11919    @Override
11920    public void finishPackageInstall(int token, boolean didLaunch) {
11921        enforceSystemOrRoot("Only the system is allowed to finish installs");
11922
11923        if (DEBUG_INSTALL) {
11924            Slog.v(TAG, "BM finishing package install for " + token);
11925        }
11926        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11927
11928        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11929        mHandler.sendMessage(msg);
11930    }
11931
11932    /**
11933     * Get the verification agent timeout.
11934     *
11935     * @return verification timeout in milliseconds
11936     */
11937    private long getVerificationTimeout() {
11938        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11939                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11940                DEFAULT_VERIFICATION_TIMEOUT);
11941    }
11942
11943    /**
11944     * Get the default verification agent response code.
11945     *
11946     * @return default verification response code
11947     */
11948    private int getDefaultVerificationResponse() {
11949        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11950                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11951                DEFAULT_VERIFICATION_RESPONSE);
11952    }
11953
11954    /**
11955     * Check whether or not package verification has been enabled.
11956     *
11957     * @return true if verification should be performed
11958     */
11959    private boolean isVerificationEnabled(int userId, int installFlags) {
11960        if (!DEFAULT_VERIFY_ENABLE) {
11961            return false;
11962        }
11963        // Ephemeral apps don't get the full verification treatment
11964        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11965            if (DEBUG_EPHEMERAL) {
11966                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11967            }
11968            return false;
11969        }
11970
11971        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11972
11973        // Check if installing from ADB
11974        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11975            // Do not run verification in a test harness environment
11976            if (ActivityManager.isRunningInTestHarness()) {
11977                return false;
11978            }
11979            if (ensureVerifyAppsEnabled) {
11980                return true;
11981            }
11982            // Check if the developer does not want package verification for ADB installs
11983            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11984                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11985                return false;
11986            }
11987        }
11988
11989        if (ensureVerifyAppsEnabled) {
11990            return true;
11991        }
11992
11993        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11994                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11995    }
11996
11997    @Override
11998    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11999            throws RemoteException {
12000        mContext.enforceCallingOrSelfPermission(
12001                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12002                "Only intentfilter verification agents can verify applications");
12003
12004        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12005        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12006                Binder.getCallingUid(), verificationCode, failedDomains);
12007        msg.arg1 = id;
12008        msg.obj = response;
12009        mHandler.sendMessage(msg);
12010    }
12011
12012    @Override
12013    public int getIntentVerificationStatus(String packageName, int userId) {
12014        synchronized (mPackages) {
12015            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12016        }
12017    }
12018
12019    @Override
12020    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12021        mContext.enforceCallingOrSelfPermission(
12022                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12023
12024        boolean result = false;
12025        synchronized (mPackages) {
12026            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12027        }
12028        if (result) {
12029            scheduleWritePackageRestrictionsLocked(userId);
12030        }
12031        return result;
12032    }
12033
12034    @Override
12035    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12036            String packageName) {
12037        synchronized (mPackages) {
12038            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12039        }
12040    }
12041
12042    @Override
12043    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12044        if (TextUtils.isEmpty(packageName)) {
12045            return ParceledListSlice.emptyList();
12046        }
12047        synchronized (mPackages) {
12048            PackageParser.Package pkg = mPackages.get(packageName);
12049            if (pkg == null || pkg.activities == null) {
12050                return ParceledListSlice.emptyList();
12051            }
12052            final int count = pkg.activities.size();
12053            ArrayList<IntentFilter> result = new ArrayList<>();
12054            for (int n=0; n<count; n++) {
12055                PackageParser.Activity activity = pkg.activities.get(n);
12056                if (activity.intents != null && activity.intents.size() > 0) {
12057                    result.addAll(activity.intents);
12058                }
12059            }
12060            return new ParceledListSlice<>(result);
12061        }
12062    }
12063
12064    @Override
12065    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12066        mContext.enforceCallingOrSelfPermission(
12067                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12068
12069        synchronized (mPackages) {
12070            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12071            if (packageName != null) {
12072                result |= updateIntentVerificationStatus(packageName,
12073                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12074                        userId);
12075                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12076                        packageName, userId);
12077            }
12078            return result;
12079        }
12080    }
12081
12082    @Override
12083    public String getDefaultBrowserPackageName(int userId) {
12084        synchronized (mPackages) {
12085            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12086        }
12087    }
12088
12089    /**
12090     * Get the "allow unknown sources" setting.
12091     *
12092     * @return the current "allow unknown sources" setting
12093     */
12094    private int getUnknownSourcesSettings() {
12095        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12096                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12097                -1);
12098    }
12099
12100    @Override
12101    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12102        final int uid = Binder.getCallingUid();
12103        // writer
12104        synchronized (mPackages) {
12105            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12106            if (targetPackageSetting == null) {
12107                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12108            }
12109
12110            PackageSetting installerPackageSetting;
12111            if (installerPackageName != null) {
12112                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12113                if (installerPackageSetting == null) {
12114                    throw new IllegalArgumentException("Unknown installer package: "
12115                            + installerPackageName);
12116                }
12117            } else {
12118                installerPackageSetting = null;
12119            }
12120
12121            Signature[] callerSignature;
12122            Object obj = mSettings.getUserIdLPr(uid);
12123            if (obj != null) {
12124                if (obj instanceof SharedUserSetting) {
12125                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12126                } else if (obj instanceof PackageSetting) {
12127                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12128                } else {
12129                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12130                }
12131            } else {
12132                throw new SecurityException("Unknown calling UID: " + uid);
12133            }
12134
12135            // Verify: can't set installerPackageName to a package that is
12136            // not signed with the same cert as the caller.
12137            if (installerPackageSetting != null) {
12138                if (compareSignatures(callerSignature,
12139                        installerPackageSetting.signatures.mSignatures)
12140                        != PackageManager.SIGNATURE_MATCH) {
12141                    throw new SecurityException(
12142                            "Caller does not have same cert as new installer package "
12143                            + installerPackageName);
12144                }
12145            }
12146
12147            // Verify: if target already has an installer package, it must
12148            // be signed with the same cert as the caller.
12149            if (targetPackageSetting.installerPackageName != null) {
12150                PackageSetting setting = mSettings.mPackages.get(
12151                        targetPackageSetting.installerPackageName);
12152                // If the currently set package isn't valid, then it's always
12153                // okay to change it.
12154                if (setting != null) {
12155                    if (compareSignatures(callerSignature,
12156                            setting.signatures.mSignatures)
12157                            != PackageManager.SIGNATURE_MATCH) {
12158                        throw new SecurityException(
12159                                "Caller does not have same cert as old installer package "
12160                                + targetPackageSetting.installerPackageName);
12161                    }
12162                }
12163            }
12164
12165            // Okay!
12166            targetPackageSetting.installerPackageName = installerPackageName;
12167            if (installerPackageName != null) {
12168                mSettings.mInstallerPackages.add(installerPackageName);
12169            }
12170            scheduleWriteSettingsLocked();
12171        }
12172    }
12173
12174    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12175        // Queue up an async operation since the package installation may take a little while.
12176        mHandler.post(new Runnable() {
12177            public void run() {
12178                mHandler.removeCallbacks(this);
12179                 // Result object to be returned
12180                PackageInstalledInfo res = new PackageInstalledInfo();
12181                res.setReturnCode(currentStatus);
12182                res.uid = -1;
12183                res.pkg = null;
12184                res.removedInfo = null;
12185                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12186                    args.doPreInstall(res.returnCode);
12187                    synchronized (mInstallLock) {
12188                        installPackageTracedLI(args, res);
12189                    }
12190                    args.doPostInstall(res.returnCode, res.uid);
12191                }
12192
12193                // A restore should be performed at this point if (a) the install
12194                // succeeded, (b) the operation is not an update, and (c) the new
12195                // package has not opted out of backup participation.
12196                final boolean update = res.removedInfo != null
12197                        && res.removedInfo.removedPackage != null;
12198                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12199                boolean doRestore = !update
12200                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12201
12202                // Set up the post-install work request bookkeeping.  This will be used
12203                // and cleaned up by the post-install event handling regardless of whether
12204                // there's a restore pass performed.  Token values are >= 1.
12205                int token;
12206                if (mNextInstallToken < 0) mNextInstallToken = 1;
12207                token = mNextInstallToken++;
12208
12209                PostInstallData data = new PostInstallData(args, res);
12210                mRunningInstalls.put(token, data);
12211                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12212
12213                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12214                    // Pass responsibility to the Backup Manager.  It will perform a
12215                    // restore if appropriate, then pass responsibility back to the
12216                    // Package Manager to run the post-install observer callbacks
12217                    // and broadcasts.
12218                    IBackupManager bm = IBackupManager.Stub.asInterface(
12219                            ServiceManager.getService(Context.BACKUP_SERVICE));
12220                    if (bm != null) {
12221                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12222                                + " to BM for possible restore");
12223                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12224                        try {
12225                            // TODO: http://b/22388012
12226                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12227                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12228                            } else {
12229                                doRestore = false;
12230                            }
12231                        } catch (RemoteException e) {
12232                            // can't happen; the backup manager is local
12233                        } catch (Exception e) {
12234                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12235                            doRestore = false;
12236                        }
12237                    } else {
12238                        Slog.e(TAG, "Backup Manager not found!");
12239                        doRestore = false;
12240                    }
12241                }
12242
12243                if (!doRestore) {
12244                    // No restore possible, or the Backup Manager was mysteriously not
12245                    // available -- just fire the post-install work request directly.
12246                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12247
12248                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12249
12250                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12251                    mHandler.sendMessage(msg);
12252                }
12253            }
12254        });
12255    }
12256
12257    /**
12258     * Callback from PackageSettings whenever an app is first transitioned out of the
12259     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12260     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12261     * here whether the app is the target of an ongoing install, and only send the
12262     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12263     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12264     * handling.
12265     */
12266    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12267        // Serialize this with the rest of the install-process message chain.  In the
12268        // restore-at-install case, this Runnable will necessarily run before the
12269        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12270        // are coherent.  In the non-restore case, the app has already completed install
12271        // and been launched through some other means, so it is not in a problematic
12272        // state for observers to see the FIRST_LAUNCH signal.
12273        mHandler.post(new Runnable() {
12274            @Override
12275            public void run() {
12276                for (int i = 0; i < mRunningInstalls.size(); i++) {
12277                    final PostInstallData data = mRunningInstalls.valueAt(i);
12278                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12279                        // right package; but is it for the right user?
12280                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12281                            if (userId == data.res.newUsers[uIndex]) {
12282                                if (DEBUG_BACKUP) {
12283                                    Slog.i(TAG, "Package " + pkgName
12284                                            + " being restored so deferring FIRST_LAUNCH");
12285                                }
12286                                return;
12287                            }
12288                        }
12289                    }
12290                }
12291                // didn't find it, so not being restored
12292                if (DEBUG_BACKUP) {
12293                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12294                }
12295                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12296            }
12297        });
12298    }
12299
12300    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12301        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12302                installerPkg, null, userIds);
12303    }
12304
12305    private abstract class HandlerParams {
12306        private static final int MAX_RETRIES = 4;
12307
12308        /**
12309         * Number of times startCopy() has been attempted and had a non-fatal
12310         * error.
12311         */
12312        private int mRetries = 0;
12313
12314        /** User handle for the user requesting the information or installation. */
12315        private final UserHandle mUser;
12316        String traceMethod;
12317        int traceCookie;
12318
12319        HandlerParams(UserHandle user) {
12320            mUser = user;
12321        }
12322
12323        UserHandle getUser() {
12324            return mUser;
12325        }
12326
12327        HandlerParams setTraceMethod(String traceMethod) {
12328            this.traceMethod = traceMethod;
12329            return this;
12330        }
12331
12332        HandlerParams setTraceCookie(int traceCookie) {
12333            this.traceCookie = traceCookie;
12334            return this;
12335        }
12336
12337        final boolean startCopy() {
12338            boolean res;
12339            try {
12340                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12341
12342                if (++mRetries > MAX_RETRIES) {
12343                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12344                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12345                    handleServiceError();
12346                    return false;
12347                } else {
12348                    handleStartCopy();
12349                    res = true;
12350                }
12351            } catch (RemoteException e) {
12352                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12353                mHandler.sendEmptyMessage(MCS_RECONNECT);
12354                res = false;
12355            }
12356            handleReturnCode();
12357            return res;
12358        }
12359
12360        final void serviceError() {
12361            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12362            handleServiceError();
12363            handleReturnCode();
12364        }
12365
12366        abstract void handleStartCopy() throws RemoteException;
12367        abstract void handleServiceError();
12368        abstract void handleReturnCode();
12369    }
12370
12371    class MeasureParams extends HandlerParams {
12372        private final PackageStats mStats;
12373        private boolean mSuccess;
12374
12375        private final IPackageStatsObserver mObserver;
12376
12377        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12378            super(new UserHandle(stats.userHandle));
12379            mObserver = observer;
12380            mStats = stats;
12381        }
12382
12383        @Override
12384        public String toString() {
12385            return "MeasureParams{"
12386                + Integer.toHexString(System.identityHashCode(this))
12387                + " " + mStats.packageName + "}";
12388        }
12389
12390        @Override
12391        void handleStartCopy() throws RemoteException {
12392            synchronized (mInstallLock) {
12393                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12394            }
12395
12396            if (mSuccess) {
12397                final boolean mounted;
12398                if (Environment.isExternalStorageEmulated()) {
12399                    mounted = true;
12400                } else {
12401                    final String status = Environment.getExternalStorageState();
12402                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12403                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12404                }
12405
12406                if (mounted) {
12407                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12408
12409                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12410                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12411
12412                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12413                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12414
12415                    // Always subtract cache size, since it's a subdirectory
12416                    mStats.externalDataSize -= mStats.externalCacheSize;
12417
12418                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12419                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12420
12421                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12422                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12423                }
12424            }
12425        }
12426
12427        @Override
12428        void handleReturnCode() {
12429            if (mObserver != null) {
12430                try {
12431                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12432                } catch (RemoteException e) {
12433                    Slog.i(TAG, "Observer no longer exists.");
12434                }
12435            }
12436        }
12437
12438        @Override
12439        void handleServiceError() {
12440            Slog.e(TAG, "Could not measure application " + mStats.packageName
12441                            + " external storage");
12442        }
12443    }
12444
12445    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12446            throws RemoteException {
12447        long result = 0;
12448        for (File path : paths) {
12449            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12450        }
12451        return result;
12452    }
12453
12454    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12455        for (File path : paths) {
12456            try {
12457                mcs.clearDirectory(path.getAbsolutePath());
12458            } catch (RemoteException e) {
12459            }
12460        }
12461    }
12462
12463    static class OriginInfo {
12464        /**
12465         * Location where install is coming from, before it has been
12466         * copied/renamed into place. This could be a single monolithic APK
12467         * file, or a cluster directory. This location may be untrusted.
12468         */
12469        final File file;
12470        final String cid;
12471
12472        /**
12473         * Flag indicating that {@link #file} or {@link #cid} has already been
12474         * staged, meaning downstream users don't need to defensively copy the
12475         * contents.
12476         */
12477        final boolean staged;
12478
12479        /**
12480         * Flag indicating that {@link #file} or {@link #cid} is an already
12481         * installed app that is being moved.
12482         */
12483        final boolean existing;
12484
12485        final String resolvedPath;
12486        final File resolvedFile;
12487
12488        static OriginInfo fromNothing() {
12489            return new OriginInfo(null, null, false, false);
12490        }
12491
12492        static OriginInfo fromUntrustedFile(File file) {
12493            return new OriginInfo(file, null, false, false);
12494        }
12495
12496        static OriginInfo fromExistingFile(File file) {
12497            return new OriginInfo(file, null, false, true);
12498        }
12499
12500        static OriginInfo fromStagedFile(File file) {
12501            return new OriginInfo(file, null, true, false);
12502        }
12503
12504        static OriginInfo fromStagedContainer(String cid) {
12505            return new OriginInfo(null, cid, true, false);
12506        }
12507
12508        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12509            this.file = file;
12510            this.cid = cid;
12511            this.staged = staged;
12512            this.existing = existing;
12513
12514            if (cid != null) {
12515                resolvedPath = PackageHelper.getSdDir(cid);
12516                resolvedFile = new File(resolvedPath);
12517            } else if (file != null) {
12518                resolvedPath = file.getAbsolutePath();
12519                resolvedFile = file;
12520            } else {
12521                resolvedPath = null;
12522                resolvedFile = null;
12523            }
12524        }
12525    }
12526
12527    static class MoveInfo {
12528        final int moveId;
12529        final String fromUuid;
12530        final String toUuid;
12531        final String packageName;
12532        final String dataAppName;
12533        final int appId;
12534        final String seinfo;
12535        final int targetSdkVersion;
12536
12537        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12538                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12539            this.moveId = moveId;
12540            this.fromUuid = fromUuid;
12541            this.toUuid = toUuid;
12542            this.packageName = packageName;
12543            this.dataAppName = dataAppName;
12544            this.appId = appId;
12545            this.seinfo = seinfo;
12546            this.targetSdkVersion = targetSdkVersion;
12547        }
12548    }
12549
12550    static class VerificationInfo {
12551        /** A constant used to indicate that a uid value is not present. */
12552        public static final int NO_UID = -1;
12553
12554        /** URI referencing where the package was downloaded from. */
12555        final Uri originatingUri;
12556
12557        /** HTTP referrer URI associated with the originatingURI. */
12558        final Uri referrer;
12559
12560        /** UID of the application that the install request originated from. */
12561        final int originatingUid;
12562
12563        /** UID of application requesting the install */
12564        final int installerUid;
12565
12566        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12567            this.originatingUri = originatingUri;
12568            this.referrer = referrer;
12569            this.originatingUid = originatingUid;
12570            this.installerUid = installerUid;
12571        }
12572    }
12573
12574    class InstallParams extends HandlerParams {
12575        final OriginInfo origin;
12576        final MoveInfo move;
12577        final IPackageInstallObserver2 observer;
12578        int installFlags;
12579        final String installerPackageName;
12580        final String volumeUuid;
12581        private InstallArgs mArgs;
12582        private int mRet;
12583        final String packageAbiOverride;
12584        final String[] grantedRuntimePermissions;
12585        final VerificationInfo verificationInfo;
12586        final Certificate[][] certificates;
12587
12588        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12589                int installFlags, String installerPackageName, String volumeUuid,
12590                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12591                String[] grantedPermissions, Certificate[][] certificates) {
12592            super(user);
12593            this.origin = origin;
12594            this.move = move;
12595            this.observer = observer;
12596            this.installFlags = installFlags;
12597            this.installerPackageName = installerPackageName;
12598            this.volumeUuid = volumeUuid;
12599            this.verificationInfo = verificationInfo;
12600            this.packageAbiOverride = packageAbiOverride;
12601            this.grantedRuntimePermissions = grantedPermissions;
12602            this.certificates = certificates;
12603        }
12604
12605        @Override
12606        public String toString() {
12607            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12608                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12609        }
12610
12611        private int installLocationPolicy(PackageInfoLite pkgLite) {
12612            String packageName = pkgLite.packageName;
12613            int installLocation = pkgLite.installLocation;
12614            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12615            // reader
12616            synchronized (mPackages) {
12617                // Currently installed package which the new package is attempting to replace or
12618                // null if no such package is installed.
12619                PackageParser.Package installedPkg = mPackages.get(packageName);
12620                // Package which currently owns the data which the new package will own if installed.
12621                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12622                // will be null whereas dataOwnerPkg will contain information about the package
12623                // which was uninstalled while keeping its data.
12624                PackageParser.Package dataOwnerPkg = installedPkg;
12625                if (dataOwnerPkg  == null) {
12626                    PackageSetting ps = mSettings.mPackages.get(packageName);
12627                    if (ps != null) {
12628                        dataOwnerPkg = ps.pkg;
12629                    }
12630                }
12631
12632                if (dataOwnerPkg != null) {
12633                    // If installed, the package will get access to data left on the device by its
12634                    // predecessor. As a security measure, this is permited only if this is not a
12635                    // version downgrade or if the predecessor package is marked as debuggable and
12636                    // a downgrade is explicitly requested.
12637                    //
12638                    // On debuggable platform builds, downgrades are permitted even for
12639                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12640                    // not offer security guarantees and thus it's OK to disable some security
12641                    // mechanisms to make debugging/testing easier on those builds. However, even on
12642                    // debuggable builds downgrades of packages are permitted only if requested via
12643                    // installFlags. This is because we aim to keep the behavior of debuggable
12644                    // platform builds as close as possible to the behavior of non-debuggable
12645                    // platform builds.
12646                    final boolean downgradeRequested =
12647                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12648                    final boolean packageDebuggable =
12649                                (dataOwnerPkg.applicationInfo.flags
12650                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12651                    final boolean downgradePermitted =
12652                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12653                    if (!downgradePermitted) {
12654                        try {
12655                            checkDowngrade(dataOwnerPkg, pkgLite);
12656                        } catch (PackageManagerException e) {
12657                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12658                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12659                        }
12660                    }
12661                }
12662
12663                if (installedPkg != null) {
12664                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12665                        // Check for updated system application.
12666                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12667                            if (onSd) {
12668                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12669                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12670                            }
12671                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12672                        } else {
12673                            if (onSd) {
12674                                // Install flag overrides everything.
12675                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12676                            }
12677                            // If current upgrade specifies particular preference
12678                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12679                                // Application explicitly specified internal.
12680                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12681                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12682                                // App explictly prefers external. Let policy decide
12683                            } else {
12684                                // Prefer previous location
12685                                if (isExternal(installedPkg)) {
12686                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12687                                }
12688                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12689                            }
12690                        }
12691                    } else {
12692                        // Invalid install. Return error code
12693                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12694                    }
12695                }
12696            }
12697            // All the special cases have been taken care of.
12698            // Return result based on recommended install location.
12699            if (onSd) {
12700                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12701            }
12702            return pkgLite.recommendedInstallLocation;
12703        }
12704
12705        /*
12706         * Invoke remote method to get package information and install
12707         * location values. Override install location based on default
12708         * policy if needed and then create install arguments based
12709         * on the install location.
12710         */
12711        public void handleStartCopy() throws RemoteException {
12712            int ret = PackageManager.INSTALL_SUCCEEDED;
12713
12714            // If we're already staged, we've firmly committed to an install location
12715            if (origin.staged) {
12716                if (origin.file != null) {
12717                    installFlags |= PackageManager.INSTALL_INTERNAL;
12718                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12719                } else if (origin.cid != null) {
12720                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12721                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12722                } else {
12723                    throw new IllegalStateException("Invalid stage location");
12724                }
12725            }
12726
12727            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12728            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12729            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12730            PackageInfoLite pkgLite = null;
12731
12732            if (onInt && onSd) {
12733                // Check if both bits are set.
12734                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12735                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12736            } else if (onSd && ephemeral) {
12737                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12738                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12739            } else {
12740                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12741                        packageAbiOverride);
12742
12743                if (DEBUG_EPHEMERAL && ephemeral) {
12744                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12745                }
12746
12747                /*
12748                 * If we have too little free space, try to free cache
12749                 * before giving up.
12750                 */
12751                if (!origin.staged && pkgLite.recommendedInstallLocation
12752                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12753                    // TODO: focus freeing disk space on the target device
12754                    final StorageManager storage = StorageManager.from(mContext);
12755                    final long lowThreshold = storage.getStorageLowBytes(
12756                            Environment.getDataDirectory());
12757
12758                    final long sizeBytes = mContainerService.calculateInstalledSize(
12759                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12760
12761                    try {
12762                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12763                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12764                                installFlags, packageAbiOverride);
12765                    } catch (InstallerException e) {
12766                        Slog.w(TAG, "Failed to free cache", e);
12767                    }
12768
12769                    /*
12770                     * The cache free must have deleted the file we
12771                     * downloaded to install.
12772                     *
12773                     * TODO: fix the "freeCache" call to not delete
12774                     *       the file we care about.
12775                     */
12776                    if (pkgLite.recommendedInstallLocation
12777                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12778                        pkgLite.recommendedInstallLocation
12779                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12780                    }
12781                }
12782            }
12783
12784            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12785                int loc = pkgLite.recommendedInstallLocation;
12786                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12787                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12788                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12789                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12790                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12791                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12792                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12793                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12794                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12795                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12796                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12797                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12798                } else {
12799                    // Override with defaults if needed.
12800                    loc = installLocationPolicy(pkgLite);
12801                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12802                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12803                    } else if (!onSd && !onInt) {
12804                        // Override install location with flags
12805                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12806                            // Set the flag to install on external media.
12807                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12808                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12809                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12810                            if (DEBUG_EPHEMERAL) {
12811                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12812                            }
12813                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12814                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12815                                    |PackageManager.INSTALL_INTERNAL);
12816                        } else {
12817                            // Make sure the flag for installing on external
12818                            // media is unset
12819                            installFlags |= PackageManager.INSTALL_INTERNAL;
12820                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12821                        }
12822                    }
12823                }
12824            }
12825
12826            final InstallArgs args = createInstallArgs(this);
12827            mArgs = args;
12828
12829            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12830                // TODO: http://b/22976637
12831                // Apps installed for "all" users use the device owner to verify the app
12832                UserHandle verifierUser = getUser();
12833                if (verifierUser == UserHandle.ALL) {
12834                    verifierUser = UserHandle.SYSTEM;
12835                }
12836
12837                /*
12838                 * Determine if we have any installed package verifiers. If we
12839                 * do, then we'll defer to them to verify the packages.
12840                 */
12841                final int requiredUid = mRequiredVerifierPackage == null ? -1
12842                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12843                                verifierUser.getIdentifier());
12844                if (!origin.existing && requiredUid != -1
12845                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12846                    final Intent verification = new Intent(
12847                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12848                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12849                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12850                            PACKAGE_MIME_TYPE);
12851                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12852
12853                    // Query all live verifiers based on current user state
12854                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12855                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12856
12857                    if (DEBUG_VERIFY) {
12858                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12859                                + verification.toString() + " with " + pkgLite.verifiers.length
12860                                + " optional verifiers");
12861                    }
12862
12863                    final int verificationId = mPendingVerificationToken++;
12864
12865                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12866
12867                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12868                            installerPackageName);
12869
12870                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12871                            installFlags);
12872
12873                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12874                            pkgLite.packageName);
12875
12876                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12877                            pkgLite.versionCode);
12878
12879                    if (verificationInfo != null) {
12880                        if (verificationInfo.originatingUri != null) {
12881                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12882                                    verificationInfo.originatingUri);
12883                        }
12884                        if (verificationInfo.referrer != null) {
12885                            verification.putExtra(Intent.EXTRA_REFERRER,
12886                                    verificationInfo.referrer);
12887                        }
12888                        if (verificationInfo.originatingUid >= 0) {
12889                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12890                                    verificationInfo.originatingUid);
12891                        }
12892                        if (verificationInfo.installerUid >= 0) {
12893                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12894                                    verificationInfo.installerUid);
12895                        }
12896                    }
12897
12898                    final PackageVerificationState verificationState = new PackageVerificationState(
12899                            requiredUid, args);
12900
12901                    mPendingVerification.append(verificationId, verificationState);
12902
12903                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12904                            receivers, verificationState);
12905
12906                    /*
12907                     * If any sufficient verifiers were listed in the package
12908                     * manifest, attempt to ask them.
12909                     */
12910                    if (sufficientVerifiers != null) {
12911                        final int N = sufficientVerifiers.size();
12912                        if (N == 0) {
12913                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12914                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12915                        } else {
12916                            for (int i = 0; i < N; i++) {
12917                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12918
12919                                final Intent sufficientIntent = new Intent(verification);
12920                                sufficientIntent.setComponent(verifierComponent);
12921                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12922                            }
12923                        }
12924                    }
12925
12926                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12927                            mRequiredVerifierPackage, receivers);
12928                    if (ret == PackageManager.INSTALL_SUCCEEDED
12929                            && mRequiredVerifierPackage != null) {
12930                        Trace.asyncTraceBegin(
12931                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12932                        /*
12933                         * Send the intent to the required verification agent,
12934                         * but only start the verification timeout after the
12935                         * target BroadcastReceivers have run.
12936                         */
12937                        verification.setComponent(requiredVerifierComponent);
12938                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12939                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12940                                new BroadcastReceiver() {
12941                                    @Override
12942                                    public void onReceive(Context context, Intent intent) {
12943                                        final Message msg = mHandler
12944                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12945                                        msg.arg1 = verificationId;
12946                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12947                                    }
12948                                }, null, 0, null, null);
12949
12950                        /*
12951                         * We don't want the copy to proceed until verification
12952                         * succeeds, so null out this field.
12953                         */
12954                        mArgs = null;
12955                    }
12956                } else {
12957                    /*
12958                     * No package verification is enabled, so immediately start
12959                     * the remote call to initiate copy using temporary file.
12960                     */
12961                    ret = args.copyApk(mContainerService, true);
12962                }
12963            }
12964
12965            mRet = ret;
12966        }
12967
12968        @Override
12969        void handleReturnCode() {
12970            // If mArgs is null, then MCS couldn't be reached. When it
12971            // reconnects, it will try again to install. At that point, this
12972            // will succeed.
12973            if (mArgs != null) {
12974                processPendingInstall(mArgs, mRet);
12975            }
12976        }
12977
12978        @Override
12979        void handleServiceError() {
12980            mArgs = createInstallArgs(this);
12981            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12982        }
12983
12984        public boolean isForwardLocked() {
12985            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12986        }
12987    }
12988
12989    /**
12990     * Used during creation of InstallArgs
12991     *
12992     * @param installFlags package installation flags
12993     * @return true if should be installed on external storage
12994     */
12995    private static boolean installOnExternalAsec(int installFlags) {
12996        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12997            return false;
12998        }
12999        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13000            return true;
13001        }
13002        return false;
13003    }
13004
13005    /**
13006     * Used during creation of InstallArgs
13007     *
13008     * @param installFlags package installation flags
13009     * @return true if should be installed as forward locked
13010     */
13011    private static boolean installForwardLocked(int installFlags) {
13012        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13013    }
13014
13015    private InstallArgs createInstallArgs(InstallParams params) {
13016        if (params.move != null) {
13017            return new MoveInstallArgs(params);
13018        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13019            return new AsecInstallArgs(params);
13020        } else {
13021            return new FileInstallArgs(params);
13022        }
13023    }
13024
13025    /**
13026     * Create args that describe an existing installed package. Typically used
13027     * when cleaning up old installs, or used as a move source.
13028     */
13029    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13030            String resourcePath, String[] instructionSets) {
13031        final boolean isInAsec;
13032        if (installOnExternalAsec(installFlags)) {
13033            /* Apps on SD card are always in ASEC containers. */
13034            isInAsec = true;
13035        } else if (installForwardLocked(installFlags)
13036                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13037            /*
13038             * Forward-locked apps are only in ASEC containers if they're the
13039             * new style
13040             */
13041            isInAsec = true;
13042        } else {
13043            isInAsec = false;
13044        }
13045
13046        if (isInAsec) {
13047            return new AsecInstallArgs(codePath, instructionSets,
13048                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13049        } else {
13050            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13051        }
13052    }
13053
13054    static abstract class InstallArgs {
13055        /** @see InstallParams#origin */
13056        final OriginInfo origin;
13057        /** @see InstallParams#move */
13058        final MoveInfo move;
13059
13060        final IPackageInstallObserver2 observer;
13061        // Always refers to PackageManager flags only
13062        final int installFlags;
13063        final String installerPackageName;
13064        final String volumeUuid;
13065        final UserHandle user;
13066        final String abiOverride;
13067        final String[] installGrantPermissions;
13068        /** If non-null, drop an async trace when the install completes */
13069        final String traceMethod;
13070        final int traceCookie;
13071        final Certificate[][] certificates;
13072
13073        // The list of instruction sets supported by this app. This is currently
13074        // only used during the rmdex() phase to clean up resources. We can get rid of this
13075        // if we move dex files under the common app path.
13076        /* nullable */ String[] instructionSets;
13077
13078        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13079                int installFlags, String installerPackageName, String volumeUuid,
13080                UserHandle user, String[] instructionSets,
13081                String abiOverride, String[] installGrantPermissions,
13082                String traceMethod, int traceCookie, Certificate[][] certificates) {
13083            this.origin = origin;
13084            this.move = move;
13085            this.installFlags = installFlags;
13086            this.observer = observer;
13087            this.installerPackageName = installerPackageName;
13088            this.volumeUuid = volumeUuid;
13089            this.user = user;
13090            this.instructionSets = instructionSets;
13091            this.abiOverride = abiOverride;
13092            this.installGrantPermissions = installGrantPermissions;
13093            this.traceMethod = traceMethod;
13094            this.traceCookie = traceCookie;
13095            this.certificates = certificates;
13096        }
13097
13098        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13099        abstract int doPreInstall(int status);
13100
13101        /**
13102         * Rename package into final resting place. All paths on the given
13103         * scanned package should be updated to reflect the rename.
13104         */
13105        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13106        abstract int doPostInstall(int status, int uid);
13107
13108        /** @see PackageSettingBase#codePathString */
13109        abstract String getCodePath();
13110        /** @see PackageSettingBase#resourcePathString */
13111        abstract String getResourcePath();
13112
13113        // Need installer lock especially for dex file removal.
13114        abstract void cleanUpResourcesLI();
13115        abstract boolean doPostDeleteLI(boolean delete);
13116
13117        /**
13118         * Called before the source arguments are copied. This is used mostly
13119         * for MoveParams when it needs to read the source file to put it in the
13120         * destination.
13121         */
13122        int doPreCopy() {
13123            return PackageManager.INSTALL_SUCCEEDED;
13124        }
13125
13126        /**
13127         * Called after the source arguments are copied. This is used mostly for
13128         * MoveParams when it needs to read the source file to put it in the
13129         * destination.
13130         */
13131        int doPostCopy(int uid) {
13132            return PackageManager.INSTALL_SUCCEEDED;
13133        }
13134
13135        protected boolean isFwdLocked() {
13136            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13137        }
13138
13139        protected boolean isExternalAsec() {
13140            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13141        }
13142
13143        protected boolean isEphemeral() {
13144            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13145        }
13146
13147        UserHandle getUser() {
13148            return user;
13149        }
13150    }
13151
13152    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13153        if (!allCodePaths.isEmpty()) {
13154            if (instructionSets == null) {
13155                throw new IllegalStateException("instructionSet == null");
13156            }
13157            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13158            for (String codePath : allCodePaths) {
13159                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13160                    try {
13161                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13162                    } catch (InstallerException ignored) {
13163                    }
13164                }
13165            }
13166        }
13167    }
13168
13169    /**
13170     * Logic to handle installation of non-ASEC applications, including copying
13171     * and renaming logic.
13172     */
13173    class FileInstallArgs extends InstallArgs {
13174        private File codeFile;
13175        private File resourceFile;
13176
13177        // Example topology:
13178        // /data/app/com.example/base.apk
13179        // /data/app/com.example/split_foo.apk
13180        // /data/app/com.example/lib/arm/libfoo.so
13181        // /data/app/com.example/lib/arm64/libfoo.so
13182        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13183
13184        /** New install */
13185        FileInstallArgs(InstallParams params) {
13186            super(params.origin, params.move, params.observer, params.installFlags,
13187                    params.installerPackageName, params.volumeUuid,
13188                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13189                    params.grantedRuntimePermissions,
13190                    params.traceMethod, params.traceCookie, params.certificates);
13191            if (isFwdLocked()) {
13192                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13193            }
13194        }
13195
13196        /** Existing install */
13197        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13198            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13199                    null, null, null, 0, null /*certificates*/);
13200            this.codeFile = (codePath != null) ? new File(codePath) : null;
13201            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13202        }
13203
13204        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13205            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13206            try {
13207                return doCopyApk(imcs, temp);
13208            } finally {
13209                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13210            }
13211        }
13212
13213        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13214            if (origin.staged) {
13215                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13216                codeFile = origin.file;
13217                resourceFile = origin.file;
13218                return PackageManager.INSTALL_SUCCEEDED;
13219            }
13220
13221            try {
13222                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13223                final File tempDir =
13224                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13225                codeFile = tempDir;
13226                resourceFile = tempDir;
13227            } catch (IOException e) {
13228                Slog.w(TAG, "Failed to create copy file: " + e);
13229                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13230            }
13231
13232            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13233                @Override
13234                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13235                    if (!FileUtils.isValidExtFilename(name)) {
13236                        throw new IllegalArgumentException("Invalid filename: " + name);
13237                    }
13238                    try {
13239                        final File file = new File(codeFile, name);
13240                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13241                                O_RDWR | O_CREAT, 0644);
13242                        Os.chmod(file.getAbsolutePath(), 0644);
13243                        return new ParcelFileDescriptor(fd);
13244                    } catch (ErrnoException e) {
13245                        throw new RemoteException("Failed to open: " + e.getMessage());
13246                    }
13247                }
13248            };
13249
13250            int ret = PackageManager.INSTALL_SUCCEEDED;
13251            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13252            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13253                Slog.e(TAG, "Failed to copy package");
13254                return ret;
13255            }
13256
13257            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13258            NativeLibraryHelper.Handle handle = null;
13259            try {
13260                handle = NativeLibraryHelper.Handle.create(codeFile);
13261                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13262                        abiOverride);
13263            } catch (IOException e) {
13264                Slog.e(TAG, "Copying native libraries failed", e);
13265                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13266            } finally {
13267                IoUtils.closeQuietly(handle);
13268            }
13269
13270            return ret;
13271        }
13272
13273        int doPreInstall(int status) {
13274            if (status != PackageManager.INSTALL_SUCCEEDED) {
13275                cleanUp();
13276            }
13277            return status;
13278        }
13279
13280        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13281            if (status != PackageManager.INSTALL_SUCCEEDED) {
13282                cleanUp();
13283                return false;
13284            }
13285
13286            final File targetDir = codeFile.getParentFile();
13287            final File beforeCodeFile = codeFile;
13288            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13289
13290            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13291            try {
13292                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13293            } catch (ErrnoException e) {
13294                Slog.w(TAG, "Failed to rename", e);
13295                return false;
13296            }
13297
13298            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13299                Slog.w(TAG, "Failed to restorecon");
13300                return false;
13301            }
13302
13303            // Reflect the rename internally
13304            codeFile = afterCodeFile;
13305            resourceFile = afterCodeFile;
13306
13307            // Reflect the rename in scanned details
13308            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13309            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13310                    afterCodeFile, pkg.baseCodePath));
13311            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13312                    afterCodeFile, pkg.splitCodePaths));
13313
13314            // Reflect the rename in app info
13315            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13316            pkg.setApplicationInfoCodePath(pkg.codePath);
13317            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13318            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13319            pkg.setApplicationInfoResourcePath(pkg.codePath);
13320            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13321            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13322
13323            return true;
13324        }
13325
13326        int doPostInstall(int status, int uid) {
13327            if (status != PackageManager.INSTALL_SUCCEEDED) {
13328                cleanUp();
13329            }
13330            return status;
13331        }
13332
13333        @Override
13334        String getCodePath() {
13335            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13336        }
13337
13338        @Override
13339        String getResourcePath() {
13340            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13341        }
13342
13343        private boolean cleanUp() {
13344            if (codeFile == null || !codeFile.exists()) {
13345                return false;
13346            }
13347
13348            removeCodePathLI(codeFile);
13349
13350            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13351                resourceFile.delete();
13352            }
13353
13354            return true;
13355        }
13356
13357        void cleanUpResourcesLI() {
13358            // Try enumerating all code paths before deleting
13359            List<String> allCodePaths = Collections.EMPTY_LIST;
13360            if (codeFile != null && codeFile.exists()) {
13361                try {
13362                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13363                    allCodePaths = pkg.getAllCodePaths();
13364                } catch (PackageParserException e) {
13365                    // Ignored; we tried our best
13366                }
13367            }
13368
13369            cleanUp();
13370            removeDexFiles(allCodePaths, instructionSets);
13371        }
13372
13373        boolean doPostDeleteLI(boolean delete) {
13374            // XXX err, shouldn't we respect the delete flag?
13375            cleanUpResourcesLI();
13376            return true;
13377        }
13378    }
13379
13380    private boolean isAsecExternal(String cid) {
13381        final String asecPath = PackageHelper.getSdFilesystem(cid);
13382        return !asecPath.startsWith(mAsecInternalPath);
13383    }
13384
13385    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13386            PackageManagerException {
13387        if (copyRet < 0) {
13388            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13389                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13390                throw new PackageManagerException(copyRet, message);
13391            }
13392        }
13393    }
13394
13395    /**
13396     * Extract the MountService "container ID" from the full code path of an
13397     * .apk.
13398     */
13399    static String cidFromCodePath(String fullCodePath) {
13400        int eidx = fullCodePath.lastIndexOf("/");
13401        String subStr1 = fullCodePath.substring(0, eidx);
13402        int sidx = subStr1.lastIndexOf("/");
13403        return subStr1.substring(sidx+1, eidx);
13404    }
13405
13406    /**
13407     * Logic to handle installation of ASEC applications, including copying and
13408     * renaming logic.
13409     */
13410    class AsecInstallArgs extends InstallArgs {
13411        static final String RES_FILE_NAME = "pkg.apk";
13412        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13413
13414        String cid;
13415        String packagePath;
13416        String resourcePath;
13417
13418        /** New install */
13419        AsecInstallArgs(InstallParams params) {
13420            super(params.origin, params.move, params.observer, params.installFlags,
13421                    params.installerPackageName, params.volumeUuid,
13422                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13423                    params.grantedRuntimePermissions,
13424                    params.traceMethod, params.traceCookie, params.certificates);
13425        }
13426
13427        /** Existing install */
13428        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13429                        boolean isExternal, boolean isForwardLocked) {
13430            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13431              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13432                    instructionSets, null, null, null, 0, null /*certificates*/);
13433            // Hackily pretend we're still looking at a full code path
13434            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13435                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13436            }
13437
13438            // Extract cid from fullCodePath
13439            int eidx = fullCodePath.lastIndexOf("/");
13440            String subStr1 = fullCodePath.substring(0, eidx);
13441            int sidx = subStr1.lastIndexOf("/");
13442            cid = subStr1.substring(sidx+1, eidx);
13443            setMountPath(subStr1);
13444        }
13445
13446        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13447            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13448              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13449                    instructionSets, null, null, null, 0, null /*certificates*/);
13450            this.cid = cid;
13451            setMountPath(PackageHelper.getSdDir(cid));
13452        }
13453
13454        void createCopyFile() {
13455            cid = mInstallerService.allocateExternalStageCidLegacy();
13456        }
13457
13458        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13459            if (origin.staged && origin.cid != null) {
13460                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13461                cid = origin.cid;
13462                setMountPath(PackageHelper.getSdDir(cid));
13463                return PackageManager.INSTALL_SUCCEEDED;
13464            }
13465
13466            if (temp) {
13467                createCopyFile();
13468            } else {
13469                /*
13470                 * Pre-emptively destroy the container since it's destroyed if
13471                 * copying fails due to it existing anyway.
13472                 */
13473                PackageHelper.destroySdDir(cid);
13474            }
13475
13476            final String newMountPath = imcs.copyPackageToContainer(
13477                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13478                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13479
13480            if (newMountPath != null) {
13481                setMountPath(newMountPath);
13482                return PackageManager.INSTALL_SUCCEEDED;
13483            } else {
13484                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13485            }
13486        }
13487
13488        @Override
13489        String getCodePath() {
13490            return packagePath;
13491        }
13492
13493        @Override
13494        String getResourcePath() {
13495            return resourcePath;
13496        }
13497
13498        int doPreInstall(int status) {
13499            if (status != PackageManager.INSTALL_SUCCEEDED) {
13500                // Destroy container
13501                PackageHelper.destroySdDir(cid);
13502            } else {
13503                boolean mounted = PackageHelper.isContainerMounted(cid);
13504                if (!mounted) {
13505                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13506                            Process.SYSTEM_UID);
13507                    if (newMountPath != null) {
13508                        setMountPath(newMountPath);
13509                    } else {
13510                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13511                    }
13512                }
13513            }
13514            return status;
13515        }
13516
13517        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13518            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13519            String newMountPath = null;
13520            if (PackageHelper.isContainerMounted(cid)) {
13521                // Unmount the container
13522                if (!PackageHelper.unMountSdDir(cid)) {
13523                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13524                    return false;
13525                }
13526            }
13527            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13528                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13529                        " which might be stale. Will try to clean up.");
13530                // Clean up the stale container and proceed to recreate.
13531                if (!PackageHelper.destroySdDir(newCacheId)) {
13532                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13533                    return false;
13534                }
13535                // Successfully cleaned up stale container. Try to rename again.
13536                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13537                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13538                            + " inspite of cleaning it up.");
13539                    return false;
13540                }
13541            }
13542            if (!PackageHelper.isContainerMounted(newCacheId)) {
13543                Slog.w(TAG, "Mounting container " + newCacheId);
13544                newMountPath = PackageHelper.mountSdDir(newCacheId,
13545                        getEncryptKey(), Process.SYSTEM_UID);
13546            } else {
13547                newMountPath = PackageHelper.getSdDir(newCacheId);
13548            }
13549            if (newMountPath == null) {
13550                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13551                return false;
13552            }
13553            Log.i(TAG, "Succesfully renamed " + cid +
13554                    " to " + newCacheId +
13555                    " at new path: " + newMountPath);
13556            cid = newCacheId;
13557
13558            final File beforeCodeFile = new File(packagePath);
13559            setMountPath(newMountPath);
13560            final File afterCodeFile = new File(packagePath);
13561
13562            // Reflect the rename in scanned details
13563            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13564            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13565                    afterCodeFile, pkg.baseCodePath));
13566            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13567                    afterCodeFile, pkg.splitCodePaths));
13568
13569            // Reflect the rename in app info
13570            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13571            pkg.setApplicationInfoCodePath(pkg.codePath);
13572            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13573            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13574            pkg.setApplicationInfoResourcePath(pkg.codePath);
13575            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13576            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13577
13578            return true;
13579        }
13580
13581        private void setMountPath(String mountPath) {
13582            final File mountFile = new File(mountPath);
13583
13584            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13585            if (monolithicFile.exists()) {
13586                packagePath = monolithicFile.getAbsolutePath();
13587                if (isFwdLocked()) {
13588                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13589                } else {
13590                    resourcePath = packagePath;
13591                }
13592            } else {
13593                packagePath = mountFile.getAbsolutePath();
13594                resourcePath = packagePath;
13595            }
13596        }
13597
13598        int doPostInstall(int status, int uid) {
13599            if (status != PackageManager.INSTALL_SUCCEEDED) {
13600                cleanUp();
13601            } else {
13602                final int groupOwner;
13603                final String protectedFile;
13604                if (isFwdLocked()) {
13605                    groupOwner = UserHandle.getSharedAppGid(uid);
13606                    protectedFile = RES_FILE_NAME;
13607                } else {
13608                    groupOwner = -1;
13609                    protectedFile = null;
13610                }
13611
13612                if (uid < Process.FIRST_APPLICATION_UID
13613                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13614                    Slog.e(TAG, "Failed to finalize " + cid);
13615                    PackageHelper.destroySdDir(cid);
13616                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13617                }
13618
13619                boolean mounted = PackageHelper.isContainerMounted(cid);
13620                if (!mounted) {
13621                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13622                }
13623            }
13624            return status;
13625        }
13626
13627        private void cleanUp() {
13628            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13629
13630            // Destroy secure container
13631            PackageHelper.destroySdDir(cid);
13632        }
13633
13634        private List<String> getAllCodePaths() {
13635            final File codeFile = new File(getCodePath());
13636            if (codeFile != null && codeFile.exists()) {
13637                try {
13638                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13639                    return pkg.getAllCodePaths();
13640                } catch (PackageParserException e) {
13641                    // Ignored; we tried our best
13642                }
13643            }
13644            return Collections.EMPTY_LIST;
13645        }
13646
13647        void cleanUpResourcesLI() {
13648            // Enumerate all code paths before deleting
13649            cleanUpResourcesLI(getAllCodePaths());
13650        }
13651
13652        private void cleanUpResourcesLI(List<String> allCodePaths) {
13653            cleanUp();
13654            removeDexFiles(allCodePaths, instructionSets);
13655        }
13656
13657        String getPackageName() {
13658            return getAsecPackageName(cid);
13659        }
13660
13661        boolean doPostDeleteLI(boolean delete) {
13662            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13663            final List<String> allCodePaths = getAllCodePaths();
13664            boolean mounted = PackageHelper.isContainerMounted(cid);
13665            if (mounted) {
13666                // Unmount first
13667                if (PackageHelper.unMountSdDir(cid)) {
13668                    mounted = false;
13669                }
13670            }
13671            if (!mounted && delete) {
13672                cleanUpResourcesLI(allCodePaths);
13673            }
13674            return !mounted;
13675        }
13676
13677        @Override
13678        int doPreCopy() {
13679            if (isFwdLocked()) {
13680                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13681                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13682                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13683                }
13684            }
13685
13686            return PackageManager.INSTALL_SUCCEEDED;
13687        }
13688
13689        @Override
13690        int doPostCopy(int uid) {
13691            if (isFwdLocked()) {
13692                if (uid < Process.FIRST_APPLICATION_UID
13693                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13694                                RES_FILE_NAME)) {
13695                    Slog.e(TAG, "Failed to finalize " + cid);
13696                    PackageHelper.destroySdDir(cid);
13697                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13698                }
13699            }
13700
13701            return PackageManager.INSTALL_SUCCEEDED;
13702        }
13703    }
13704
13705    /**
13706     * Logic to handle movement of existing installed applications.
13707     */
13708    class MoveInstallArgs extends InstallArgs {
13709        private File codeFile;
13710        private File resourceFile;
13711
13712        /** New install */
13713        MoveInstallArgs(InstallParams params) {
13714            super(params.origin, params.move, params.observer, params.installFlags,
13715                    params.installerPackageName, params.volumeUuid,
13716                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13717                    params.grantedRuntimePermissions,
13718                    params.traceMethod, params.traceCookie, params.certificates);
13719        }
13720
13721        int copyApk(IMediaContainerService imcs, boolean temp) {
13722            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13723                    + move.fromUuid + " to " + move.toUuid);
13724            synchronized (mInstaller) {
13725                try {
13726                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13727                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13728                } catch (InstallerException e) {
13729                    Slog.w(TAG, "Failed to move app", e);
13730                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13731                }
13732            }
13733
13734            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13735            resourceFile = codeFile;
13736            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13737
13738            return PackageManager.INSTALL_SUCCEEDED;
13739        }
13740
13741        int doPreInstall(int status) {
13742            if (status != PackageManager.INSTALL_SUCCEEDED) {
13743                cleanUp(move.toUuid);
13744            }
13745            return status;
13746        }
13747
13748        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13749            if (status != PackageManager.INSTALL_SUCCEEDED) {
13750                cleanUp(move.toUuid);
13751                return false;
13752            }
13753
13754            // Reflect the move in app info
13755            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13756            pkg.setApplicationInfoCodePath(pkg.codePath);
13757            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13758            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13759            pkg.setApplicationInfoResourcePath(pkg.codePath);
13760            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13761            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13762
13763            return true;
13764        }
13765
13766        int doPostInstall(int status, int uid) {
13767            if (status == PackageManager.INSTALL_SUCCEEDED) {
13768                cleanUp(move.fromUuid);
13769            } else {
13770                cleanUp(move.toUuid);
13771            }
13772            return status;
13773        }
13774
13775        @Override
13776        String getCodePath() {
13777            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13778        }
13779
13780        @Override
13781        String getResourcePath() {
13782            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13783        }
13784
13785        private boolean cleanUp(String volumeUuid) {
13786            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13787                    move.dataAppName);
13788            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13789            final int[] userIds = sUserManager.getUserIds();
13790            synchronized (mInstallLock) {
13791                // Clean up both app data and code
13792                // All package moves are frozen until finished
13793                for (int userId : userIds) {
13794                    try {
13795                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13796                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13797                    } catch (InstallerException e) {
13798                        Slog.w(TAG, String.valueOf(e));
13799                    }
13800                }
13801                removeCodePathLI(codeFile);
13802            }
13803            return true;
13804        }
13805
13806        void cleanUpResourcesLI() {
13807            throw new UnsupportedOperationException();
13808        }
13809
13810        boolean doPostDeleteLI(boolean delete) {
13811            throw new UnsupportedOperationException();
13812        }
13813    }
13814
13815    static String getAsecPackageName(String packageCid) {
13816        int idx = packageCid.lastIndexOf("-");
13817        if (idx == -1) {
13818            return packageCid;
13819        }
13820        return packageCid.substring(0, idx);
13821    }
13822
13823    // Utility method used to create code paths based on package name and available index.
13824    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13825        String idxStr = "";
13826        int idx = 1;
13827        // Fall back to default value of idx=1 if prefix is not
13828        // part of oldCodePath
13829        if (oldCodePath != null) {
13830            String subStr = oldCodePath;
13831            // Drop the suffix right away
13832            if (suffix != null && subStr.endsWith(suffix)) {
13833                subStr = subStr.substring(0, subStr.length() - suffix.length());
13834            }
13835            // If oldCodePath already contains prefix find out the
13836            // ending index to either increment or decrement.
13837            int sidx = subStr.lastIndexOf(prefix);
13838            if (sidx != -1) {
13839                subStr = subStr.substring(sidx + prefix.length());
13840                if (subStr != null) {
13841                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13842                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13843                    }
13844                    try {
13845                        idx = Integer.parseInt(subStr);
13846                        if (idx <= 1) {
13847                            idx++;
13848                        } else {
13849                            idx--;
13850                        }
13851                    } catch(NumberFormatException e) {
13852                    }
13853                }
13854            }
13855        }
13856        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13857        return prefix + idxStr;
13858    }
13859
13860    private File getNextCodePath(File targetDir, String packageName) {
13861        int suffix = 1;
13862        File result;
13863        do {
13864            result = new File(targetDir, packageName + "-" + suffix);
13865            suffix++;
13866        } while (result.exists());
13867        return result;
13868    }
13869
13870    // Utility method that returns the relative package path with respect
13871    // to the installation directory. Like say for /data/data/com.test-1.apk
13872    // string com.test-1 is returned.
13873    static String deriveCodePathName(String codePath) {
13874        if (codePath == null) {
13875            return null;
13876        }
13877        final File codeFile = new File(codePath);
13878        final String name = codeFile.getName();
13879        if (codeFile.isDirectory()) {
13880            return name;
13881        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13882            final int lastDot = name.lastIndexOf('.');
13883            return name.substring(0, lastDot);
13884        } else {
13885            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13886            return null;
13887        }
13888    }
13889
13890    static class PackageInstalledInfo {
13891        String name;
13892        int uid;
13893        // The set of users that originally had this package installed.
13894        int[] origUsers;
13895        // The set of users that now have this package installed.
13896        int[] newUsers;
13897        PackageParser.Package pkg;
13898        int returnCode;
13899        String returnMsg;
13900        PackageRemovedInfo removedInfo;
13901        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13902
13903        public void setError(int code, String msg) {
13904            setReturnCode(code);
13905            setReturnMessage(msg);
13906            Slog.w(TAG, msg);
13907        }
13908
13909        public void setError(String msg, PackageParserException e) {
13910            setReturnCode(e.error);
13911            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13912            Slog.w(TAG, msg, e);
13913        }
13914
13915        public void setError(String msg, PackageManagerException e) {
13916            returnCode = e.error;
13917            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13918            Slog.w(TAG, msg, e);
13919        }
13920
13921        public void setReturnCode(int returnCode) {
13922            this.returnCode = returnCode;
13923            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13924            for (int i = 0; i < childCount; i++) {
13925                addedChildPackages.valueAt(i).returnCode = returnCode;
13926            }
13927        }
13928
13929        private void setReturnMessage(String returnMsg) {
13930            this.returnMsg = returnMsg;
13931            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13932            for (int i = 0; i < childCount; i++) {
13933                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13934            }
13935        }
13936
13937        // In some error cases we want to convey more info back to the observer
13938        String origPackage;
13939        String origPermission;
13940    }
13941
13942    /*
13943     * Install a non-existing package.
13944     */
13945    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13946            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13947            PackageInstalledInfo res) {
13948        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13949
13950        // Remember this for later, in case we need to rollback this install
13951        String pkgName = pkg.packageName;
13952
13953        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13954
13955        synchronized(mPackages) {
13956            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13957                // A package with the same name is already installed, though
13958                // it has been renamed to an older name.  The package we
13959                // are trying to install should be installed as an update to
13960                // the existing one, but that has not been requested, so bail.
13961                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13962                        + " without first uninstalling package running as "
13963                        + mSettings.mRenamedPackages.get(pkgName));
13964                return;
13965            }
13966            if (mPackages.containsKey(pkgName)) {
13967                // Don't allow installation over an existing package with the same name.
13968                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13969                        + " without first uninstalling.");
13970                return;
13971            }
13972        }
13973
13974        try {
13975            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13976                    System.currentTimeMillis(), user);
13977
13978            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13979
13980            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13981                prepareAppDataAfterInstallLIF(newPackage);
13982
13983            } else {
13984                // Remove package from internal structures, but keep around any
13985                // data that might have already existed
13986                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13987                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13988            }
13989        } catch (PackageManagerException e) {
13990            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13991        }
13992
13993        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13994    }
13995
13996    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13997        // Can't rotate keys during boot or if sharedUser.
13998        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13999                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14000            return false;
14001        }
14002        // app is using upgradeKeySets; make sure all are valid
14003        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14004        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14005        for (int i = 0; i < upgradeKeySets.length; i++) {
14006            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14007                Slog.wtf(TAG, "Package "
14008                         + (oldPs.name != null ? oldPs.name : "<null>")
14009                         + " contains upgrade-key-set reference to unknown key-set: "
14010                         + upgradeKeySets[i]
14011                         + " reverting to signatures check.");
14012                return false;
14013            }
14014        }
14015        return true;
14016    }
14017
14018    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14019        // Upgrade keysets are being used.  Determine if new package has a superset of the
14020        // required keys.
14021        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14022        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14023        for (int i = 0; i < upgradeKeySets.length; i++) {
14024            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14025            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14026                return true;
14027            }
14028        }
14029        return false;
14030    }
14031
14032    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14033        try (DigestInputStream digestStream =
14034                new DigestInputStream(new FileInputStream(file), digest)) {
14035            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14036        }
14037    }
14038
14039    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14040            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14041        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14042
14043        final PackageParser.Package oldPackage;
14044        final String pkgName = pkg.packageName;
14045        final int[] allUsers;
14046        final int[] installedUsers;
14047
14048        synchronized(mPackages) {
14049            oldPackage = mPackages.get(pkgName);
14050            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14051
14052            // don't allow upgrade to target a release SDK from a pre-release SDK
14053            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14054                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14055            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14056                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14057            if (oldTargetsPreRelease
14058                    && !newTargetsPreRelease
14059                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14060                Slog.w(TAG, "Can't install package targeting released sdk");
14061                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14062                return;
14063            }
14064
14065            // don't allow an upgrade from full to ephemeral
14066            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14067            if (isEphemeral && !oldIsEphemeral) {
14068                // can't downgrade from full to ephemeral
14069                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14070                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14071                return;
14072            }
14073
14074            // verify signatures are valid
14075            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14076            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14077                if (!checkUpgradeKeySetLP(ps, pkg)) {
14078                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14079                            "New package not signed by keys specified by upgrade-keysets: "
14080                                    + pkgName);
14081                    return;
14082                }
14083            } else {
14084                // default to original signature matching
14085                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14086                        != PackageManager.SIGNATURE_MATCH) {
14087                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14088                            "New package has a different signature: " + pkgName);
14089                    return;
14090                }
14091            }
14092
14093            // don't allow a system upgrade unless the upgrade hash matches
14094            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14095                byte[] digestBytes = null;
14096                try {
14097                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14098                    updateDigest(digest, new File(pkg.baseCodePath));
14099                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14100                        for (String path : pkg.splitCodePaths) {
14101                            updateDigest(digest, new File(path));
14102                        }
14103                    }
14104                    digestBytes = digest.digest();
14105                } catch (NoSuchAlgorithmException | IOException e) {
14106                    res.setError(INSTALL_FAILED_INVALID_APK,
14107                            "Could not compute hash: " + pkgName);
14108                    return;
14109                }
14110                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14111                    res.setError(INSTALL_FAILED_INVALID_APK,
14112                            "New package fails restrict-update check: " + pkgName);
14113                    return;
14114                }
14115                // retain upgrade restriction
14116                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14117            }
14118
14119            // Check for shared user id changes
14120            String invalidPackageName =
14121                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14122            if (invalidPackageName != null) {
14123                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14124                        "Package " + invalidPackageName + " tried to change user "
14125                                + oldPackage.mSharedUserId);
14126                return;
14127            }
14128
14129            // In case of rollback, remember per-user/profile install state
14130            allUsers = sUserManager.getUserIds();
14131            installedUsers = ps.queryInstalledUsers(allUsers, true);
14132        }
14133
14134        // Update what is removed
14135        res.removedInfo = new PackageRemovedInfo();
14136        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14137        res.removedInfo.removedPackage = oldPackage.packageName;
14138        res.removedInfo.isUpdate = true;
14139        res.removedInfo.origUsers = installedUsers;
14140        final int childCount = (oldPackage.childPackages != null)
14141                ? oldPackage.childPackages.size() : 0;
14142        for (int i = 0; i < childCount; i++) {
14143            boolean childPackageUpdated = false;
14144            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14145            if (res.addedChildPackages != null) {
14146                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14147                if (childRes != null) {
14148                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14149                    childRes.removedInfo.removedPackage = childPkg.packageName;
14150                    childRes.removedInfo.isUpdate = true;
14151                    childPackageUpdated = true;
14152                }
14153            }
14154            if (!childPackageUpdated) {
14155                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14156                childRemovedRes.removedPackage = childPkg.packageName;
14157                childRemovedRes.isUpdate = false;
14158                childRemovedRes.dataRemoved = true;
14159                synchronized (mPackages) {
14160                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14161                    if (childPs != null) {
14162                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14163                    }
14164                }
14165                if (res.removedInfo.removedChildPackages == null) {
14166                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14167                }
14168                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14169            }
14170        }
14171
14172        boolean sysPkg = (isSystemApp(oldPackage));
14173        if (sysPkg) {
14174            // Set the system/privileged flags as needed
14175            final boolean privileged =
14176                    (oldPackage.applicationInfo.privateFlags
14177                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14178            final int systemPolicyFlags = policyFlags
14179                    | PackageParser.PARSE_IS_SYSTEM
14180                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14181
14182            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14183                    user, allUsers, installerPackageName, res);
14184        } else {
14185            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14186                    user, allUsers, installerPackageName, res);
14187        }
14188    }
14189
14190    public List<String> getPreviousCodePaths(String packageName) {
14191        final PackageSetting ps = mSettings.mPackages.get(packageName);
14192        final List<String> result = new ArrayList<String>();
14193        if (ps != null && ps.oldCodePaths != null) {
14194            result.addAll(ps.oldCodePaths);
14195        }
14196        return result;
14197    }
14198
14199    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14200            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14201            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14202        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14203                + deletedPackage);
14204
14205        String pkgName = deletedPackage.packageName;
14206        boolean deletedPkg = true;
14207        boolean addedPkg = false;
14208        boolean updatedSettings = false;
14209        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14210        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14211                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14212
14213        final long origUpdateTime = (pkg.mExtras != null)
14214                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14215
14216        // First delete the existing package while retaining the data directory
14217        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14218                res.removedInfo, true, pkg)) {
14219            // If the existing package wasn't successfully deleted
14220            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14221            deletedPkg = false;
14222        } else {
14223            // Successfully deleted the old package; proceed with replace.
14224
14225            // If deleted package lived in a container, give users a chance to
14226            // relinquish resources before killing.
14227            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14228                if (DEBUG_INSTALL) {
14229                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14230                }
14231                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14232                final ArrayList<String> pkgList = new ArrayList<String>(1);
14233                pkgList.add(deletedPackage.applicationInfo.packageName);
14234                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14235            }
14236
14237            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14238                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14239            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14240
14241            try {
14242                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14243                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14244                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14245
14246                // Update the in-memory copy of the previous code paths.
14247                PackageSetting ps = mSettings.mPackages.get(pkgName);
14248                if (!killApp) {
14249                    if (ps.oldCodePaths == null) {
14250                        ps.oldCodePaths = new ArraySet<>();
14251                    }
14252                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14253                    if (deletedPackage.splitCodePaths != null) {
14254                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14255                    }
14256                } else {
14257                    ps.oldCodePaths = null;
14258                }
14259                if (ps.childPackageNames != null) {
14260                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14261                        final String childPkgName = ps.childPackageNames.get(i);
14262                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14263                        childPs.oldCodePaths = ps.oldCodePaths;
14264                    }
14265                }
14266                prepareAppDataAfterInstallLIF(newPackage);
14267                addedPkg = true;
14268            } catch (PackageManagerException e) {
14269                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14270            }
14271        }
14272
14273        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14274            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14275
14276            // Revert all internal state mutations and added folders for the failed install
14277            if (addedPkg) {
14278                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14279                        res.removedInfo, true, null);
14280            }
14281
14282            // Restore the old package
14283            if (deletedPkg) {
14284                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14285                File restoreFile = new File(deletedPackage.codePath);
14286                // Parse old package
14287                boolean oldExternal = isExternal(deletedPackage);
14288                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14289                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14290                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14291                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14292                try {
14293                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14294                            null);
14295                } catch (PackageManagerException e) {
14296                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14297                            + e.getMessage());
14298                    return;
14299                }
14300
14301                synchronized (mPackages) {
14302                    // Ensure the installer package name up to date
14303                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14304
14305                    // Update permissions for restored package
14306                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14307
14308                    mSettings.writeLPr();
14309                }
14310
14311                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14312            }
14313        } else {
14314            synchronized (mPackages) {
14315                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14316                if (ps != null) {
14317                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14318                    if (res.removedInfo.removedChildPackages != null) {
14319                        final int childCount = res.removedInfo.removedChildPackages.size();
14320                        // Iterate in reverse as we may modify the collection
14321                        for (int i = childCount - 1; i >= 0; i--) {
14322                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14323                            if (res.addedChildPackages.containsKey(childPackageName)) {
14324                                res.removedInfo.removedChildPackages.removeAt(i);
14325                            } else {
14326                                PackageRemovedInfo childInfo = res.removedInfo
14327                                        .removedChildPackages.valueAt(i);
14328                                childInfo.removedForAllUsers = mPackages.get(
14329                                        childInfo.removedPackage) == null;
14330                            }
14331                        }
14332                    }
14333                }
14334            }
14335        }
14336    }
14337
14338    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14339            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14340            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14341        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14342                + ", old=" + deletedPackage);
14343
14344        final boolean disabledSystem;
14345
14346        // Remove existing system package
14347        removePackageLI(deletedPackage, true);
14348
14349        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14350        if (!disabledSystem) {
14351            // We didn't need to disable the .apk as a current system package,
14352            // which means we are replacing another update that is already
14353            // installed.  We need to make sure to delete the older one's .apk.
14354            res.removedInfo.args = createInstallArgsForExisting(0,
14355                    deletedPackage.applicationInfo.getCodePath(),
14356                    deletedPackage.applicationInfo.getResourcePath(),
14357                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14358        } else {
14359            res.removedInfo.args = null;
14360        }
14361
14362        // Successfully disabled the old package. Now proceed with re-installation
14363        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14364                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14365        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14366
14367        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14368        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14369                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14370
14371        PackageParser.Package newPackage = null;
14372        try {
14373            // Add the package to the internal data structures
14374            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14375
14376            // Set the update and install times
14377            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14378            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14379                    System.currentTimeMillis());
14380
14381            // Update the package dynamic state if succeeded
14382            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14383                // Now that the install succeeded make sure we remove data
14384                // directories for any child package the update removed.
14385                final int deletedChildCount = (deletedPackage.childPackages != null)
14386                        ? deletedPackage.childPackages.size() : 0;
14387                final int newChildCount = (newPackage.childPackages != null)
14388                        ? newPackage.childPackages.size() : 0;
14389                for (int i = 0; i < deletedChildCount; i++) {
14390                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14391                    boolean childPackageDeleted = true;
14392                    for (int j = 0; j < newChildCount; j++) {
14393                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14394                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14395                            childPackageDeleted = false;
14396                            break;
14397                        }
14398                    }
14399                    if (childPackageDeleted) {
14400                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14401                                deletedChildPkg.packageName);
14402                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14403                            PackageRemovedInfo removedChildRes = res.removedInfo
14404                                    .removedChildPackages.get(deletedChildPkg.packageName);
14405                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14406                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14407                        }
14408                    }
14409                }
14410
14411                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14412                prepareAppDataAfterInstallLIF(newPackage);
14413            }
14414        } catch (PackageManagerException e) {
14415            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14416            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14417        }
14418
14419        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14420            // Re installation failed. Restore old information
14421            // Remove new pkg information
14422            if (newPackage != null) {
14423                removeInstalledPackageLI(newPackage, true);
14424            }
14425            // Add back the old system package
14426            try {
14427                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14428            } catch (PackageManagerException e) {
14429                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14430            }
14431
14432            synchronized (mPackages) {
14433                if (disabledSystem) {
14434                    enableSystemPackageLPw(deletedPackage);
14435                }
14436
14437                // Ensure the installer package name up to date
14438                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14439
14440                // Update permissions for restored package
14441                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14442
14443                mSettings.writeLPr();
14444            }
14445
14446            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14447                    + " after failed upgrade");
14448        }
14449    }
14450
14451    /**
14452     * Checks whether the parent or any of the child packages have a change shared
14453     * user. For a package to be a valid update the shred users of the parent and
14454     * the children should match. We may later support changing child shared users.
14455     * @param oldPkg The updated package.
14456     * @param newPkg The update package.
14457     * @return The shared user that change between the versions.
14458     */
14459    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14460            PackageParser.Package newPkg) {
14461        // Check parent shared user
14462        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14463            return newPkg.packageName;
14464        }
14465        // Check child shared users
14466        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14467        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14468        for (int i = 0; i < newChildCount; i++) {
14469            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14470            // If this child was present, did it have the same shared user?
14471            for (int j = 0; j < oldChildCount; j++) {
14472                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14473                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14474                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14475                    return newChildPkg.packageName;
14476                }
14477            }
14478        }
14479        return null;
14480    }
14481
14482    private void removeNativeBinariesLI(PackageSetting ps) {
14483        // Remove the lib path for the parent package
14484        if (ps != null) {
14485            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14486            // Remove the lib path for the child packages
14487            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14488            for (int i = 0; i < childCount; i++) {
14489                PackageSetting childPs = null;
14490                synchronized (mPackages) {
14491                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14492                }
14493                if (childPs != null) {
14494                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14495                            .legacyNativeLibraryPathString);
14496                }
14497            }
14498        }
14499    }
14500
14501    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14502        // Enable the parent package
14503        mSettings.enableSystemPackageLPw(pkg.packageName);
14504        // Enable the child packages
14505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14506        for (int i = 0; i < childCount; i++) {
14507            PackageParser.Package childPkg = pkg.childPackages.get(i);
14508            mSettings.enableSystemPackageLPw(childPkg.packageName);
14509        }
14510    }
14511
14512    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14513            PackageParser.Package newPkg) {
14514        // Disable the parent package (parent always replaced)
14515        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14516        // Disable the child packages
14517        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14518        for (int i = 0; i < childCount; i++) {
14519            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14520            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14521            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14522        }
14523        return disabled;
14524    }
14525
14526    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14527            String installerPackageName) {
14528        // Enable the parent package
14529        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14530        // Enable the child packages
14531        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14532        for (int i = 0; i < childCount; i++) {
14533            PackageParser.Package childPkg = pkg.childPackages.get(i);
14534            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14535        }
14536    }
14537
14538    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14539        // Collect all used permissions in the UID
14540        ArraySet<String> usedPermissions = new ArraySet<>();
14541        final int packageCount = su.packages.size();
14542        for (int i = 0; i < packageCount; i++) {
14543            PackageSetting ps = su.packages.valueAt(i);
14544            if (ps.pkg == null) {
14545                continue;
14546            }
14547            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14548            for (int j = 0; j < requestedPermCount; j++) {
14549                String permission = ps.pkg.requestedPermissions.get(j);
14550                BasePermission bp = mSettings.mPermissions.get(permission);
14551                if (bp != null) {
14552                    usedPermissions.add(permission);
14553                }
14554            }
14555        }
14556
14557        PermissionsState permissionsState = su.getPermissionsState();
14558        // Prune install permissions
14559        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14560        final int installPermCount = installPermStates.size();
14561        for (int i = installPermCount - 1; i >= 0;  i--) {
14562            PermissionState permissionState = installPermStates.get(i);
14563            if (!usedPermissions.contains(permissionState.getName())) {
14564                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14565                if (bp != null) {
14566                    permissionsState.revokeInstallPermission(bp);
14567                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14568                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14569                }
14570            }
14571        }
14572
14573        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14574
14575        // Prune runtime permissions
14576        for (int userId : allUserIds) {
14577            List<PermissionState> runtimePermStates = permissionsState
14578                    .getRuntimePermissionStates(userId);
14579            final int runtimePermCount = runtimePermStates.size();
14580            for (int i = runtimePermCount - 1; i >= 0; i--) {
14581                PermissionState permissionState = runtimePermStates.get(i);
14582                if (!usedPermissions.contains(permissionState.getName())) {
14583                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14584                    if (bp != null) {
14585                        permissionsState.revokeRuntimePermission(bp, userId);
14586                        permissionsState.updatePermissionFlags(bp, userId,
14587                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14588                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14589                                runtimePermissionChangedUserIds, userId);
14590                    }
14591                }
14592            }
14593        }
14594
14595        return runtimePermissionChangedUserIds;
14596    }
14597
14598    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14599            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14600        // Update the parent package setting
14601        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14602                res, user);
14603        // Update the child packages setting
14604        final int childCount = (newPackage.childPackages != null)
14605                ? newPackage.childPackages.size() : 0;
14606        for (int i = 0; i < childCount; i++) {
14607            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14608            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14609            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14610                    childRes.origUsers, childRes, user);
14611        }
14612    }
14613
14614    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14615            String installerPackageName, int[] allUsers, int[] installedForUsers,
14616            PackageInstalledInfo res, UserHandle user) {
14617        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14618
14619        String pkgName = newPackage.packageName;
14620        synchronized (mPackages) {
14621            //write settings. the installStatus will be incomplete at this stage.
14622            //note that the new package setting would have already been
14623            //added to mPackages. It hasn't been persisted yet.
14624            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14625            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14626            mSettings.writeLPr();
14627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14628        }
14629
14630        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14631        synchronized (mPackages) {
14632            updatePermissionsLPw(newPackage.packageName, newPackage,
14633                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14634                            ? UPDATE_PERMISSIONS_ALL : 0));
14635            // For system-bundled packages, we assume that installing an upgraded version
14636            // of the package implies that the user actually wants to run that new code,
14637            // so we enable the package.
14638            PackageSetting ps = mSettings.mPackages.get(pkgName);
14639            final int userId = user.getIdentifier();
14640            if (ps != null) {
14641                if (isSystemApp(newPackage)) {
14642                    if (DEBUG_INSTALL) {
14643                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14644                    }
14645                    // Enable system package for requested users
14646                    if (res.origUsers != null) {
14647                        for (int origUserId : res.origUsers) {
14648                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14649                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14650                                        origUserId, installerPackageName);
14651                            }
14652                        }
14653                    }
14654                    // Also convey the prior install/uninstall state
14655                    if (allUsers != null && installedForUsers != null) {
14656                        for (int currentUserId : allUsers) {
14657                            final boolean installed = ArrayUtils.contains(
14658                                    installedForUsers, currentUserId);
14659                            if (DEBUG_INSTALL) {
14660                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14661                            }
14662                            ps.setInstalled(installed, currentUserId);
14663                        }
14664                        // these install state changes will be persisted in the
14665                        // upcoming call to mSettings.writeLPr().
14666                    }
14667                }
14668                // It's implied that when a user requests installation, they want the app to be
14669                // installed and enabled.
14670                if (userId != UserHandle.USER_ALL) {
14671                    ps.setInstalled(true, userId);
14672                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14673                }
14674            }
14675            res.name = pkgName;
14676            res.uid = newPackage.applicationInfo.uid;
14677            res.pkg = newPackage;
14678            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14679            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14680            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14681            //to update install status
14682            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14683            mSettings.writeLPr();
14684            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14685        }
14686
14687        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14688    }
14689
14690    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14691        try {
14692            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14693            installPackageLI(args, res);
14694        } finally {
14695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14696        }
14697    }
14698
14699    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14700        final int installFlags = args.installFlags;
14701        final String installerPackageName = args.installerPackageName;
14702        final String volumeUuid = args.volumeUuid;
14703        final File tmpPackageFile = new File(args.getCodePath());
14704        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14705        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14706                || (args.volumeUuid != null));
14707        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14708        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14709        boolean replace = false;
14710        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14711        if (args.move != null) {
14712            // moving a complete application; perform an initial scan on the new install location
14713            scanFlags |= SCAN_INITIAL;
14714        }
14715        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14716            scanFlags |= SCAN_DONT_KILL_APP;
14717        }
14718
14719        // Result object to be returned
14720        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14721
14722        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14723
14724        // Sanity check
14725        if (ephemeral && (forwardLocked || onExternal)) {
14726            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14727                    + " external=" + onExternal);
14728            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14729            return;
14730        }
14731
14732        // Retrieve PackageSettings and parse package
14733        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14734                | PackageParser.PARSE_ENFORCE_CODE
14735                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14736                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14737                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14738                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14739        PackageParser pp = new PackageParser();
14740        pp.setSeparateProcesses(mSeparateProcesses);
14741        pp.setDisplayMetrics(mMetrics);
14742
14743        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14744        final PackageParser.Package pkg;
14745        try {
14746            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14747        } catch (PackageParserException e) {
14748            res.setError("Failed parse during installPackageLI", e);
14749            return;
14750        } finally {
14751            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14752        }
14753
14754        // If we are installing a clustered package add results for the children
14755        if (pkg.childPackages != null) {
14756            synchronized (mPackages) {
14757                final int childCount = pkg.childPackages.size();
14758                for (int i = 0; i < childCount; i++) {
14759                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14760                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14761                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14762                    childRes.pkg = childPkg;
14763                    childRes.name = childPkg.packageName;
14764                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14765                    if (childPs != null) {
14766                        childRes.origUsers = childPs.queryInstalledUsers(
14767                                sUserManager.getUserIds(), true);
14768                    }
14769                    if ((mPackages.containsKey(childPkg.packageName))) {
14770                        childRes.removedInfo = new PackageRemovedInfo();
14771                        childRes.removedInfo.removedPackage = childPkg.packageName;
14772                    }
14773                    if (res.addedChildPackages == null) {
14774                        res.addedChildPackages = new ArrayMap<>();
14775                    }
14776                    res.addedChildPackages.put(childPkg.packageName, childRes);
14777                }
14778            }
14779        }
14780
14781        // If package doesn't declare API override, mark that we have an install
14782        // time CPU ABI override.
14783        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14784            pkg.cpuAbiOverride = args.abiOverride;
14785        }
14786
14787        String pkgName = res.name = pkg.packageName;
14788        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14789            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14790                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14791                return;
14792            }
14793        }
14794
14795        try {
14796            // either use what we've been given or parse directly from the APK
14797            if (args.certificates != null) {
14798                try {
14799                    PackageParser.populateCertificates(pkg, args.certificates);
14800                } catch (PackageParserException e) {
14801                    // there was something wrong with the certificates we were given;
14802                    // try to pull them from the APK
14803                    PackageParser.collectCertificates(pkg, parseFlags);
14804                }
14805            } else {
14806                PackageParser.collectCertificates(pkg, parseFlags);
14807            }
14808        } catch (PackageParserException e) {
14809            res.setError("Failed collect during installPackageLI", e);
14810            return;
14811        }
14812
14813        // Get rid of all references to package scan path via parser.
14814        pp = null;
14815        String oldCodePath = null;
14816        boolean systemApp = false;
14817        synchronized (mPackages) {
14818            // Check if installing already existing package
14819            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14820                String oldName = mSettings.mRenamedPackages.get(pkgName);
14821                if (pkg.mOriginalPackages != null
14822                        && pkg.mOriginalPackages.contains(oldName)
14823                        && mPackages.containsKey(oldName)) {
14824                    // This package is derived from an original package,
14825                    // and this device has been updating from that original
14826                    // name.  We must continue using the original name, so
14827                    // rename the new package here.
14828                    pkg.setPackageName(oldName);
14829                    pkgName = pkg.packageName;
14830                    replace = true;
14831                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14832                            + oldName + " pkgName=" + pkgName);
14833                } else if (mPackages.containsKey(pkgName)) {
14834                    // This package, under its official name, already exists
14835                    // on the device; we should replace it.
14836                    replace = true;
14837                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14838                }
14839
14840                // Child packages are installed through the parent package
14841                if (pkg.parentPackage != null) {
14842                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14843                            "Package " + pkg.packageName + " is child of package "
14844                                    + pkg.parentPackage.parentPackage + ". Child packages "
14845                                    + "can be updated only through the parent package.");
14846                    return;
14847                }
14848
14849                if (replace) {
14850                    // Prevent apps opting out from runtime permissions
14851                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14852                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14853                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14854                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14855                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14856                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14857                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14858                                        + " doesn't support runtime permissions but the old"
14859                                        + " target SDK " + oldTargetSdk + " does.");
14860                        return;
14861                    }
14862
14863                    // Prevent installing of child packages
14864                    if (oldPackage.parentPackage != null) {
14865                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14866                                "Package " + pkg.packageName + " is child of package "
14867                                        + oldPackage.parentPackage + ". Child packages "
14868                                        + "can be updated only through the parent package.");
14869                        return;
14870                    }
14871                }
14872            }
14873
14874            PackageSetting ps = mSettings.mPackages.get(pkgName);
14875            if (ps != null) {
14876                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14877
14878                // Quick sanity check that we're signed correctly if updating;
14879                // we'll check this again later when scanning, but we want to
14880                // bail early here before tripping over redefined permissions.
14881                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14882                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14883                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14884                                + pkg.packageName + " upgrade keys do not match the "
14885                                + "previously installed version");
14886                        return;
14887                    }
14888                } else {
14889                    try {
14890                        verifySignaturesLP(ps, pkg);
14891                    } catch (PackageManagerException e) {
14892                        res.setError(e.error, e.getMessage());
14893                        return;
14894                    }
14895                }
14896
14897                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14898                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14899                    systemApp = (ps.pkg.applicationInfo.flags &
14900                            ApplicationInfo.FLAG_SYSTEM) != 0;
14901                }
14902                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14903            }
14904
14905            // Check whether the newly-scanned package wants to define an already-defined perm
14906            int N = pkg.permissions.size();
14907            for (int i = N-1; i >= 0; i--) {
14908                PackageParser.Permission perm = pkg.permissions.get(i);
14909                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14910                if (bp != null) {
14911                    // If the defining package is signed with our cert, it's okay.  This
14912                    // also includes the "updating the same package" case, of course.
14913                    // "updating same package" could also involve key-rotation.
14914                    final boolean sigsOk;
14915                    if (bp.sourcePackage.equals(pkg.packageName)
14916                            && (bp.packageSetting instanceof PackageSetting)
14917                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14918                                    scanFlags))) {
14919                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14920                    } else {
14921                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14922                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14923                    }
14924                    if (!sigsOk) {
14925                        // If the owning package is the system itself, we log but allow
14926                        // install to proceed; we fail the install on all other permission
14927                        // redefinitions.
14928                        if (!bp.sourcePackage.equals("android")) {
14929                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14930                                    + pkg.packageName + " attempting to redeclare permission "
14931                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14932                            res.origPermission = perm.info.name;
14933                            res.origPackage = bp.sourcePackage;
14934                            return;
14935                        } else {
14936                            Slog.w(TAG, "Package " + pkg.packageName
14937                                    + " attempting to redeclare system permission "
14938                                    + perm.info.name + "; ignoring new declaration");
14939                            pkg.permissions.remove(i);
14940                        }
14941                    }
14942                }
14943            }
14944        }
14945
14946        if (systemApp) {
14947            if (onExternal) {
14948                // Abort update; system app can't be replaced with app on sdcard
14949                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14950                        "Cannot install updates to system apps on sdcard");
14951                return;
14952            } else if (ephemeral) {
14953                // Abort update; system app can't be replaced with an ephemeral app
14954                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14955                        "Cannot update a system app with an ephemeral app");
14956                return;
14957            }
14958        }
14959
14960        if (args.move != null) {
14961            // We did an in-place move, so dex is ready to roll
14962            scanFlags |= SCAN_NO_DEX;
14963            scanFlags |= SCAN_MOVE;
14964
14965            synchronized (mPackages) {
14966                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14967                if (ps == null) {
14968                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14969                            "Missing settings for moved package " + pkgName);
14970                }
14971
14972                // We moved the entire application as-is, so bring over the
14973                // previously derived ABI information.
14974                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14975                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14976            }
14977
14978        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14979            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14980            scanFlags |= SCAN_NO_DEX;
14981
14982            try {
14983                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14984                    args.abiOverride : pkg.cpuAbiOverride);
14985                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14986                        true /* extract libs */);
14987            } catch (PackageManagerException pme) {
14988                Slog.e(TAG, "Error deriving application ABI", pme);
14989                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14990                return;
14991            }
14992
14993            // Shared libraries for the package need to be updated.
14994            synchronized (mPackages) {
14995                try {
14996                    updateSharedLibrariesLPw(pkg, null);
14997                } catch (PackageManagerException e) {
14998                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14999                }
15000            }
15001            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15002            // Do not run PackageDexOptimizer through the local performDexOpt
15003            // method because `pkg` is not in `mPackages` yet.
15004            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15005                    null /* instructionSets */, false /* checkProfiles */,
15006                    getCompilerFilterForReason(REASON_INSTALL));
15007            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15008            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
15009                String msg = "Extracting package failed for " + pkgName;
15010                res.setError(INSTALL_FAILED_DEXOPT, msg);
15011                return;
15012            }
15013
15014            // Notify BackgroundDexOptService that the package has been changed.
15015            // If this is an update of a package which used to fail to compile,
15016            // BDOS will remove it from its blacklist.
15017            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15018        }
15019
15020        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15021            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15022            return;
15023        }
15024
15025        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15026
15027        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15028                "installPackageLI")) {
15029            if (replace) {
15030                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15031                        installerPackageName, res);
15032            } else {
15033                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15034                        args.user, installerPackageName, volumeUuid, res);
15035            }
15036        }
15037        synchronized (mPackages) {
15038            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15039            if (ps != null) {
15040                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15041            }
15042
15043            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15044            for (int i = 0; i < childCount; i++) {
15045                PackageParser.Package childPkg = pkg.childPackages.get(i);
15046                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15047                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15048                if (childPs != null) {
15049                    childRes.newUsers = childPs.queryInstalledUsers(
15050                            sUserManager.getUserIds(), true);
15051                }
15052            }
15053        }
15054    }
15055
15056    private void startIntentFilterVerifications(int userId, boolean replacing,
15057            PackageParser.Package pkg) {
15058        if (mIntentFilterVerifierComponent == null) {
15059            Slog.w(TAG, "No IntentFilter verification will not be done as "
15060                    + "there is no IntentFilterVerifier available!");
15061            return;
15062        }
15063
15064        final int verifierUid = getPackageUid(
15065                mIntentFilterVerifierComponent.getPackageName(),
15066                MATCH_DEBUG_TRIAGED_MISSING,
15067                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15068
15069        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15070        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15071        mHandler.sendMessage(msg);
15072
15073        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15074        for (int i = 0; i < childCount; i++) {
15075            PackageParser.Package childPkg = pkg.childPackages.get(i);
15076            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15077            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15078            mHandler.sendMessage(msg);
15079        }
15080    }
15081
15082    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15083            PackageParser.Package pkg) {
15084        int size = pkg.activities.size();
15085        if (size == 0) {
15086            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15087                    "No activity, so no need to verify any IntentFilter!");
15088            return;
15089        }
15090
15091        final boolean hasDomainURLs = hasDomainURLs(pkg);
15092        if (!hasDomainURLs) {
15093            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15094                    "No domain URLs, so no need to verify any IntentFilter!");
15095            return;
15096        }
15097
15098        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15099                + " if any IntentFilter from the " + size
15100                + " Activities needs verification ...");
15101
15102        int count = 0;
15103        final String packageName = pkg.packageName;
15104
15105        synchronized (mPackages) {
15106            // If this is a new install and we see that we've already run verification for this
15107            // package, we have nothing to do: it means the state was restored from backup.
15108            if (!replacing) {
15109                IntentFilterVerificationInfo ivi =
15110                        mSettings.getIntentFilterVerificationLPr(packageName);
15111                if (ivi != null) {
15112                    if (DEBUG_DOMAIN_VERIFICATION) {
15113                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15114                                + ivi.getStatusString());
15115                    }
15116                    return;
15117                }
15118            }
15119
15120            // If any filters need to be verified, then all need to be.
15121            boolean needToVerify = false;
15122            for (PackageParser.Activity a : pkg.activities) {
15123                for (ActivityIntentInfo filter : a.intents) {
15124                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15125                        if (DEBUG_DOMAIN_VERIFICATION) {
15126                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15127                        }
15128                        needToVerify = true;
15129                        break;
15130                    }
15131                }
15132            }
15133
15134            if (needToVerify) {
15135                final int verificationId = mIntentFilterVerificationToken++;
15136                for (PackageParser.Activity a : pkg.activities) {
15137                    for (ActivityIntentInfo filter : a.intents) {
15138                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15139                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15140                                    "Verification needed for IntentFilter:" + filter.toString());
15141                            mIntentFilterVerifier.addOneIntentFilterVerification(
15142                                    verifierUid, userId, verificationId, filter, packageName);
15143                            count++;
15144                        }
15145                    }
15146                }
15147            }
15148        }
15149
15150        if (count > 0) {
15151            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15152                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15153                    +  " for userId:" + userId);
15154            mIntentFilterVerifier.startVerifications(userId);
15155        } else {
15156            if (DEBUG_DOMAIN_VERIFICATION) {
15157                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15158            }
15159        }
15160    }
15161
15162    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15163        final ComponentName cn  = filter.activity.getComponentName();
15164        final String packageName = cn.getPackageName();
15165
15166        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15167                packageName);
15168        if (ivi == null) {
15169            return true;
15170        }
15171        int status = ivi.getStatus();
15172        switch (status) {
15173            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15174            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15175                return true;
15176
15177            default:
15178                // Nothing to do
15179                return false;
15180        }
15181    }
15182
15183    private static boolean isMultiArch(ApplicationInfo info) {
15184        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15185    }
15186
15187    private static boolean isExternal(PackageParser.Package pkg) {
15188        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15189    }
15190
15191    private static boolean isExternal(PackageSetting ps) {
15192        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15193    }
15194
15195    private static boolean isEphemeral(PackageParser.Package pkg) {
15196        return pkg.applicationInfo.isEphemeralApp();
15197    }
15198
15199    private static boolean isEphemeral(PackageSetting ps) {
15200        return ps.pkg != null && isEphemeral(ps.pkg);
15201    }
15202
15203    private static boolean isSystemApp(PackageParser.Package pkg) {
15204        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15205    }
15206
15207    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15208        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15209    }
15210
15211    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15212        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15213    }
15214
15215    private static boolean isSystemApp(PackageSetting ps) {
15216        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15217    }
15218
15219    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15220        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15221    }
15222
15223    private int packageFlagsToInstallFlags(PackageSetting ps) {
15224        int installFlags = 0;
15225        if (isEphemeral(ps)) {
15226            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15227        }
15228        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15229            // This existing package was an external ASEC install when we have
15230            // the external flag without a UUID
15231            installFlags |= PackageManager.INSTALL_EXTERNAL;
15232        }
15233        if (ps.isForwardLocked()) {
15234            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15235        }
15236        return installFlags;
15237    }
15238
15239    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15240        if (isExternal(pkg)) {
15241            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15242                return StorageManager.UUID_PRIMARY_PHYSICAL;
15243            } else {
15244                return pkg.volumeUuid;
15245            }
15246        } else {
15247            return StorageManager.UUID_PRIVATE_INTERNAL;
15248        }
15249    }
15250
15251    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15252        if (isExternal(pkg)) {
15253            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15254                return mSettings.getExternalVersion();
15255            } else {
15256                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15257            }
15258        } else {
15259            return mSettings.getInternalVersion();
15260        }
15261    }
15262
15263    private void deleteTempPackageFiles() {
15264        final FilenameFilter filter = new FilenameFilter() {
15265            public boolean accept(File dir, String name) {
15266                return name.startsWith("vmdl") && name.endsWith(".tmp");
15267            }
15268        };
15269        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15270            file.delete();
15271        }
15272    }
15273
15274    @Override
15275    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15276            int flags) {
15277        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15278                flags);
15279    }
15280
15281    @Override
15282    public void deletePackage(final String packageName,
15283            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15284        mContext.enforceCallingOrSelfPermission(
15285                android.Manifest.permission.DELETE_PACKAGES, null);
15286        Preconditions.checkNotNull(packageName);
15287        Preconditions.checkNotNull(observer);
15288        final int uid = Binder.getCallingUid();
15289        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15290        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15291        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15292            mContext.enforceCallingOrSelfPermission(
15293                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15294                    "deletePackage for user " + userId);
15295        }
15296
15297        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15298            try {
15299                observer.onPackageDeleted(packageName,
15300                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15301            } catch (RemoteException re) {
15302            }
15303            return;
15304        }
15305
15306        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15307            try {
15308                observer.onPackageDeleted(packageName,
15309                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15310            } catch (RemoteException re) {
15311            }
15312            return;
15313        }
15314
15315        if (DEBUG_REMOVE) {
15316            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15317                    + " deleteAllUsers: " + deleteAllUsers );
15318        }
15319        // Queue up an async operation since the package deletion may take a little while.
15320        mHandler.post(new Runnable() {
15321            public void run() {
15322                mHandler.removeCallbacks(this);
15323                int returnCode;
15324                if (!deleteAllUsers) {
15325                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15326                } else {
15327                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15328                    // If nobody is blocking uninstall, proceed with delete for all users
15329                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15330                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15331                    } else {
15332                        // Otherwise uninstall individually for users with blockUninstalls=false
15333                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15334                        for (int userId : users) {
15335                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15336                                returnCode = deletePackageX(packageName, userId, userFlags);
15337                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15338                                    Slog.w(TAG, "Package delete failed for user " + userId
15339                                            + ", returnCode " + returnCode);
15340                                }
15341                            }
15342                        }
15343                        // The app has only been marked uninstalled for certain users.
15344                        // We still need to report that delete was blocked
15345                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15346                    }
15347                }
15348                try {
15349                    observer.onPackageDeleted(packageName, returnCode, null);
15350                } catch (RemoteException e) {
15351                    Log.i(TAG, "Observer no longer exists.");
15352                } //end catch
15353            } //end run
15354        });
15355    }
15356
15357    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15358        int[] result = EMPTY_INT_ARRAY;
15359        for (int userId : userIds) {
15360            if (getBlockUninstallForUser(packageName, userId)) {
15361                result = ArrayUtils.appendInt(result, userId);
15362            }
15363        }
15364        return result;
15365    }
15366
15367    @Override
15368    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15369        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15370    }
15371
15372    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15373        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15374                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15375        try {
15376            if (dpm != null) {
15377                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15378                        /* callingUserOnly =*/ false);
15379                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15380                        : deviceOwnerComponentName.getPackageName();
15381                // Does the package contains the device owner?
15382                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15383                // this check is probably not needed, since DO should be registered as a device
15384                // admin on some user too. (Original bug for this: b/17657954)
15385                if (packageName.equals(deviceOwnerPackageName)) {
15386                    return true;
15387                }
15388                // Does it contain a device admin for any user?
15389                int[] users;
15390                if (userId == UserHandle.USER_ALL) {
15391                    users = sUserManager.getUserIds();
15392                } else {
15393                    users = new int[]{userId};
15394                }
15395                for (int i = 0; i < users.length; ++i) {
15396                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15397                        return true;
15398                    }
15399                }
15400            }
15401        } catch (RemoteException e) {
15402        }
15403        return false;
15404    }
15405
15406    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15407        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15408    }
15409
15410    /**
15411     *  This method is an internal method that could be get invoked either
15412     *  to delete an installed package or to clean up a failed installation.
15413     *  After deleting an installed package, a broadcast is sent to notify any
15414     *  listeners that the package has been removed. For cleaning up a failed
15415     *  installation, the broadcast is not necessary since the package's
15416     *  installation wouldn't have sent the initial broadcast either
15417     *  The key steps in deleting a package are
15418     *  deleting the package information in internal structures like mPackages,
15419     *  deleting the packages base directories through installd
15420     *  updating mSettings to reflect current status
15421     *  persisting settings for later use
15422     *  sending a broadcast if necessary
15423     */
15424    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15425        final PackageRemovedInfo info = new PackageRemovedInfo();
15426        final boolean res;
15427
15428        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15429                ? UserHandle.ALL : new UserHandle(userId);
15430
15431        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15432            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15433            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15434        }
15435
15436        PackageSetting uninstalledPs = null;
15437
15438        // for the uninstall-updates case and restricted profiles, remember the per-
15439        // user handle installed state
15440        int[] allUsers;
15441        synchronized (mPackages) {
15442            uninstalledPs = mSettings.mPackages.get(packageName);
15443            if (uninstalledPs == null) {
15444                Slog.w(TAG, "Not removing non-existent package " + packageName);
15445                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15446            }
15447            allUsers = sUserManager.getUserIds();
15448            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15449        }
15450
15451        synchronized (mInstallLock) {
15452            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15453            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15454                    "deletePackageX")) {
15455                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15456                        deleteFlags | REMOVE_CHATTY, info, true, null);
15457            }
15458            synchronized (mPackages) {
15459                if (res) {
15460                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15461                }
15462            }
15463        }
15464
15465        if (res) {
15466            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15467            info.sendPackageRemovedBroadcasts(killApp);
15468            info.sendSystemPackageUpdatedBroadcasts();
15469            info.sendSystemPackageAppearedBroadcasts();
15470        }
15471        // Force a gc here.
15472        Runtime.getRuntime().gc();
15473        // Delete the resources here after sending the broadcast to let
15474        // other processes clean up before deleting resources.
15475        if (info.args != null) {
15476            synchronized (mInstallLock) {
15477                info.args.doPostDeleteLI(true);
15478            }
15479        }
15480
15481        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15482    }
15483
15484    class PackageRemovedInfo {
15485        String removedPackage;
15486        int uid = -1;
15487        int removedAppId = -1;
15488        int[] origUsers;
15489        int[] removedUsers = null;
15490        boolean isRemovedPackageSystemUpdate = false;
15491        boolean isUpdate;
15492        boolean dataRemoved;
15493        boolean removedForAllUsers;
15494        // Clean up resources deleted packages.
15495        InstallArgs args = null;
15496        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15497        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15498
15499        void sendPackageRemovedBroadcasts(boolean killApp) {
15500            sendPackageRemovedBroadcastInternal(killApp);
15501            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15502            for (int i = 0; i < childCount; i++) {
15503                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15504                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15505            }
15506        }
15507
15508        void sendSystemPackageUpdatedBroadcasts() {
15509            if (isRemovedPackageSystemUpdate) {
15510                sendSystemPackageUpdatedBroadcastsInternal();
15511                final int childCount = (removedChildPackages != null)
15512                        ? removedChildPackages.size() : 0;
15513                for (int i = 0; i < childCount; i++) {
15514                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15515                    if (childInfo.isRemovedPackageSystemUpdate) {
15516                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15517                    }
15518                }
15519            }
15520        }
15521
15522        void sendSystemPackageAppearedBroadcasts() {
15523            final int packageCount = (appearedChildPackages != null)
15524                    ? appearedChildPackages.size() : 0;
15525            for (int i = 0; i < packageCount; i++) {
15526                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15527                for (int userId : installedInfo.newUsers) {
15528                    sendPackageAddedForUser(installedInfo.name, true,
15529                            UserHandle.getAppId(installedInfo.uid), userId);
15530                }
15531            }
15532        }
15533
15534        private void sendSystemPackageUpdatedBroadcastsInternal() {
15535            Bundle extras = new Bundle(2);
15536            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15537            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15538            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15539                    extras, 0, null, null, null);
15540            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15541                    extras, 0, null, null, null);
15542            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15543                    null, 0, removedPackage, null, null);
15544        }
15545
15546        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15547            Bundle extras = new Bundle(2);
15548            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15549            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15550            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15551            if (isUpdate || isRemovedPackageSystemUpdate) {
15552                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15553            }
15554            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15555            if (removedPackage != null) {
15556                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15557                        extras, 0, null, null, removedUsers);
15558                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15559                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15560                            removedPackage, extras, 0, null, null, removedUsers);
15561                }
15562            }
15563            if (removedAppId >= 0) {
15564                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15565                        removedUsers);
15566            }
15567        }
15568    }
15569
15570    /*
15571     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15572     * flag is not set, the data directory is removed as well.
15573     * make sure this flag is set for partially installed apps. If not its meaningless to
15574     * delete a partially installed application.
15575     */
15576    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15577            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15578        String packageName = ps.name;
15579        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15580        // Retrieve object to delete permissions for shared user later on
15581        final PackageParser.Package deletedPkg;
15582        final PackageSetting deletedPs;
15583        // reader
15584        synchronized (mPackages) {
15585            deletedPkg = mPackages.get(packageName);
15586            deletedPs = mSettings.mPackages.get(packageName);
15587            if (outInfo != null) {
15588                outInfo.removedPackage = packageName;
15589                outInfo.removedUsers = deletedPs != null
15590                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15591                        : null;
15592            }
15593        }
15594
15595        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15596
15597        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15598            final PackageParser.Package resolvedPkg;
15599            if (deletedPkg != null) {
15600                resolvedPkg = deletedPkg;
15601            } else {
15602                // We don't have a parsed package when it lives on an ejected
15603                // adopted storage device, so fake something together
15604                resolvedPkg = new PackageParser.Package(ps.name);
15605                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15606            }
15607            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15608                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15609            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15610            if (outInfo != null) {
15611                outInfo.dataRemoved = true;
15612            }
15613            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15614        }
15615
15616        // writer
15617        synchronized (mPackages) {
15618            if (deletedPs != null) {
15619                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15620                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15621                    clearDefaultBrowserIfNeeded(packageName);
15622                    if (outInfo != null) {
15623                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15624                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15625                    }
15626                    updatePermissionsLPw(deletedPs.name, null, 0);
15627                    if (deletedPs.sharedUser != null) {
15628                        // Remove permissions associated with package. Since runtime
15629                        // permissions are per user we have to kill the removed package
15630                        // or packages running under the shared user of the removed
15631                        // package if revoking the permissions requested only by the removed
15632                        // package is successful and this causes a change in gids.
15633                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15634                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15635                                    userId);
15636                            if (userIdToKill == UserHandle.USER_ALL
15637                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15638                                // If gids changed for this user, kill all affected packages.
15639                                mHandler.post(new Runnable() {
15640                                    @Override
15641                                    public void run() {
15642                                        // This has to happen with no lock held.
15643                                        killApplication(deletedPs.name, deletedPs.appId,
15644                                                KILL_APP_REASON_GIDS_CHANGED);
15645                                    }
15646                                });
15647                                break;
15648                            }
15649                        }
15650                    }
15651                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15652                }
15653                // make sure to preserve per-user disabled state if this removal was just
15654                // a downgrade of a system app to the factory package
15655                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15656                    if (DEBUG_REMOVE) {
15657                        Slog.d(TAG, "Propagating install state across downgrade");
15658                    }
15659                    for (int userId : allUserHandles) {
15660                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15661                        if (DEBUG_REMOVE) {
15662                            Slog.d(TAG, "    user " + userId + " => " + installed);
15663                        }
15664                        ps.setInstalled(installed, userId);
15665                    }
15666                }
15667            }
15668            // can downgrade to reader
15669            if (writeSettings) {
15670                // Save settings now
15671                mSettings.writeLPr();
15672            }
15673        }
15674        if (outInfo != null) {
15675            // A user ID was deleted here. Go through all users and remove it
15676            // from KeyStore.
15677            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15678        }
15679    }
15680
15681    static boolean locationIsPrivileged(File path) {
15682        try {
15683            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15684                    .getCanonicalPath();
15685            return path.getCanonicalPath().startsWith(privilegedAppDir);
15686        } catch (IOException e) {
15687            Slog.e(TAG, "Unable to access code path " + path);
15688        }
15689        return false;
15690    }
15691
15692    /*
15693     * Tries to delete system package.
15694     */
15695    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15696            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15697            boolean writeSettings) {
15698        if (deletedPs.parentPackageName != null) {
15699            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15700            return false;
15701        }
15702
15703        final boolean applyUserRestrictions
15704                = (allUserHandles != null) && (outInfo.origUsers != null);
15705        final PackageSetting disabledPs;
15706        // Confirm if the system package has been updated
15707        // An updated system app can be deleted. This will also have to restore
15708        // the system pkg from system partition
15709        // reader
15710        synchronized (mPackages) {
15711            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15712        }
15713
15714        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15715                + " disabledPs=" + disabledPs);
15716
15717        if (disabledPs == null) {
15718            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15719            return false;
15720        } else if (DEBUG_REMOVE) {
15721            Slog.d(TAG, "Deleting system pkg from data partition");
15722        }
15723
15724        if (DEBUG_REMOVE) {
15725            if (applyUserRestrictions) {
15726                Slog.d(TAG, "Remembering install states:");
15727                for (int userId : allUserHandles) {
15728                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15729                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15730                }
15731            }
15732        }
15733
15734        // Delete the updated package
15735        outInfo.isRemovedPackageSystemUpdate = true;
15736        if (outInfo.removedChildPackages != null) {
15737            final int childCount = (deletedPs.childPackageNames != null)
15738                    ? deletedPs.childPackageNames.size() : 0;
15739            for (int i = 0; i < childCount; i++) {
15740                String childPackageName = deletedPs.childPackageNames.get(i);
15741                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15742                        .contains(childPackageName)) {
15743                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15744                            childPackageName);
15745                    if (childInfo != null) {
15746                        childInfo.isRemovedPackageSystemUpdate = true;
15747                    }
15748                }
15749            }
15750        }
15751
15752        if (disabledPs.versionCode < deletedPs.versionCode) {
15753            // Delete data for downgrades
15754            flags &= ~PackageManager.DELETE_KEEP_DATA;
15755        } else {
15756            // Preserve data by setting flag
15757            flags |= PackageManager.DELETE_KEEP_DATA;
15758        }
15759
15760        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15761                outInfo, writeSettings, disabledPs.pkg);
15762        if (!ret) {
15763            return false;
15764        }
15765
15766        // writer
15767        synchronized (mPackages) {
15768            // Reinstate the old system package
15769            enableSystemPackageLPw(disabledPs.pkg);
15770            // Remove any native libraries from the upgraded package.
15771            removeNativeBinariesLI(deletedPs);
15772        }
15773
15774        // Install the system package
15775        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15776        int parseFlags = mDefParseFlags
15777                | PackageParser.PARSE_MUST_BE_APK
15778                | PackageParser.PARSE_IS_SYSTEM
15779                | PackageParser.PARSE_IS_SYSTEM_DIR;
15780        if (locationIsPrivileged(disabledPs.codePath)) {
15781            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15782        }
15783
15784        final PackageParser.Package newPkg;
15785        try {
15786            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15787        } catch (PackageManagerException e) {
15788            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15789                    + e.getMessage());
15790            return false;
15791        }
15792
15793        prepareAppDataAfterInstallLIF(newPkg);
15794
15795        // writer
15796        synchronized (mPackages) {
15797            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15798
15799            // Propagate the permissions state as we do not want to drop on the floor
15800            // runtime permissions. The update permissions method below will take
15801            // care of removing obsolete permissions and grant install permissions.
15802            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15803            updatePermissionsLPw(newPkg.packageName, newPkg,
15804                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15805
15806            if (applyUserRestrictions) {
15807                if (DEBUG_REMOVE) {
15808                    Slog.d(TAG, "Propagating install state across reinstall");
15809                }
15810                for (int userId : allUserHandles) {
15811                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15812                    if (DEBUG_REMOVE) {
15813                        Slog.d(TAG, "    user " + userId + " => " + installed);
15814                    }
15815                    ps.setInstalled(installed, userId);
15816
15817                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15818                }
15819                // Regardless of writeSettings we need to ensure that this restriction
15820                // state propagation is persisted
15821                mSettings.writeAllUsersPackageRestrictionsLPr();
15822            }
15823            // can downgrade to reader here
15824            if (writeSettings) {
15825                mSettings.writeLPr();
15826            }
15827        }
15828        return true;
15829    }
15830
15831    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15832            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15833            PackageRemovedInfo outInfo, boolean writeSettings,
15834            PackageParser.Package replacingPackage) {
15835        synchronized (mPackages) {
15836            if (outInfo != null) {
15837                outInfo.uid = ps.appId;
15838            }
15839
15840            if (outInfo != null && outInfo.removedChildPackages != null) {
15841                final int childCount = (ps.childPackageNames != null)
15842                        ? ps.childPackageNames.size() : 0;
15843                for (int i = 0; i < childCount; i++) {
15844                    String childPackageName = ps.childPackageNames.get(i);
15845                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15846                    if (childPs == null) {
15847                        return false;
15848                    }
15849                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15850                            childPackageName);
15851                    if (childInfo != null) {
15852                        childInfo.uid = childPs.appId;
15853                    }
15854                }
15855            }
15856        }
15857
15858        // Delete package data from internal structures and also remove data if flag is set
15859        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15860
15861        // Delete the child packages data
15862        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15863        for (int i = 0; i < childCount; i++) {
15864            PackageSetting childPs;
15865            synchronized (mPackages) {
15866                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15867            }
15868            if (childPs != null) {
15869                PackageRemovedInfo childOutInfo = (outInfo != null
15870                        && outInfo.removedChildPackages != null)
15871                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15872                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15873                        && (replacingPackage != null
15874                        && !replacingPackage.hasChildPackage(childPs.name))
15875                        ? flags & ~DELETE_KEEP_DATA : flags;
15876                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15877                        deleteFlags, writeSettings);
15878            }
15879        }
15880
15881        // Delete application code and resources only for parent packages
15882        if (ps.parentPackageName == null) {
15883            if (deleteCodeAndResources && (outInfo != null)) {
15884                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15885                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15886                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15887            }
15888        }
15889
15890        return true;
15891    }
15892
15893    @Override
15894    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15895            int userId) {
15896        mContext.enforceCallingOrSelfPermission(
15897                android.Manifest.permission.DELETE_PACKAGES, null);
15898        synchronized (mPackages) {
15899            PackageSetting ps = mSettings.mPackages.get(packageName);
15900            if (ps == null) {
15901                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15902                return false;
15903            }
15904            if (!ps.getInstalled(userId)) {
15905                // Can't block uninstall for an app that is not installed or enabled.
15906                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15907                return false;
15908            }
15909            ps.setBlockUninstall(blockUninstall, userId);
15910            mSettings.writePackageRestrictionsLPr(userId);
15911        }
15912        return true;
15913    }
15914
15915    @Override
15916    public boolean getBlockUninstallForUser(String packageName, int userId) {
15917        synchronized (mPackages) {
15918            PackageSetting ps = mSettings.mPackages.get(packageName);
15919            if (ps == null) {
15920                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15921                return false;
15922            }
15923            return ps.getBlockUninstall(userId);
15924        }
15925    }
15926
15927    @Override
15928    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15929        int callingUid = Binder.getCallingUid();
15930        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15931            throw new SecurityException(
15932                    "setRequiredForSystemUser can only be run by the system or root");
15933        }
15934        synchronized (mPackages) {
15935            PackageSetting ps = mSettings.mPackages.get(packageName);
15936            if (ps == null) {
15937                Log.w(TAG, "Package doesn't exist: " + packageName);
15938                return false;
15939            }
15940            if (systemUserApp) {
15941                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15942            } else {
15943                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15944            }
15945            mSettings.writeLPr();
15946        }
15947        return true;
15948    }
15949
15950    /*
15951     * This method handles package deletion in general
15952     */
15953    private boolean deletePackageLIF(String packageName, UserHandle user,
15954            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15955            PackageRemovedInfo outInfo, boolean writeSettings,
15956            PackageParser.Package replacingPackage) {
15957        if (packageName == null) {
15958            Slog.w(TAG, "Attempt to delete null packageName.");
15959            return false;
15960        }
15961
15962        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15963
15964        PackageSetting ps;
15965
15966        synchronized (mPackages) {
15967            ps = mSettings.mPackages.get(packageName);
15968            if (ps == null) {
15969                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15970                return false;
15971            }
15972
15973            if (ps.parentPackageName != null && (!isSystemApp(ps)
15974                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15975                if (DEBUG_REMOVE) {
15976                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15977                            + ((user == null) ? UserHandle.USER_ALL : user));
15978                }
15979                final int removedUserId = (user != null) ? user.getIdentifier()
15980                        : UserHandle.USER_ALL;
15981                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15982                    return false;
15983                }
15984                markPackageUninstalledForUserLPw(ps, user);
15985                scheduleWritePackageRestrictionsLocked(user);
15986                return true;
15987            }
15988        }
15989
15990        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15991                && user.getIdentifier() != UserHandle.USER_ALL)) {
15992            // The caller is asking that the package only be deleted for a single
15993            // user.  To do this, we just mark its uninstalled state and delete
15994            // its data. If this is a system app, we only allow this to happen if
15995            // they have set the special DELETE_SYSTEM_APP which requests different
15996            // semantics than normal for uninstalling system apps.
15997            markPackageUninstalledForUserLPw(ps, user);
15998
15999            if (!isSystemApp(ps)) {
16000                // Do not uninstall the APK if an app should be cached
16001                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16002                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16003                    // Other user still have this package installed, so all
16004                    // we need to do is clear this user's data and save that
16005                    // it is uninstalled.
16006                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16007                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16008                        return false;
16009                    }
16010                    scheduleWritePackageRestrictionsLocked(user);
16011                    return true;
16012                } else {
16013                    // We need to set it back to 'installed' so the uninstall
16014                    // broadcasts will be sent correctly.
16015                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16016                    ps.setInstalled(true, user.getIdentifier());
16017                }
16018            } else {
16019                // This is a system app, so we assume that the
16020                // other users still have this package installed, so all
16021                // we need to do is clear this user's data and save that
16022                // it is uninstalled.
16023                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16024                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16025                    return false;
16026                }
16027                scheduleWritePackageRestrictionsLocked(user);
16028                return true;
16029            }
16030        }
16031
16032        // If we are deleting a composite package for all users, keep track
16033        // of result for each child.
16034        if (ps.childPackageNames != null && outInfo != null) {
16035            synchronized (mPackages) {
16036                final int childCount = ps.childPackageNames.size();
16037                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16038                for (int i = 0; i < childCount; i++) {
16039                    String childPackageName = ps.childPackageNames.get(i);
16040                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16041                    childInfo.removedPackage = childPackageName;
16042                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16043                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16044                    if (childPs != null) {
16045                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16046                    }
16047                }
16048            }
16049        }
16050
16051        boolean ret = false;
16052        if (isSystemApp(ps)) {
16053            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16054            // When an updated system application is deleted we delete the existing resources
16055            // as well and fall back to existing code in system partition
16056            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16057        } else {
16058            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16059            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16060                    outInfo, writeSettings, replacingPackage);
16061        }
16062
16063        // Take a note whether we deleted the package for all users
16064        if (outInfo != null) {
16065            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16066            if (outInfo.removedChildPackages != null) {
16067                synchronized (mPackages) {
16068                    final int childCount = outInfo.removedChildPackages.size();
16069                    for (int i = 0; i < childCount; i++) {
16070                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16071                        if (childInfo != null) {
16072                            childInfo.removedForAllUsers = mPackages.get(
16073                                    childInfo.removedPackage) == null;
16074                        }
16075                    }
16076                }
16077            }
16078            // If we uninstalled an update to a system app there may be some
16079            // child packages that appeared as they are declared in the system
16080            // app but were not declared in the update.
16081            if (isSystemApp(ps)) {
16082                synchronized (mPackages) {
16083                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16084                    final int childCount = (updatedPs.childPackageNames != null)
16085                            ? updatedPs.childPackageNames.size() : 0;
16086                    for (int i = 0; i < childCount; i++) {
16087                        String childPackageName = updatedPs.childPackageNames.get(i);
16088                        if (outInfo.removedChildPackages == null
16089                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16090                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16091                            if (childPs == null) {
16092                                continue;
16093                            }
16094                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16095                            installRes.name = childPackageName;
16096                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16097                            installRes.pkg = mPackages.get(childPackageName);
16098                            installRes.uid = childPs.pkg.applicationInfo.uid;
16099                            if (outInfo.appearedChildPackages == null) {
16100                                outInfo.appearedChildPackages = new ArrayMap<>();
16101                            }
16102                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16103                        }
16104                    }
16105                }
16106            }
16107        }
16108
16109        return ret;
16110    }
16111
16112    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16113        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16114                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16115        for (int nextUserId : userIds) {
16116            if (DEBUG_REMOVE) {
16117                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16118            }
16119            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16120                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16121                    false /*hidden*/, false /*suspended*/, null, null, null,
16122                    false /*blockUninstall*/,
16123                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16124        }
16125    }
16126
16127    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16128            PackageRemovedInfo outInfo) {
16129        final PackageParser.Package pkg;
16130        synchronized (mPackages) {
16131            pkg = mPackages.get(ps.name);
16132        }
16133
16134        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16135                : new int[] {userId};
16136        for (int nextUserId : userIds) {
16137            if (DEBUG_REMOVE) {
16138                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16139                        + nextUserId);
16140            }
16141
16142            destroyAppDataLIF(pkg, userId,
16143                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16144            destroyAppProfilesLIF(pkg, userId);
16145            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16146            schedulePackageCleaning(ps.name, nextUserId, false);
16147            synchronized (mPackages) {
16148                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16149                    scheduleWritePackageRestrictionsLocked(nextUserId);
16150                }
16151                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16152            }
16153        }
16154
16155        if (outInfo != null) {
16156            outInfo.removedPackage = ps.name;
16157            outInfo.removedAppId = ps.appId;
16158            outInfo.removedUsers = userIds;
16159        }
16160
16161        return true;
16162    }
16163
16164    private final class ClearStorageConnection implements ServiceConnection {
16165        IMediaContainerService mContainerService;
16166
16167        @Override
16168        public void onServiceConnected(ComponentName name, IBinder service) {
16169            synchronized (this) {
16170                mContainerService = IMediaContainerService.Stub.asInterface(service);
16171                notifyAll();
16172            }
16173        }
16174
16175        @Override
16176        public void onServiceDisconnected(ComponentName name) {
16177        }
16178    }
16179
16180    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16181        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16182
16183        final boolean mounted;
16184        if (Environment.isExternalStorageEmulated()) {
16185            mounted = true;
16186        } else {
16187            final String status = Environment.getExternalStorageState();
16188
16189            mounted = status.equals(Environment.MEDIA_MOUNTED)
16190                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16191        }
16192
16193        if (!mounted) {
16194            return;
16195        }
16196
16197        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16198        int[] users;
16199        if (userId == UserHandle.USER_ALL) {
16200            users = sUserManager.getUserIds();
16201        } else {
16202            users = new int[] { userId };
16203        }
16204        final ClearStorageConnection conn = new ClearStorageConnection();
16205        if (mContext.bindServiceAsUser(
16206                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16207            try {
16208                for (int curUser : users) {
16209                    long timeout = SystemClock.uptimeMillis() + 5000;
16210                    synchronized (conn) {
16211                        long now = SystemClock.uptimeMillis();
16212                        while (conn.mContainerService == null && now < timeout) {
16213                            try {
16214                                conn.wait(timeout - now);
16215                            } catch (InterruptedException e) {
16216                            }
16217                        }
16218                    }
16219                    if (conn.mContainerService == null) {
16220                        return;
16221                    }
16222
16223                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16224                    clearDirectory(conn.mContainerService,
16225                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16226                    if (allData) {
16227                        clearDirectory(conn.mContainerService,
16228                                userEnv.buildExternalStorageAppDataDirs(packageName));
16229                        clearDirectory(conn.mContainerService,
16230                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16231                    }
16232                }
16233            } finally {
16234                mContext.unbindService(conn);
16235            }
16236        }
16237    }
16238
16239    @Override
16240    public void clearApplicationProfileData(String packageName) {
16241        enforceSystemOrRoot("Only the system can clear all profile data");
16242
16243        final PackageParser.Package pkg;
16244        synchronized (mPackages) {
16245            pkg = mPackages.get(packageName);
16246        }
16247
16248        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16249            synchronized (mInstallLock) {
16250                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16251            }
16252        }
16253    }
16254
16255    @Override
16256    public void clearApplicationUserData(final String packageName,
16257            final IPackageDataObserver observer, final int userId) {
16258        mContext.enforceCallingOrSelfPermission(
16259                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16260
16261        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16262                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16263
16264        final DevicePolicyManagerInternal dpmi = LocalServices
16265                .getService(DevicePolicyManagerInternal.class);
16266        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16267            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16268        }
16269        // Queue up an async operation since the package deletion may take a little while.
16270        mHandler.post(new Runnable() {
16271            public void run() {
16272                mHandler.removeCallbacks(this);
16273                final boolean succeeded;
16274                try (PackageFreezer freezer = freezePackage(packageName,
16275                        "clearApplicationUserData")) {
16276                    synchronized (mInstallLock) {
16277                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16278                    }
16279                    clearExternalStorageDataSync(packageName, userId, true);
16280                }
16281                if (succeeded) {
16282                    // invoke DeviceStorageMonitor's update method to clear any notifications
16283                    DeviceStorageMonitorInternal dsm = LocalServices
16284                            .getService(DeviceStorageMonitorInternal.class);
16285                    if (dsm != null) {
16286                        dsm.checkMemory();
16287                    }
16288                }
16289                if(observer != null) {
16290                    try {
16291                        observer.onRemoveCompleted(packageName, succeeded);
16292                    } catch (RemoteException e) {
16293                        Log.i(TAG, "Observer no longer exists.");
16294                    }
16295                } //end if observer
16296            } //end run
16297        });
16298    }
16299
16300    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16301        if (packageName == null) {
16302            Slog.w(TAG, "Attempt to delete null packageName.");
16303            return false;
16304        }
16305
16306        // Try finding details about the requested package
16307        PackageParser.Package pkg;
16308        synchronized (mPackages) {
16309            pkg = mPackages.get(packageName);
16310            if (pkg == null) {
16311                final PackageSetting ps = mSettings.mPackages.get(packageName);
16312                if (ps != null) {
16313                    pkg = ps.pkg;
16314                }
16315            }
16316
16317            if (pkg == null) {
16318                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16319                return false;
16320            }
16321
16322            PackageSetting ps = (PackageSetting) pkg.mExtras;
16323            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16324        }
16325
16326        clearAppDataLIF(pkg, userId,
16327                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16328
16329        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16330        removeKeystoreDataIfNeeded(userId, appId);
16331
16332        UserManagerInternal umInternal = getUserManagerInternal();
16333        final int flags;
16334        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16335            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16336        } else if (umInternal.isUserRunning(userId)) {
16337            flags = StorageManager.FLAG_STORAGE_DE;
16338        } else {
16339            flags = 0;
16340        }
16341        prepareAppDataContentsLIF(pkg, userId, flags);
16342
16343        return true;
16344    }
16345
16346    /**
16347     * Reverts user permission state changes (permissions and flags) in
16348     * all packages for a given user.
16349     *
16350     * @param userId The device user for which to do a reset.
16351     */
16352    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16353        final int packageCount = mPackages.size();
16354        for (int i = 0; i < packageCount; i++) {
16355            PackageParser.Package pkg = mPackages.valueAt(i);
16356            PackageSetting ps = (PackageSetting) pkg.mExtras;
16357            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16358        }
16359    }
16360
16361    private void resetNetworkPolicies(int userId) {
16362        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16363    }
16364
16365    /**
16366     * Reverts user permission state changes (permissions and flags).
16367     *
16368     * @param ps The package for which to reset.
16369     * @param userId The device user for which to do a reset.
16370     */
16371    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16372            final PackageSetting ps, final int userId) {
16373        if (ps.pkg == null) {
16374            return;
16375        }
16376
16377        // These are flags that can change base on user actions.
16378        final int userSettableMask = FLAG_PERMISSION_USER_SET
16379                | FLAG_PERMISSION_USER_FIXED
16380                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16381                | FLAG_PERMISSION_REVIEW_REQUIRED;
16382
16383        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16384                | FLAG_PERMISSION_POLICY_FIXED;
16385
16386        boolean writeInstallPermissions = false;
16387        boolean writeRuntimePermissions = false;
16388
16389        final int permissionCount = ps.pkg.requestedPermissions.size();
16390        for (int i = 0; i < permissionCount; i++) {
16391            String permission = ps.pkg.requestedPermissions.get(i);
16392
16393            BasePermission bp = mSettings.mPermissions.get(permission);
16394            if (bp == null) {
16395                continue;
16396            }
16397
16398            // If shared user we just reset the state to which only this app contributed.
16399            if (ps.sharedUser != null) {
16400                boolean used = false;
16401                final int packageCount = ps.sharedUser.packages.size();
16402                for (int j = 0; j < packageCount; j++) {
16403                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16404                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16405                            && pkg.pkg.requestedPermissions.contains(permission)) {
16406                        used = true;
16407                        break;
16408                    }
16409                }
16410                if (used) {
16411                    continue;
16412                }
16413            }
16414
16415            PermissionsState permissionsState = ps.getPermissionsState();
16416
16417            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16418
16419            // Always clear the user settable flags.
16420            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16421                    bp.name) != null;
16422            // If permission review is enabled and this is a legacy app, mark the
16423            // permission as requiring a review as this is the initial state.
16424            int flags = 0;
16425            if (Build.PERMISSIONS_REVIEW_REQUIRED
16426                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16427                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16428            }
16429            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16430                if (hasInstallState) {
16431                    writeInstallPermissions = true;
16432                } else {
16433                    writeRuntimePermissions = true;
16434                }
16435            }
16436
16437            // Below is only runtime permission handling.
16438            if (!bp.isRuntime()) {
16439                continue;
16440            }
16441
16442            // Never clobber system or policy.
16443            if ((oldFlags & policyOrSystemFlags) != 0) {
16444                continue;
16445            }
16446
16447            // If this permission was granted by default, make sure it is.
16448            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16449                if (permissionsState.grantRuntimePermission(bp, userId)
16450                        != PERMISSION_OPERATION_FAILURE) {
16451                    writeRuntimePermissions = true;
16452                }
16453            // If permission review is enabled the permissions for a legacy apps
16454            // are represented as constantly granted runtime ones, so don't revoke.
16455            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16456                // Otherwise, reset the permission.
16457                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16458                switch (revokeResult) {
16459                    case PERMISSION_OPERATION_SUCCESS:
16460                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16461                        writeRuntimePermissions = true;
16462                        final int appId = ps.appId;
16463                        mHandler.post(new Runnable() {
16464                            @Override
16465                            public void run() {
16466                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16467                            }
16468                        });
16469                    } break;
16470                }
16471            }
16472        }
16473
16474        // Synchronously write as we are taking permissions away.
16475        if (writeRuntimePermissions) {
16476            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16477        }
16478
16479        // Synchronously write as we are taking permissions away.
16480        if (writeInstallPermissions) {
16481            mSettings.writeLPr();
16482        }
16483    }
16484
16485    /**
16486     * Remove entries from the keystore daemon. Will only remove it if the
16487     * {@code appId} is valid.
16488     */
16489    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16490        if (appId < 0) {
16491            return;
16492        }
16493
16494        final KeyStore keyStore = KeyStore.getInstance();
16495        if (keyStore != null) {
16496            if (userId == UserHandle.USER_ALL) {
16497                for (final int individual : sUserManager.getUserIds()) {
16498                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16499                }
16500            } else {
16501                keyStore.clearUid(UserHandle.getUid(userId, appId));
16502            }
16503        } else {
16504            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16505        }
16506    }
16507
16508    @Override
16509    public void deleteApplicationCacheFiles(final String packageName,
16510            final IPackageDataObserver observer) {
16511        final int userId = UserHandle.getCallingUserId();
16512        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16513    }
16514
16515    @Override
16516    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16517            final IPackageDataObserver observer) {
16518        mContext.enforceCallingOrSelfPermission(
16519                android.Manifest.permission.DELETE_CACHE_FILES, null);
16520        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16521                /* requireFullPermission= */ true, /* checkShell= */ false,
16522                "delete application cache files");
16523
16524        final PackageParser.Package pkg;
16525        synchronized (mPackages) {
16526            pkg = mPackages.get(packageName);
16527        }
16528
16529        // Queue up an async operation since the package deletion may take a little while.
16530        mHandler.post(new Runnable() {
16531            public void run() {
16532                synchronized (mInstallLock) {
16533                    final int flags = StorageManager.FLAG_STORAGE_DE
16534                            | StorageManager.FLAG_STORAGE_CE;
16535                    // We're only clearing cache files, so we don't care if the
16536                    // app is unfrozen and still able to run
16537                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16538                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16539                }
16540                clearExternalStorageDataSync(packageName, userId, false);
16541                if (observer != null) {
16542                    try {
16543                        observer.onRemoveCompleted(packageName, true);
16544                    } catch (RemoteException e) {
16545                        Log.i(TAG, "Observer no longer exists.");
16546                    }
16547                }
16548            }
16549        });
16550    }
16551
16552    @Override
16553    public void getPackageSizeInfo(final String packageName, int userHandle,
16554            final IPackageStatsObserver observer) {
16555        mContext.enforceCallingOrSelfPermission(
16556                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16557        if (packageName == null) {
16558            throw new IllegalArgumentException("Attempt to get size of null packageName");
16559        }
16560
16561        PackageStats stats = new PackageStats(packageName, userHandle);
16562
16563        /*
16564         * Queue up an async operation since the package measurement may take a
16565         * little while.
16566         */
16567        Message msg = mHandler.obtainMessage(INIT_COPY);
16568        msg.obj = new MeasureParams(stats, observer);
16569        mHandler.sendMessage(msg);
16570    }
16571
16572    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16573        final PackageSetting ps;
16574        synchronized (mPackages) {
16575            ps = mSettings.mPackages.get(packageName);
16576            if (ps == null) {
16577                Slog.w(TAG, "Failed to find settings for " + packageName);
16578                return false;
16579            }
16580        }
16581        try {
16582            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16583                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16584                    ps.getCeDataInode(userId), ps.codePathString, stats);
16585        } catch (InstallerException e) {
16586            Slog.w(TAG, String.valueOf(e));
16587            return false;
16588        }
16589
16590        // For now, ignore code size of packages on system partition
16591        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16592            stats.codeSize = 0;
16593        }
16594
16595        return true;
16596    }
16597
16598    private int getUidTargetSdkVersionLockedLPr(int uid) {
16599        Object obj = mSettings.getUserIdLPr(uid);
16600        if (obj instanceof SharedUserSetting) {
16601            final SharedUserSetting sus = (SharedUserSetting) obj;
16602            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16603            final Iterator<PackageSetting> it = sus.packages.iterator();
16604            while (it.hasNext()) {
16605                final PackageSetting ps = it.next();
16606                if (ps.pkg != null) {
16607                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16608                    if (v < vers) vers = v;
16609                }
16610            }
16611            return vers;
16612        } else if (obj instanceof PackageSetting) {
16613            final PackageSetting ps = (PackageSetting) obj;
16614            if (ps.pkg != null) {
16615                return ps.pkg.applicationInfo.targetSdkVersion;
16616            }
16617        }
16618        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16619    }
16620
16621    @Override
16622    public void addPreferredActivity(IntentFilter filter, int match,
16623            ComponentName[] set, ComponentName activity, int userId) {
16624        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16625                "Adding preferred");
16626    }
16627
16628    private void addPreferredActivityInternal(IntentFilter filter, int match,
16629            ComponentName[] set, ComponentName activity, boolean always, int userId,
16630            String opname) {
16631        // writer
16632        int callingUid = Binder.getCallingUid();
16633        enforceCrossUserPermission(callingUid, userId,
16634                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16635        if (filter.countActions() == 0) {
16636            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16637            return;
16638        }
16639        synchronized (mPackages) {
16640            if (mContext.checkCallingOrSelfPermission(
16641                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16642                    != PackageManager.PERMISSION_GRANTED) {
16643                if (getUidTargetSdkVersionLockedLPr(callingUid)
16644                        < Build.VERSION_CODES.FROYO) {
16645                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16646                            + callingUid);
16647                    return;
16648                }
16649                mContext.enforceCallingOrSelfPermission(
16650                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16651            }
16652
16653            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16654            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16655                    + userId + ":");
16656            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16657            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16658            scheduleWritePackageRestrictionsLocked(userId);
16659        }
16660    }
16661
16662    @Override
16663    public void replacePreferredActivity(IntentFilter filter, int match,
16664            ComponentName[] set, ComponentName activity, int userId) {
16665        if (filter.countActions() != 1) {
16666            throw new IllegalArgumentException(
16667                    "replacePreferredActivity expects filter to have only 1 action.");
16668        }
16669        if (filter.countDataAuthorities() != 0
16670                || filter.countDataPaths() != 0
16671                || filter.countDataSchemes() > 1
16672                || filter.countDataTypes() != 0) {
16673            throw new IllegalArgumentException(
16674                    "replacePreferredActivity expects filter to have no data authorities, " +
16675                    "paths, or types; and at most one scheme.");
16676        }
16677
16678        final int callingUid = Binder.getCallingUid();
16679        enforceCrossUserPermission(callingUid, userId,
16680                true /* requireFullPermission */, false /* checkShell */,
16681                "replace preferred activity");
16682        synchronized (mPackages) {
16683            if (mContext.checkCallingOrSelfPermission(
16684                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16685                    != PackageManager.PERMISSION_GRANTED) {
16686                if (getUidTargetSdkVersionLockedLPr(callingUid)
16687                        < Build.VERSION_CODES.FROYO) {
16688                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16689                            + Binder.getCallingUid());
16690                    return;
16691                }
16692                mContext.enforceCallingOrSelfPermission(
16693                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16694            }
16695
16696            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16697            if (pir != null) {
16698                // Get all of the existing entries that exactly match this filter.
16699                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16700                if (existing != null && existing.size() == 1) {
16701                    PreferredActivity cur = existing.get(0);
16702                    if (DEBUG_PREFERRED) {
16703                        Slog.i(TAG, "Checking replace of preferred:");
16704                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16705                        if (!cur.mPref.mAlways) {
16706                            Slog.i(TAG, "  -- CUR; not mAlways!");
16707                        } else {
16708                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16709                            Slog.i(TAG, "  -- CUR: mSet="
16710                                    + Arrays.toString(cur.mPref.mSetComponents));
16711                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16712                            Slog.i(TAG, "  -- NEW: mMatch="
16713                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16714                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16715                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16716                        }
16717                    }
16718                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16719                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16720                            && cur.mPref.sameSet(set)) {
16721                        // Setting the preferred activity to what it happens to be already
16722                        if (DEBUG_PREFERRED) {
16723                            Slog.i(TAG, "Replacing with same preferred activity "
16724                                    + cur.mPref.mShortComponent + " for user "
16725                                    + userId + ":");
16726                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16727                        }
16728                        return;
16729                    }
16730                }
16731
16732                if (existing != null) {
16733                    if (DEBUG_PREFERRED) {
16734                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16735                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16736                    }
16737                    for (int i = 0; i < existing.size(); i++) {
16738                        PreferredActivity pa = existing.get(i);
16739                        if (DEBUG_PREFERRED) {
16740                            Slog.i(TAG, "Removing existing preferred activity "
16741                                    + pa.mPref.mComponent + ":");
16742                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16743                        }
16744                        pir.removeFilter(pa);
16745                    }
16746                }
16747            }
16748            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16749                    "Replacing preferred");
16750        }
16751    }
16752
16753    @Override
16754    public void clearPackagePreferredActivities(String packageName) {
16755        final int uid = Binder.getCallingUid();
16756        // writer
16757        synchronized (mPackages) {
16758            PackageParser.Package pkg = mPackages.get(packageName);
16759            if (pkg == null || pkg.applicationInfo.uid != uid) {
16760                if (mContext.checkCallingOrSelfPermission(
16761                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16762                        != PackageManager.PERMISSION_GRANTED) {
16763                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16764                            < Build.VERSION_CODES.FROYO) {
16765                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16766                                + Binder.getCallingUid());
16767                        return;
16768                    }
16769                    mContext.enforceCallingOrSelfPermission(
16770                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16771                }
16772            }
16773
16774            int user = UserHandle.getCallingUserId();
16775            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16776                scheduleWritePackageRestrictionsLocked(user);
16777            }
16778        }
16779    }
16780
16781    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16782    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16783        ArrayList<PreferredActivity> removed = null;
16784        boolean changed = false;
16785        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16786            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16787            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16788            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16789                continue;
16790            }
16791            Iterator<PreferredActivity> it = pir.filterIterator();
16792            while (it.hasNext()) {
16793                PreferredActivity pa = it.next();
16794                // Mark entry for removal only if it matches the package name
16795                // and the entry is of type "always".
16796                if (packageName == null ||
16797                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16798                                && pa.mPref.mAlways)) {
16799                    if (removed == null) {
16800                        removed = new ArrayList<PreferredActivity>();
16801                    }
16802                    removed.add(pa);
16803                }
16804            }
16805            if (removed != null) {
16806                for (int j=0; j<removed.size(); j++) {
16807                    PreferredActivity pa = removed.get(j);
16808                    pir.removeFilter(pa);
16809                }
16810                changed = true;
16811            }
16812        }
16813        return changed;
16814    }
16815
16816    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16817    private void clearIntentFilterVerificationsLPw(int userId) {
16818        final int packageCount = mPackages.size();
16819        for (int i = 0; i < packageCount; i++) {
16820            PackageParser.Package pkg = mPackages.valueAt(i);
16821            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16822        }
16823    }
16824
16825    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16826    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16827        if (userId == UserHandle.USER_ALL) {
16828            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16829                    sUserManager.getUserIds())) {
16830                for (int oneUserId : sUserManager.getUserIds()) {
16831                    scheduleWritePackageRestrictionsLocked(oneUserId);
16832                }
16833            }
16834        } else {
16835            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16836                scheduleWritePackageRestrictionsLocked(userId);
16837            }
16838        }
16839    }
16840
16841    void clearDefaultBrowserIfNeeded(String packageName) {
16842        for (int oneUserId : sUserManager.getUserIds()) {
16843            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16844            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16845            if (packageName.equals(defaultBrowserPackageName)) {
16846                setDefaultBrowserPackageName(null, oneUserId);
16847            }
16848        }
16849    }
16850
16851    @Override
16852    public void resetApplicationPreferences(int userId) {
16853        mContext.enforceCallingOrSelfPermission(
16854                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16855        final long identity = Binder.clearCallingIdentity();
16856        // writer
16857        try {
16858            synchronized (mPackages) {
16859                clearPackagePreferredActivitiesLPw(null, userId);
16860                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16861                // TODO: We have to reset the default SMS and Phone. This requires
16862                // significant refactoring to keep all default apps in the package
16863                // manager (cleaner but more work) or have the services provide
16864                // callbacks to the package manager to request a default app reset.
16865                applyFactoryDefaultBrowserLPw(userId);
16866                clearIntentFilterVerificationsLPw(userId);
16867                primeDomainVerificationsLPw(userId);
16868                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16869                scheduleWritePackageRestrictionsLocked(userId);
16870            }
16871            resetNetworkPolicies(userId);
16872        } finally {
16873            Binder.restoreCallingIdentity(identity);
16874        }
16875    }
16876
16877    @Override
16878    public int getPreferredActivities(List<IntentFilter> outFilters,
16879            List<ComponentName> outActivities, String packageName) {
16880
16881        int num = 0;
16882        final int userId = UserHandle.getCallingUserId();
16883        // reader
16884        synchronized (mPackages) {
16885            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16886            if (pir != null) {
16887                final Iterator<PreferredActivity> it = pir.filterIterator();
16888                while (it.hasNext()) {
16889                    final PreferredActivity pa = it.next();
16890                    if (packageName == null
16891                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16892                                    && pa.mPref.mAlways)) {
16893                        if (outFilters != null) {
16894                            outFilters.add(new IntentFilter(pa));
16895                        }
16896                        if (outActivities != null) {
16897                            outActivities.add(pa.mPref.mComponent);
16898                        }
16899                    }
16900                }
16901            }
16902        }
16903
16904        return num;
16905    }
16906
16907    @Override
16908    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16909            int userId) {
16910        int callingUid = Binder.getCallingUid();
16911        if (callingUid != Process.SYSTEM_UID) {
16912            throw new SecurityException(
16913                    "addPersistentPreferredActivity can only be run by the system");
16914        }
16915        if (filter.countActions() == 0) {
16916            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16917            return;
16918        }
16919        synchronized (mPackages) {
16920            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16921                    ":");
16922            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16923            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16924                    new PersistentPreferredActivity(filter, activity));
16925            scheduleWritePackageRestrictionsLocked(userId);
16926        }
16927    }
16928
16929    @Override
16930    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16931        int callingUid = Binder.getCallingUid();
16932        if (callingUid != Process.SYSTEM_UID) {
16933            throw new SecurityException(
16934                    "clearPackagePersistentPreferredActivities can only be run by the system");
16935        }
16936        ArrayList<PersistentPreferredActivity> removed = null;
16937        boolean changed = false;
16938        synchronized (mPackages) {
16939            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16940                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16941                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16942                        .valueAt(i);
16943                if (userId != thisUserId) {
16944                    continue;
16945                }
16946                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16947                while (it.hasNext()) {
16948                    PersistentPreferredActivity ppa = it.next();
16949                    // Mark entry for removal only if it matches the package name.
16950                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16951                        if (removed == null) {
16952                            removed = new ArrayList<PersistentPreferredActivity>();
16953                        }
16954                        removed.add(ppa);
16955                    }
16956                }
16957                if (removed != null) {
16958                    for (int j=0; j<removed.size(); j++) {
16959                        PersistentPreferredActivity ppa = removed.get(j);
16960                        ppir.removeFilter(ppa);
16961                    }
16962                    changed = true;
16963                }
16964            }
16965
16966            if (changed) {
16967                scheduleWritePackageRestrictionsLocked(userId);
16968            }
16969        }
16970    }
16971
16972    /**
16973     * Common machinery for picking apart a restored XML blob and passing
16974     * it to a caller-supplied functor to be applied to the running system.
16975     */
16976    private void restoreFromXml(XmlPullParser parser, int userId,
16977            String expectedStartTag, BlobXmlRestorer functor)
16978            throws IOException, XmlPullParserException {
16979        int type;
16980        while ((type = parser.next()) != XmlPullParser.START_TAG
16981                && type != XmlPullParser.END_DOCUMENT) {
16982        }
16983        if (type != XmlPullParser.START_TAG) {
16984            // oops didn't find a start tag?!
16985            if (DEBUG_BACKUP) {
16986                Slog.e(TAG, "Didn't find start tag during restore");
16987            }
16988            return;
16989        }
16990Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16991        // this is supposed to be TAG_PREFERRED_BACKUP
16992        if (!expectedStartTag.equals(parser.getName())) {
16993            if (DEBUG_BACKUP) {
16994                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16995            }
16996            return;
16997        }
16998
16999        // skip interfering stuff, then we're aligned with the backing implementation
17000        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17001Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17002        functor.apply(parser, userId);
17003    }
17004
17005    private interface BlobXmlRestorer {
17006        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17007    }
17008
17009    /**
17010     * Non-Binder method, support for the backup/restore mechanism: write the
17011     * full set of preferred activities in its canonical XML format.  Returns the
17012     * XML output as a byte array, or null if there is none.
17013     */
17014    @Override
17015    public byte[] getPreferredActivityBackup(int userId) {
17016        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17017            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17018        }
17019
17020        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17021        try {
17022            final XmlSerializer serializer = new FastXmlSerializer();
17023            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17024            serializer.startDocument(null, true);
17025            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17026
17027            synchronized (mPackages) {
17028                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17029            }
17030
17031            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17032            serializer.endDocument();
17033            serializer.flush();
17034        } catch (Exception e) {
17035            if (DEBUG_BACKUP) {
17036                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17037            }
17038            return null;
17039        }
17040
17041        return dataStream.toByteArray();
17042    }
17043
17044    @Override
17045    public void restorePreferredActivities(byte[] backup, int userId) {
17046        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17047            throw new SecurityException("Only the system may call restorePreferredActivities()");
17048        }
17049
17050        try {
17051            final XmlPullParser parser = Xml.newPullParser();
17052            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17053            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17054                    new BlobXmlRestorer() {
17055                        @Override
17056                        public void apply(XmlPullParser parser, int userId)
17057                                throws XmlPullParserException, IOException {
17058                            synchronized (mPackages) {
17059                                mSettings.readPreferredActivitiesLPw(parser, userId);
17060                            }
17061                        }
17062                    } );
17063        } catch (Exception e) {
17064            if (DEBUG_BACKUP) {
17065                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17066            }
17067        }
17068    }
17069
17070    /**
17071     * Non-Binder method, support for the backup/restore mechanism: write the
17072     * default browser (etc) settings in its canonical XML format.  Returns the default
17073     * browser XML representation as a byte array, or null if there is none.
17074     */
17075    @Override
17076    public byte[] getDefaultAppsBackup(int userId) {
17077        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17078            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17079        }
17080
17081        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17082        try {
17083            final XmlSerializer serializer = new FastXmlSerializer();
17084            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17085            serializer.startDocument(null, true);
17086            serializer.startTag(null, TAG_DEFAULT_APPS);
17087
17088            synchronized (mPackages) {
17089                mSettings.writeDefaultAppsLPr(serializer, userId);
17090            }
17091
17092            serializer.endTag(null, TAG_DEFAULT_APPS);
17093            serializer.endDocument();
17094            serializer.flush();
17095        } catch (Exception e) {
17096            if (DEBUG_BACKUP) {
17097                Slog.e(TAG, "Unable to write default apps for backup", e);
17098            }
17099            return null;
17100        }
17101
17102        return dataStream.toByteArray();
17103    }
17104
17105    @Override
17106    public void restoreDefaultApps(byte[] backup, int userId) {
17107        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17108            throw new SecurityException("Only the system may call restoreDefaultApps()");
17109        }
17110
17111        try {
17112            final XmlPullParser parser = Xml.newPullParser();
17113            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17114            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17115                    new BlobXmlRestorer() {
17116                        @Override
17117                        public void apply(XmlPullParser parser, int userId)
17118                                throws XmlPullParserException, IOException {
17119                            synchronized (mPackages) {
17120                                mSettings.readDefaultAppsLPw(parser, userId);
17121                            }
17122                        }
17123                    } );
17124        } catch (Exception e) {
17125            if (DEBUG_BACKUP) {
17126                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17127            }
17128        }
17129    }
17130
17131    @Override
17132    public byte[] getIntentFilterVerificationBackup(int userId) {
17133        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17134            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17135        }
17136
17137        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17138        try {
17139            final XmlSerializer serializer = new FastXmlSerializer();
17140            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17141            serializer.startDocument(null, true);
17142            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17143
17144            synchronized (mPackages) {
17145                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17146            }
17147
17148            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17149            serializer.endDocument();
17150            serializer.flush();
17151        } catch (Exception e) {
17152            if (DEBUG_BACKUP) {
17153                Slog.e(TAG, "Unable to write default apps for backup", e);
17154            }
17155            return null;
17156        }
17157
17158        return dataStream.toByteArray();
17159    }
17160
17161    @Override
17162    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17163        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17164            throw new SecurityException("Only the system may call restorePreferredActivities()");
17165        }
17166
17167        try {
17168            final XmlPullParser parser = Xml.newPullParser();
17169            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17170            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17171                    new BlobXmlRestorer() {
17172                        @Override
17173                        public void apply(XmlPullParser parser, int userId)
17174                                throws XmlPullParserException, IOException {
17175                            synchronized (mPackages) {
17176                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17177                                mSettings.writeLPr();
17178                            }
17179                        }
17180                    } );
17181        } catch (Exception e) {
17182            if (DEBUG_BACKUP) {
17183                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17184            }
17185        }
17186    }
17187
17188    @Override
17189    public byte[] getPermissionGrantBackup(int userId) {
17190        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17191            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17192        }
17193
17194        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17195        try {
17196            final XmlSerializer serializer = new FastXmlSerializer();
17197            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17198            serializer.startDocument(null, true);
17199            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17200
17201            synchronized (mPackages) {
17202                serializeRuntimePermissionGrantsLPr(serializer, userId);
17203            }
17204
17205            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17206            serializer.endDocument();
17207            serializer.flush();
17208        } catch (Exception e) {
17209            if (DEBUG_BACKUP) {
17210                Slog.e(TAG, "Unable to write default apps for backup", e);
17211            }
17212            return null;
17213        }
17214
17215        return dataStream.toByteArray();
17216    }
17217
17218    @Override
17219    public void restorePermissionGrants(byte[] backup, int userId) {
17220        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17221            throw new SecurityException("Only the system may call restorePermissionGrants()");
17222        }
17223
17224        try {
17225            final XmlPullParser parser = Xml.newPullParser();
17226            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17227            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17228                    new BlobXmlRestorer() {
17229                        @Override
17230                        public void apply(XmlPullParser parser, int userId)
17231                                throws XmlPullParserException, IOException {
17232                            synchronized (mPackages) {
17233                                processRestoredPermissionGrantsLPr(parser, userId);
17234                            }
17235                        }
17236                    } );
17237        } catch (Exception e) {
17238            if (DEBUG_BACKUP) {
17239                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17240            }
17241        }
17242    }
17243
17244    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17245            throws IOException {
17246        serializer.startTag(null, TAG_ALL_GRANTS);
17247
17248        final int N = mSettings.mPackages.size();
17249        for (int i = 0; i < N; i++) {
17250            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17251            boolean pkgGrantsKnown = false;
17252
17253            PermissionsState packagePerms = ps.getPermissionsState();
17254
17255            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17256                final int grantFlags = state.getFlags();
17257                // only look at grants that are not system/policy fixed
17258                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17259                    final boolean isGranted = state.isGranted();
17260                    // And only back up the user-twiddled state bits
17261                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17262                        final String packageName = mSettings.mPackages.keyAt(i);
17263                        if (!pkgGrantsKnown) {
17264                            serializer.startTag(null, TAG_GRANT);
17265                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17266                            pkgGrantsKnown = true;
17267                        }
17268
17269                        final boolean userSet =
17270                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17271                        final boolean userFixed =
17272                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17273                        final boolean revoke =
17274                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17275
17276                        serializer.startTag(null, TAG_PERMISSION);
17277                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17278                        if (isGranted) {
17279                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17280                        }
17281                        if (userSet) {
17282                            serializer.attribute(null, ATTR_USER_SET, "true");
17283                        }
17284                        if (userFixed) {
17285                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17286                        }
17287                        if (revoke) {
17288                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17289                        }
17290                        serializer.endTag(null, TAG_PERMISSION);
17291                    }
17292                }
17293            }
17294
17295            if (pkgGrantsKnown) {
17296                serializer.endTag(null, TAG_GRANT);
17297            }
17298        }
17299
17300        serializer.endTag(null, TAG_ALL_GRANTS);
17301    }
17302
17303    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17304            throws XmlPullParserException, IOException {
17305        String pkgName = null;
17306        int outerDepth = parser.getDepth();
17307        int type;
17308        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17309                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17310            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17311                continue;
17312            }
17313
17314            final String tagName = parser.getName();
17315            if (tagName.equals(TAG_GRANT)) {
17316                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17317                if (DEBUG_BACKUP) {
17318                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17319                }
17320            } else if (tagName.equals(TAG_PERMISSION)) {
17321
17322                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17323                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17324
17325                int newFlagSet = 0;
17326                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17327                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17328                }
17329                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17330                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17331                }
17332                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17333                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17334                }
17335                if (DEBUG_BACKUP) {
17336                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17337                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17338                }
17339                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17340                if (ps != null) {
17341                    // Already installed so we apply the grant immediately
17342                    if (DEBUG_BACKUP) {
17343                        Slog.v(TAG, "        + already installed; applying");
17344                    }
17345                    PermissionsState perms = ps.getPermissionsState();
17346                    BasePermission bp = mSettings.mPermissions.get(permName);
17347                    if (bp != null) {
17348                        if (isGranted) {
17349                            perms.grantRuntimePermission(bp, userId);
17350                        }
17351                        if (newFlagSet != 0) {
17352                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17353                        }
17354                    }
17355                } else {
17356                    // Need to wait for post-restore install to apply the grant
17357                    if (DEBUG_BACKUP) {
17358                        Slog.v(TAG, "        - not yet installed; saving for later");
17359                    }
17360                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17361                            isGranted, newFlagSet, userId);
17362                }
17363            } else {
17364                PackageManagerService.reportSettingsProblem(Log.WARN,
17365                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17366                XmlUtils.skipCurrentTag(parser);
17367            }
17368        }
17369
17370        scheduleWriteSettingsLocked();
17371        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17372    }
17373
17374    @Override
17375    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17376            int sourceUserId, int targetUserId, int flags) {
17377        mContext.enforceCallingOrSelfPermission(
17378                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17379        int callingUid = Binder.getCallingUid();
17380        enforceOwnerRights(ownerPackage, callingUid);
17381        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17382        if (intentFilter.countActions() == 0) {
17383            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17384            return;
17385        }
17386        synchronized (mPackages) {
17387            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17388                    ownerPackage, targetUserId, flags);
17389            CrossProfileIntentResolver resolver =
17390                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17391            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17392            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17393            if (existing != null) {
17394                int size = existing.size();
17395                for (int i = 0; i < size; i++) {
17396                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17397                        return;
17398                    }
17399                }
17400            }
17401            resolver.addFilter(newFilter);
17402            scheduleWritePackageRestrictionsLocked(sourceUserId);
17403        }
17404    }
17405
17406    @Override
17407    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17408        mContext.enforceCallingOrSelfPermission(
17409                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17410        int callingUid = Binder.getCallingUid();
17411        enforceOwnerRights(ownerPackage, callingUid);
17412        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17413        synchronized (mPackages) {
17414            CrossProfileIntentResolver resolver =
17415                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17416            ArraySet<CrossProfileIntentFilter> set =
17417                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17418            for (CrossProfileIntentFilter filter : set) {
17419                if (filter.getOwnerPackage().equals(ownerPackage)) {
17420                    resolver.removeFilter(filter);
17421                }
17422            }
17423            scheduleWritePackageRestrictionsLocked(sourceUserId);
17424        }
17425    }
17426
17427    // Enforcing that callingUid is owning pkg on userId
17428    private void enforceOwnerRights(String pkg, int callingUid) {
17429        // The system owns everything.
17430        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17431            return;
17432        }
17433        int callingUserId = UserHandle.getUserId(callingUid);
17434        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17435        if (pi == null) {
17436            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17437                    + callingUserId);
17438        }
17439        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17440            throw new SecurityException("Calling uid " + callingUid
17441                    + " does not own package " + pkg);
17442        }
17443    }
17444
17445    @Override
17446    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17447        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17448    }
17449
17450    private Intent getHomeIntent() {
17451        Intent intent = new Intent(Intent.ACTION_MAIN);
17452        intent.addCategory(Intent.CATEGORY_HOME);
17453        return intent;
17454    }
17455
17456    private IntentFilter getHomeFilter() {
17457        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17458        filter.addCategory(Intent.CATEGORY_HOME);
17459        filter.addCategory(Intent.CATEGORY_DEFAULT);
17460        return filter;
17461    }
17462
17463    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17464            int userId) {
17465        Intent intent  = getHomeIntent();
17466        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17467                PackageManager.GET_META_DATA, userId);
17468        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17469                true, false, false, userId);
17470
17471        allHomeCandidates.clear();
17472        if (list != null) {
17473            for (ResolveInfo ri : list) {
17474                allHomeCandidates.add(ri);
17475            }
17476        }
17477        return (preferred == null || preferred.activityInfo == null)
17478                ? null
17479                : new ComponentName(preferred.activityInfo.packageName,
17480                        preferred.activityInfo.name);
17481    }
17482
17483    @Override
17484    public void setHomeActivity(ComponentName comp, int userId) {
17485        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17486        getHomeActivitiesAsUser(homeActivities, userId);
17487
17488        boolean found = false;
17489
17490        final int size = homeActivities.size();
17491        final ComponentName[] set = new ComponentName[size];
17492        for (int i = 0; i < size; i++) {
17493            final ResolveInfo candidate = homeActivities.get(i);
17494            final ActivityInfo info = candidate.activityInfo;
17495            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17496            set[i] = activityName;
17497            if (!found && activityName.equals(comp)) {
17498                found = true;
17499            }
17500        }
17501        if (!found) {
17502            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17503                    + userId);
17504        }
17505        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17506                set, comp, userId);
17507    }
17508
17509    private @Nullable String getSetupWizardPackageName() {
17510        final Intent intent = new Intent(Intent.ACTION_MAIN);
17511        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17512
17513        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17514                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17515                        | MATCH_DISABLED_COMPONENTS,
17516                UserHandle.myUserId());
17517        if (matches.size() == 1) {
17518            return matches.get(0).getComponentInfo().packageName;
17519        } else {
17520            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17521                    + ": matches=" + matches);
17522            return null;
17523        }
17524    }
17525
17526    @Override
17527    public void setApplicationEnabledSetting(String appPackageName,
17528            int newState, int flags, int userId, String callingPackage) {
17529        if (!sUserManager.exists(userId)) return;
17530        if (callingPackage == null) {
17531            callingPackage = Integer.toString(Binder.getCallingUid());
17532        }
17533        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17534    }
17535
17536    @Override
17537    public void setComponentEnabledSetting(ComponentName componentName,
17538            int newState, int flags, int userId) {
17539        if (!sUserManager.exists(userId)) return;
17540        setEnabledSetting(componentName.getPackageName(),
17541                componentName.getClassName(), newState, flags, userId, null);
17542    }
17543
17544    private void setEnabledSetting(final String packageName, String className, int newState,
17545            final int flags, int userId, String callingPackage) {
17546        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17547              || newState == COMPONENT_ENABLED_STATE_ENABLED
17548              || newState == COMPONENT_ENABLED_STATE_DISABLED
17549              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17550              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17551            throw new IllegalArgumentException("Invalid new component state: "
17552                    + newState);
17553        }
17554        PackageSetting pkgSetting;
17555        final int uid = Binder.getCallingUid();
17556        final int permission;
17557        if (uid == Process.SYSTEM_UID) {
17558            permission = PackageManager.PERMISSION_GRANTED;
17559        } else {
17560            permission = mContext.checkCallingOrSelfPermission(
17561                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17562        }
17563        enforceCrossUserPermission(uid, userId,
17564                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17565        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17566        boolean sendNow = false;
17567        boolean isApp = (className == null);
17568        String componentName = isApp ? packageName : className;
17569        int packageUid = -1;
17570        ArrayList<String> components;
17571
17572        // writer
17573        synchronized (mPackages) {
17574            pkgSetting = mSettings.mPackages.get(packageName);
17575            if (pkgSetting == null) {
17576                if (className == null) {
17577                    throw new IllegalArgumentException("Unknown package: " + packageName);
17578                }
17579                throw new IllegalArgumentException(
17580                        "Unknown component: " + packageName + "/" + className);
17581            }
17582        }
17583
17584        // Limit who can change which apps
17585        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17586            // Don't allow apps that don't have permission to modify other apps
17587            if (!allowedByPermission) {
17588                throw new SecurityException(
17589                        "Permission Denial: attempt to change component state from pid="
17590                        + Binder.getCallingPid()
17591                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17592            }
17593            // Don't allow changing profile and device owners. Calling into DPMS, so no locking.
17594            final DevicePolicyManagerInternal dpmi = LocalServices
17595                    .getService(DevicePolicyManagerInternal.class);
17596            if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
17597                throw new SecurityException("Cannot disable a device owner or a profile owner");
17598            }
17599        }
17600
17601        synchronized (mPackages) {
17602            if (uid == Process.SHELL_UID) {
17603                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17604                int oldState = pkgSetting.getEnabled(userId);
17605                if (className == null
17606                    &&
17607                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17608                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17609                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17610                    &&
17611                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17612                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17613                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17614                    // ok
17615                } else {
17616                    throw new SecurityException(
17617                            "Shell cannot change component state for " + packageName + "/"
17618                            + className + " to " + newState);
17619                }
17620            }
17621            if (className == null) {
17622                // We're dealing with an application/package level state change
17623                if (pkgSetting.getEnabled(userId) == newState) {
17624                    // Nothing to do
17625                    return;
17626                }
17627                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17628                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17629                    // Don't care about who enables an app.
17630                    callingPackage = null;
17631                }
17632                pkgSetting.setEnabled(newState, userId, callingPackage);
17633                // pkgSetting.pkg.mSetEnabled = newState;
17634            } else {
17635                // We're dealing with a component level state change
17636                // First, verify that this is a valid class name.
17637                PackageParser.Package pkg = pkgSetting.pkg;
17638                if (pkg == null || !pkg.hasComponentClassName(className)) {
17639                    if (pkg != null &&
17640                            pkg.applicationInfo.targetSdkVersion >=
17641                                    Build.VERSION_CODES.JELLY_BEAN) {
17642                        throw new IllegalArgumentException("Component class " + className
17643                                + " does not exist in " + packageName);
17644                    } else {
17645                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17646                                + className + " does not exist in " + packageName);
17647                    }
17648                }
17649                switch (newState) {
17650                case COMPONENT_ENABLED_STATE_ENABLED:
17651                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17652                        return;
17653                    }
17654                    break;
17655                case COMPONENT_ENABLED_STATE_DISABLED:
17656                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17657                        return;
17658                    }
17659                    break;
17660                case COMPONENT_ENABLED_STATE_DEFAULT:
17661                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17662                        return;
17663                    }
17664                    break;
17665                default:
17666                    Slog.e(TAG, "Invalid new component state: " + newState);
17667                    return;
17668                }
17669            }
17670            scheduleWritePackageRestrictionsLocked(userId);
17671            components = mPendingBroadcasts.get(userId, packageName);
17672            final boolean newPackage = components == null;
17673            if (newPackage) {
17674                components = new ArrayList<String>();
17675            }
17676            if (!components.contains(componentName)) {
17677                components.add(componentName);
17678            }
17679            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17680                sendNow = true;
17681                // Purge entry from pending broadcast list if another one exists already
17682                // since we are sending one right away.
17683                mPendingBroadcasts.remove(userId, packageName);
17684            } else {
17685                if (newPackage) {
17686                    mPendingBroadcasts.put(userId, packageName, components);
17687                }
17688                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17689                    // Schedule a message
17690                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17691                }
17692            }
17693        }
17694
17695        long callingId = Binder.clearCallingIdentity();
17696        try {
17697            if (sendNow) {
17698                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17699                sendPackageChangedBroadcast(packageName,
17700                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17701            }
17702        } finally {
17703            Binder.restoreCallingIdentity(callingId);
17704        }
17705    }
17706
17707    @Override
17708    public void flushPackageRestrictionsAsUser(int userId) {
17709        if (!sUserManager.exists(userId)) {
17710            return;
17711        }
17712        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17713                false /* checkShell */, "flushPackageRestrictions");
17714        synchronized (mPackages) {
17715            mSettings.writePackageRestrictionsLPr(userId);
17716            mDirtyUsers.remove(userId);
17717            if (mDirtyUsers.isEmpty()) {
17718                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17719            }
17720        }
17721    }
17722
17723    private void sendPackageChangedBroadcast(String packageName,
17724            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17725        if (DEBUG_INSTALL)
17726            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17727                    + componentNames);
17728        Bundle extras = new Bundle(4);
17729        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17730        String nameList[] = new String[componentNames.size()];
17731        componentNames.toArray(nameList);
17732        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17733        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17734        extras.putInt(Intent.EXTRA_UID, packageUid);
17735        // If this is not reporting a change of the overall package, then only send it
17736        // to registered receivers.  We don't want to launch a swath of apps for every
17737        // little component state change.
17738        final int flags = !componentNames.contains(packageName)
17739                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17740        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17741                new int[] {UserHandle.getUserId(packageUid)});
17742    }
17743
17744    @Override
17745    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17746        if (!sUserManager.exists(userId)) return;
17747        final int uid = Binder.getCallingUid();
17748        final int permission = mContext.checkCallingOrSelfPermission(
17749                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17750        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17751        enforceCrossUserPermission(uid, userId,
17752                true /* requireFullPermission */, true /* checkShell */, "stop package");
17753        // writer
17754        synchronized (mPackages) {
17755            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17756                    allowedByPermission, uid, userId)) {
17757                scheduleWritePackageRestrictionsLocked(userId);
17758            }
17759        }
17760    }
17761
17762    @Override
17763    public String getInstallerPackageName(String packageName) {
17764        // reader
17765        synchronized (mPackages) {
17766            return mSettings.getInstallerPackageNameLPr(packageName);
17767        }
17768    }
17769
17770    public boolean isOrphaned(String packageName) {
17771        // reader
17772        synchronized (mPackages) {
17773            return mSettings.isOrphaned(packageName);
17774        }
17775    }
17776
17777    @Override
17778    public int getApplicationEnabledSetting(String packageName, int userId) {
17779        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17780        int uid = Binder.getCallingUid();
17781        enforceCrossUserPermission(uid, userId,
17782                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17783        // reader
17784        synchronized (mPackages) {
17785            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17786        }
17787    }
17788
17789    @Override
17790    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17791        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17792        int uid = Binder.getCallingUid();
17793        enforceCrossUserPermission(uid, userId,
17794                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17795        // reader
17796        synchronized (mPackages) {
17797            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17798        }
17799    }
17800
17801    @Override
17802    public void enterSafeMode() {
17803        enforceSystemOrRoot("Only the system can request entering safe mode");
17804
17805        if (!mSystemReady) {
17806            mSafeMode = true;
17807        }
17808    }
17809
17810    @Override
17811    public void systemReady() {
17812        mSystemReady = true;
17813
17814        // Read the compatibilty setting when the system is ready.
17815        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17816                mContext.getContentResolver(),
17817                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17818        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17819        if (DEBUG_SETTINGS) {
17820            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17821        }
17822
17823        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17824
17825        synchronized (mPackages) {
17826            // Verify that all of the preferred activity components actually
17827            // exist.  It is possible for applications to be updated and at
17828            // that point remove a previously declared activity component that
17829            // had been set as a preferred activity.  We try to clean this up
17830            // the next time we encounter that preferred activity, but it is
17831            // possible for the user flow to never be able to return to that
17832            // situation so here we do a sanity check to make sure we haven't
17833            // left any junk around.
17834            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17835            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17836                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17837                removed.clear();
17838                for (PreferredActivity pa : pir.filterSet()) {
17839                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17840                        removed.add(pa);
17841                    }
17842                }
17843                if (removed.size() > 0) {
17844                    for (int r=0; r<removed.size(); r++) {
17845                        PreferredActivity pa = removed.get(r);
17846                        Slog.w(TAG, "Removing dangling preferred activity: "
17847                                + pa.mPref.mComponent);
17848                        pir.removeFilter(pa);
17849                    }
17850                    mSettings.writePackageRestrictionsLPr(
17851                            mSettings.mPreferredActivities.keyAt(i));
17852                }
17853            }
17854
17855            for (int userId : UserManagerService.getInstance().getUserIds()) {
17856                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17857                    grantPermissionsUserIds = ArrayUtils.appendInt(
17858                            grantPermissionsUserIds, userId);
17859                }
17860            }
17861        }
17862        sUserManager.systemReady();
17863
17864        // If we upgraded grant all default permissions before kicking off.
17865        for (int userId : grantPermissionsUserIds) {
17866            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17867        }
17868
17869        // Kick off any messages waiting for system ready
17870        if (mPostSystemReadyMessages != null) {
17871            for (Message msg : mPostSystemReadyMessages) {
17872                msg.sendToTarget();
17873            }
17874            mPostSystemReadyMessages = null;
17875        }
17876
17877        // Watch for external volumes that come and go over time
17878        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17879        storage.registerListener(mStorageListener);
17880
17881        mInstallerService.systemReady();
17882        mPackageDexOptimizer.systemReady();
17883
17884        MountServiceInternal mountServiceInternal = LocalServices.getService(
17885                MountServiceInternal.class);
17886        mountServiceInternal.addExternalStoragePolicy(
17887                new MountServiceInternal.ExternalStorageMountPolicy() {
17888            @Override
17889            public int getMountMode(int uid, String packageName) {
17890                if (Process.isIsolated(uid)) {
17891                    return Zygote.MOUNT_EXTERNAL_NONE;
17892                }
17893                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17894                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17895                }
17896                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17897                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17898                }
17899                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17900                    return Zygote.MOUNT_EXTERNAL_READ;
17901                }
17902                return Zygote.MOUNT_EXTERNAL_WRITE;
17903            }
17904
17905            @Override
17906            public boolean hasExternalStorage(int uid, String packageName) {
17907                return true;
17908            }
17909        });
17910
17911        // Now that we're mostly running, clean up stale users and apps
17912        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17913        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17914    }
17915
17916    @Override
17917    public boolean isSafeMode() {
17918        return mSafeMode;
17919    }
17920
17921    @Override
17922    public boolean hasSystemUidErrors() {
17923        return mHasSystemUidErrors;
17924    }
17925
17926    static String arrayToString(int[] array) {
17927        StringBuffer buf = new StringBuffer(128);
17928        buf.append('[');
17929        if (array != null) {
17930            for (int i=0; i<array.length; i++) {
17931                if (i > 0) buf.append(", ");
17932                buf.append(array[i]);
17933            }
17934        }
17935        buf.append(']');
17936        return buf.toString();
17937    }
17938
17939    static class DumpState {
17940        public static final int DUMP_LIBS = 1 << 0;
17941        public static final int DUMP_FEATURES = 1 << 1;
17942        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17943        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17944        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17945        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17946        public static final int DUMP_PERMISSIONS = 1 << 6;
17947        public static final int DUMP_PACKAGES = 1 << 7;
17948        public static final int DUMP_SHARED_USERS = 1 << 8;
17949        public static final int DUMP_MESSAGES = 1 << 9;
17950        public static final int DUMP_PROVIDERS = 1 << 10;
17951        public static final int DUMP_VERIFIERS = 1 << 11;
17952        public static final int DUMP_PREFERRED = 1 << 12;
17953        public static final int DUMP_PREFERRED_XML = 1 << 13;
17954        public static final int DUMP_KEYSETS = 1 << 14;
17955        public static final int DUMP_VERSION = 1 << 15;
17956        public static final int DUMP_INSTALLS = 1 << 16;
17957        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17958        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17959        public static final int DUMP_FROZEN = 1 << 19;
17960        public static final int DUMP_DEXOPT = 1 << 20;
17961
17962        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17963
17964        private int mTypes;
17965
17966        private int mOptions;
17967
17968        private boolean mTitlePrinted;
17969
17970        private SharedUserSetting mSharedUser;
17971
17972        public boolean isDumping(int type) {
17973            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17974                return true;
17975            }
17976
17977            return (mTypes & type) != 0;
17978        }
17979
17980        public void setDump(int type) {
17981            mTypes |= type;
17982        }
17983
17984        public boolean isOptionEnabled(int option) {
17985            return (mOptions & option) != 0;
17986        }
17987
17988        public void setOptionEnabled(int option) {
17989            mOptions |= option;
17990        }
17991
17992        public boolean onTitlePrinted() {
17993            final boolean printed = mTitlePrinted;
17994            mTitlePrinted = true;
17995            return printed;
17996        }
17997
17998        public boolean getTitlePrinted() {
17999            return mTitlePrinted;
18000        }
18001
18002        public void setTitlePrinted(boolean enabled) {
18003            mTitlePrinted = enabled;
18004        }
18005
18006        public SharedUserSetting getSharedUser() {
18007            return mSharedUser;
18008        }
18009
18010        public void setSharedUser(SharedUserSetting user) {
18011            mSharedUser = user;
18012        }
18013    }
18014
18015    @Override
18016    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18017            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18018        (new PackageManagerShellCommand(this)).exec(
18019                this, in, out, err, args, resultReceiver);
18020    }
18021
18022    @Override
18023    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18024        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18025                != PackageManager.PERMISSION_GRANTED) {
18026            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18027                    + Binder.getCallingPid()
18028                    + ", uid=" + Binder.getCallingUid()
18029                    + " without permission "
18030                    + android.Manifest.permission.DUMP);
18031            return;
18032        }
18033
18034        DumpState dumpState = new DumpState();
18035        boolean fullPreferred = false;
18036        boolean checkin = false;
18037
18038        String packageName = null;
18039        ArraySet<String> permissionNames = null;
18040
18041        int opti = 0;
18042        while (opti < args.length) {
18043            String opt = args[opti];
18044            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18045                break;
18046            }
18047            opti++;
18048
18049            if ("-a".equals(opt)) {
18050                // Right now we only know how to print all.
18051            } else if ("-h".equals(opt)) {
18052                pw.println("Package manager dump options:");
18053                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18054                pw.println("    --checkin: dump for a checkin");
18055                pw.println("    -f: print details of intent filters");
18056                pw.println("    -h: print this help");
18057                pw.println("  cmd may be one of:");
18058                pw.println("    l[ibraries]: list known shared libraries");
18059                pw.println("    f[eatures]: list device features");
18060                pw.println("    k[eysets]: print known keysets");
18061                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18062                pw.println("    perm[issions]: dump permissions");
18063                pw.println("    permission [name ...]: dump declaration and use of given permission");
18064                pw.println("    pref[erred]: print preferred package settings");
18065                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18066                pw.println("    prov[iders]: dump content providers");
18067                pw.println("    p[ackages]: dump installed packages");
18068                pw.println("    s[hared-users]: dump shared user IDs");
18069                pw.println("    m[essages]: print collected runtime messages");
18070                pw.println("    v[erifiers]: print package verifier info");
18071                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18072                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18073                pw.println("    version: print database version info");
18074                pw.println("    write: write current settings now");
18075                pw.println("    installs: details about install sessions");
18076                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18077                pw.println("    dexopt: dump dexopt state");
18078                pw.println("    <package.name>: info about given package");
18079                return;
18080            } else if ("--checkin".equals(opt)) {
18081                checkin = true;
18082            } else if ("-f".equals(opt)) {
18083                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18084            } else {
18085                pw.println("Unknown argument: " + opt + "; use -h for help");
18086            }
18087        }
18088
18089        // Is the caller requesting to dump a particular piece of data?
18090        if (opti < args.length) {
18091            String cmd = args[opti];
18092            opti++;
18093            // Is this a package name?
18094            if ("android".equals(cmd) || cmd.contains(".")) {
18095                packageName = cmd;
18096                // When dumping a single package, we always dump all of its
18097                // filter information since the amount of data will be reasonable.
18098                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18099            } else if ("check-permission".equals(cmd)) {
18100                if (opti >= args.length) {
18101                    pw.println("Error: check-permission missing permission argument");
18102                    return;
18103                }
18104                String perm = args[opti];
18105                opti++;
18106                if (opti >= args.length) {
18107                    pw.println("Error: check-permission missing package argument");
18108                    return;
18109                }
18110                String pkg = args[opti];
18111                opti++;
18112                int user = UserHandle.getUserId(Binder.getCallingUid());
18113                if (opti < args.length) {
18114                    try {
18115                        user = Integer.parseInt(args[opti]);
18116                    } catch (NumberFormatException e) {
18117                        pw.println("Error: check-permission user argument is not a number: "
18118                                + args[opti]);
18119                        return;
18120                    }
18121                }
18122                pw.println(checkPermission(perm, pkg, user));
18123                return;
18124            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18125                dumpState.setDump(DumpState.DUMP_LIBS);
18126            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18127                dumpState.setDump(DumpState.DUMP_FEATURES);
18128            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18129                if (opti >= args.length) {
18130                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18131                            | DumpState.DUMP_SERVICE_RESOLVERS
18132                            | DumpState.DUMP_RECEIVER_RESOLVERS
18133                            | DumpState.DUMP_CONTENT_RESOLVERS);
18134                } else {
18135                    while (opti < args.length) {
18136                        String name = args[opti];
18137                        if ("a".equals(name) || "activity".equals(name)) {
18138                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18139                        } else if ("s".equals(name) || "service".equals(name)) {
18140                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18141                        } else if ("r".equals(name) || "receiver".equals(name)) {
18142                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18143                        } else if ("c".equals(name) || "content".equals(name)) {
18144                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18145                        } else {
18146                            pw.println("Error: unknown resolver table type: " + name);
18147                            return;
18148                        }
18149                        opti++;
18150                    }
18151                }
18152            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18153                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18154            } else if ("permission".equals(cmd)) {
18155                if (opti >= args.length) {
18156                    pw.println("Error: permission requires permission name");
18157                    return;
18158                }
18159                permissionNames = new ArraySet<>();
18160                while (opti < args.length) {
18161                    permissionNames.add(args[opti]);
18162                    opti++;
18163                }
18164                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18165                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18166            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18167                dumpState.setDump(DumpState.DUMP_PREFERRED);
18168            } else if ("preferred-xml".equals(cmd)) {
18169                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18170                if (opti < args.length && "--full".equals(args[opti])) {
18171                    fullPreferred = true;
18172                    opti++;
18173                }
18174            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18175                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18176            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18177                dumpState.setDump(DumpState.DUMP_PACKAGES);
18178            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18179                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18180            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18181                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18182            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18183                dumpState.setDump(DumpState.DUMP_MESSAGES);
18184            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18185                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18186            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18187                    || "intent-filter-verifiers".equals(cmd)) {
18188                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18189            } else if ("version".equals(cmd)) {
18190                dumpState.setDump(DumpState.DUMP_VERSION);
18191            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18192                dumpState.setDump(DumpState.DUMP_KEYSETS);
18193            } else if ("installs".equals(cmd)) {
18194                dumpState.setDump(DumpState.DUMP_INSTALLS);
18195            } else if ("frozen".equals(cmd)) {
18196                dumpState.setDump(DumpState.DUMP_FROZEN);
18197            } else if ("dexopt".equals(cmd)) {
18198                dumpState.setDump(DumpState.DUMP_DEXOPT);
18199            } else if ("write".equals(cmd)) {
18200                synchronized (mPackages) {
18201                    mSettings.writeLPr();
18202                    pw.println("Settings written.");
18203                    return;
18204                }
18205            }
18206        }
18207
18208        if (checkin) {
18209            pw.println("vers,1");
18210        }
18211
18212        // reader
18213        synchronized (mPackages) {
18214            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18215                if (!checkin) {
18216                    if (dumpState.onTitlePrinted())
18217                        pw.println();
18218                    pw.println("Database versions:");
18219                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18220                }
18221            }
18222
18223            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18224                if (!checkin) {
18225                    if (dumpState.onTitlePrinted())
18226                        pw.println();
18227                    pw.println("Verifiers:");
18228                    pw.print("  Required: ");
18229                    pw.print(mRequiredVerifierPackage);
18230                    pw.print(" (uid=");
18231                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18232                            UserHandle.USER_SYSTEM));
18233                    pw.println(")");
18234                } else if (mRequiredVerifierPackage != null) {
18235                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18236                    pw.print(",");
18237                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18238                            UserHandle.USER_SYSTEM));
18239                }
18240            }
18241
18242            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18243                    packageName == null) {
18244                if (mIntentFilterVerifierComponent != null) {
18245                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18246                    if (!checkin) {
18247                        if (dumpState.onTitlePrinted())
18248                            pw.println();
18249                        pw.println("Intent Filter Verifier:");
18250                        pw.print("  Using: ");
18251                        pw.print(verifierPackageName);
18252                        pw.print(" (uid=");
18253                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18254                                UserHandle.USER_SYSTEM));
18255                        pw.println(")");
18256                    } else if (verifierPackageName != null) {
18257                        pw.print("ifv,"); pw.print(verifierPackageName);
18258                        pw.print(",");
18259                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18260                                UserHandle.USER_SYSTEM));
18261                    }
18262                } else {
18263                    pw.println();
18264                    pw.println("No Intent Filter Verifier available!");
18265                }
18266            }
18267
18268            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18269                boolean printedHeader = false;
18270                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18271                while (it.hasNext()) {
18272                    String name = it.next();
18273                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18274                    if (!checkin) {
18275                        if (!printedHeader) {
18276                            if (dumpState.onTitlePrinted())
18277                                pw.println();
18278                            pw.println("Libraries:");
18279                            printedHeader = true;
18280                        }
18281                        pw.print("  ");
18282                    } else {
18283                        pw.print("lib,");
18284                    }
18285                    pw.print(name);
18286                    if (!checkin) {
18287                        pw.print(" -> ");
18288                    }
18289                    if (ent.path != null) {
18290                        if (!checkin) {
18291                            pw.print("(jar) ");
18292                            pw.print(ent.path);
18293                        } else {
18294                            pw.print(",jar,");
18295                            pw.print(ent.path);
18296                        }
18297                    } else {
18298                        if (!checkin) {
18299                            pw.print("(apk) ");
18300                            pw.print(ent.apk);
18301                        } else {
18302                            pw.print(",apk,");
18303                            pw.print(ent.apk);
18304                        }
18305                    }
18306                    pw.println();
18307                }
18308            }
18309
18310            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18311                if (dumpState.onTitlePrinted())
18312                    pw.println();
18313                if (!checkin) {
18314                    pw.println("Features:");
18315                }
18316
18317                for (FeatureInfo feat : mAvailableFeatures.values()) {
18318                    if (checkin) {
18319                        pw.print("feat,");
18320                        pw.print(feat.name);
18321                        pw.print(",");
18322                        pw.println(feat.version);
18323                    } else {
18324                        pw.print("  ");
18325                        pw.print(feat.name);
18326                        if (feat.version > 0) {
18327                            pw.print(" version=");
18328                            pw.print(feat.version);
18329                        }
18330                        pw.println();
18331                    }
18332                }
18333            }
18334
18335            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18336                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18337                        : "Activity Resolver Table:", "  ", packageName,
18338                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18339                    dumpState.setTitlePrinted(true);
18340                }
18341            }
18342            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18343                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18344                        : "Receiver Resolver Table:", "  ", packageName,
18345                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18346                    dumpState.setTitlePrinted(true);
18347                }
18348            }
18349            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18350                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18351                        : "Service Resolver Table:", "  ", packageName,
18352                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18353                    dumpState.setTitlePrinted(true);
18354                }
18355            }
18356            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18357                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18358                        : "Provider Resolver Table:", "  ", packageName,
18359                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18360                    dumpState.setTitlePrinted(true);
18361                }
18362            }
18363
18364            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18365                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18366                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18367                    int user = mSettings.mPreferredActivities.keyAt(i);
18368                    if (pir.dump(pw,
18369                            dumpState.getTitlePrinted()
18370                                ? "\nPreferred Activities User " + user + ":"
18371                                : "Preferred Activities User " + user + ":", "  ",
18372                            packageName, true, false)) {
18373                        dumpState.setTitlePrinted(true);
18374                    }
18375                }
18376            }
18377
18378            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18379                pw.flush();
18380                FileOutputStream fout = new FileOutputStream(fd);
18381                BufferedOutputStream str = new BufferedOutputStream(fout);
18382                XmlSerializer serializer = new FastXmlSerializer();
18383                try {
18384                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18385                    serializer.startDocument(null, true);
18386                    serializer.setFeature(
18387                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18388                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18389                    serializer.endDocument();
18390                    serializer.flush();
18391                } catch (IllegalArgumentException e) {
18392                    pw.println("Failed writing: " + e);
18393                } catch (IllegalStateException e) {
18394                    pw.println("Failed writing: " + e);
18395                } catch (IOException e) {
18396                    pw.println("Failed writing: " + e);
18397                }
18398            }
18399
18400            if (!checkin
18401                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18402                    && packageName == null) {
18403                pw.println();
18404                int count = mSettings.mPackages.size();
18405                if (count == 0) {
18406                    pw.println("No applications!");
18407                    pw.println();
18408                } else {
18409                    final String prefix = "  ";
18410                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18411                    if (allPackageSettings.size() == 0) {
18412                        pw.println("No domain preferred apps!");
18413                        pw.println();
18414                    } else {
18415                        pw.println("App verification status:");
18416                        pw.println();
18417                        count = 0;
18418                        for (PackageSetting ps : allPackageSettings) {
18419                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18420                            if (ivi == null || ivi.getPackageName() == null) continue;
18421                            pw.println(prefix + "Package: " + ivi.getPackageName());
18422                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18423                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18424                            pw.println();
18425                            count++;
18426                        }
18427                        if (count == 0) {
18428                            pw.println(prefix + "No app verification established.");
18429                            pw.println();
18430                        }
18431                        for (int userId : sUserManager.getUserIds()) {
18432                            pw.println("App linkages for user " + userId + ":");
18433                            pw.println();
18434                            count = 0;
18435                            for (PackageSetting ps : allPackageSettings) {
18436                                final long status = ps.getDomainVerificationStatusForUser(userId);
18437                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18438                                    continue;
18439                                }
18440                                pw.println(prefix + "Package: " + ps.name);
18441                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18442                                String statusStr = IntentFilterVerificationInfo.
18443                                        getStatusStringFromValue(status);
18444                                pw.println(prefix + "Status:  " + statusStr);
18445                                pw.println();
18446                                count++;
18447                            }
18448                            if (count == 0) {
18449                                pw.println(prefix + "No configured app linkages.");
18450                                pw.println();
18451                            }
18452                        }
18453                    }
18454                }
18455            }
18456
18457            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18458                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18459                if (packageName == null && permissionNames == null) {
18460                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18461                        if (iperm == 0) {
18462                            if (dumpState.onTitlePrinted())
18463                                pw.println();
18464                            pw.println("AppOp Permissions:");
18465                        }
18466                        pw.print("  AppOp Permission ");
18467                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18468                        pw.println(":");
18469                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18470                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18471                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18472                        }
18473                    }
18474                }
18475            }
18476
18477            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18478                boolean printedSomething = false;
18479                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18480                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18481                        continue;
18482                    }
18483                    if (!printedSomething) {
18484                        if (dumpState.onTitlePrinted())
18485                            pw.println();
18486                        pw.println("Registered ContentProviders:");
18487                        printedSomething = true;
18488                    }
18489                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18490                    pw.print("    "); pw.println(p.toString());
18491                }
18492                printedSomething = false;
18493                for (Map.Entry<String, PackageParser.Provider> entry :
18494                        mProvidersByAuthority.entrySet()) {
18495                    PackageParser.Provider p = entry.getValue();
18496                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18497                        continue;
18498                    }
18499                    if (!printedSomething) {
18500                        if (dumpState.onTitlePrinted())
18501                            pw.println();
18502                        pw.println("ContentProvider Authorities:");
18503                        printedSomething = true;
18504                    }
18505                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18506                    pw.print("    "); pw.println(p.toString());
18507                    if (p.info != null && p.info.applicationInfo != null) {
18508                        final String appInfo = p.info.applicationInfo.toString();
18509                        pw.print("      applicationInfo="); pw.println(appInfo);
18510                    }
18511                }
18512            }
18513
18514            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18515                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18516            }
18517
18518            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18519                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18520            }
18521
18522            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18523                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18524            }
18525
18526            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18527                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18528            }
18529
18530            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18531                // XXX should handle packageName != null by dumping only install data that
18532                // the given package is involved with.
18533                if (dumpState.onTitlePrinted()) pw.println();
18534                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18535            }
18536
18537            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18538                // XXX should handle packageName != null by dumping only install data that
18539                // the given package is involved with.
18540                if (dumpState.onTitlePrinted()) pw.println();
18541
18542                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18543                ipw.println();
18544                ipw.println("Frozen packages:");
18545                ipw.increaseIndent();
18546                if (mFrozenPackages.size() == 0) {
18547                    ipw.println("(none)");
18548                } else {
18549                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18550                        ipw.println(mFrozenPackages.valueAt(i));
18551                    }
18552                }
18553                ipw.decreaseIndent();
18554            }
18555
18556            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18557                if (dumpState.onTitlePrinted()) pw.println();
18558                dumpDexoptStateLPr(pw, packageName);
18559            }
18560
18561            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18562                if (dumpState.onTitlePrinted()) pw.println();
18563                mSettings.dumpReadMessagesLPr(pw, dumpState);
18564
18565                pw.println();
18566                pw.println("Package warning messages:");
18567                BufferedReader in = null;
18568                String line = null;
18569                try {
18570                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18571                    while ((line = in.readLine()) != null) {
18572                        if (line.contains("ignored: updated version")) continue;
18573                        pw.println(line);
18574                    }
18575                } catch (IOException ignored) {
18576                } finally {
18577                    IoUtils.closeQuietly(in);
18578                }
18579            }
18580
18581            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18582                BufferedReader in = null;
18583                String line = null;
18584                try {
18585                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18586                    while ((line = in.readLine()) != null) {
18587                        if (line.contains("ignored: updated version")) continue;
18588                        pw.print("msg,");
18589                        pw.println(line);
18590                    }
18591                } catch (IOException ignored) {
18592                } finally {
18593                    IoUtils.closeQuietly(in);
18594                }
18595            }
18596        }
18597    }
18598
18599    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18600        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18601        ipw.println();
18602        ipw.println("Dexopt state:");
18603        ipw.increaseIndent();
18604        Collection<PackageParser.Package> packages = null;
18605        if (packageName != null) {
18606            PackageParser.Package targetPackage = mPackages.get(packageName);
18607            if (targetPackage != null) {
18608                packages = Collections.singletonList(targetPackage);
18609            } else {
18610                ipw.println("Unable to find package: " + packageName);
18611                return;
18612            }
18613        } else {
18614            packages = mPackages.values();
18615        }
18616
18617        for (PackageParser.Package pkg : packages) {
18618            ipw.println("[" + pkg.packageName + "]");
18619            ipw.increaseIndent();
18620            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18621            ipw.decreaseIndent();
18622        }
18623    }
18624
18625    private String dumpDomainString(String packageName) {
18626        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18627                .getList();
18628        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18629
18630        ArraySet<String> result = new ArraySet<>();
18631        if (iviList.size() > 0) {
18632            for (IntentFilterVerificationInfo ivi : iviList) {
18633                for (String host : ivi.getDomains()) {
18634                    result.add(host);
18635                }
18636            }
18637        }
18638        if (filters != null && filters.size() > 0) {
18639            for (IntentFilter filter : filters) {
18640                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18641                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18642                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18643                    result.addAll(filter.getHostsList());
18644                }
18645            }
18646        }
18647
18648        StringBuilder sb = new StringBuilder(result.size() * 16);
18649        for (String domain : result) {
18650            if (sb.length() > 0) sb.append(" ");
18651            sb.append(domain);
18652        }
18653        return sb.toString();
18654    }
18655
18656    // ------- apps on sdcard specific code -------
18657    static final boolean DEBUG_SD_INSTALL = false;
18658
18659    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18660
18661    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18662
18663    private boolean mMediaMounted = false;
18664
18665    static String getEncryptKey() {
18666        try {
18667            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18668                    SD_ENCRYPTION_KEYSTORE_NAME);
18669            if (sdEncKey == null) {
18670                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18671                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18672                if (sdEncKey == null) {
18673                    Slog.e(TAG, "Failed to create encryption keys");
18674                    return null;
18675                }
18676            }
18677            return sdEncKey;
18678        } catch (NoSuchAlgorithmException nsae) {
18679            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18680            return null;
18681        } catch (IOException ioe) {
18682            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18683            return null;
18684        }
18685    }
18686
18687    /*
18688     * Update media status on PackageManager.
18689     */
18690    @Override
18691    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18692        int callingUid = Binder.getCallingUid();
18693        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18694            throw new SecurityException("Media status can only be updated by the system");
18695        }
18696        // reader; this apparently protects mMediaMounted, but should probably
18697        // be a different lock in that case.
18698        synchronized (mPackages) {
18699            Log.i(TAG, "Updating external media status from "
18700                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18701                    + (mediaStatus ? "mounted" : "unmounted"));
18702            if (DEBUG_SD_INSTALL)
18703                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18704                        + ", mMediaMounted=" + mMediaMounted);
18705            if (mediaStatus == mMediaMounted) {
18706                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18707                        : 0, -1);
18708                mHandler.sendMessage(msg);
18709                return;
18710            }
18711            mMediaMounted = mediaStatus;
18712        }
18713        // Queue up an async operation since the package installation may take a
18714        // little while.
18715        mHandler.post(new Runnable() {
18716            public void run() {
18717                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18718            }
18719        });
18720    }
18721
18722    /**
18723     * Called by MountService when the initial ASECs to scan are available.
18724     * Should block until all the ASEC containers are finished being scanned.
18725     */
18726    public void scanAvailableAsecs() {
18727        updateExternalMediaStatusInner(true, false, false);
18728    }
18729
18730    /*
18731     * Collect information of applications on external media, map them against
18732     * existing containers and update information based on current mount status.
18733     * Please note that we always have to report status if reportStatus has been
18734     * set to true especially when unloading packages.
18735     */
18736    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18737            boolean externalStorage) {
18738        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18739        int[] uidArr = EmptyArray.INT;
18740
18741        final String[] list = PackageHelper.getSecureContainerList();
18742        if (ArrayUtils.isEmpty(list)) {
18743            Log.i(TAG, "No secure containers found");
18744        } else {
18745            // Process list of secure containers and categorize them
18746            // as active or stale based on their package internal state.
18747
18748            // reader
18749            synchronized (mPackages) {
18750                for (String cid : list) {
18751                    // Leave stages untouched for now; installer service owns them
18752                    if (PackageInstallerService.isStageName(cid)) continue;
18753
18754                    if (DEBUG_SD_INSTALL)
18755                        Log.i(TAG, "Processing container " + cid);
18756                    String pkgName = getAsecPackageName(cid);
18757                    if (pkgName == null) {
18758                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18759                        continue;
18760                    }
18761                    if (DEBUG_SD_INSTALL)
18762                        Log.i(TAG, "Looking for pkg : " + pkgName);
18763
18764                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18765                    if (ps == null) {
18766                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18767                        continue;
18768                    }
18769
18770                    /*
18771                     * Skip packages that are not external if we're unmounting
18772                     * external storage.
18773                     */
18774                    if (externalStorage && !isMounted && !isExternal(ps)) {
18775                        continue;
18776                    }
18777
18778                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18779                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18780                    // The package status is changed only if the code path
18781                    // matches between settings and the container id.
18782                    if (ps.codePathString != null
18783                            && ps.codePathString.startsWith(args.getCodePath())) {
18784                        if (DEBUG_SD_INSTALL) {
18785                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18786                                    + " at code path: " + ps.codePathString);
18787                        }
18788
18789                        // We do have a valid package installed on sdcard
18790                        processCids.put(args, ps.codePathString);
18791                        final int uid = ps.appId;
18792                        if (uid != -1) {
18793                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18794                        }
18795                    } else {
18796                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18797                                + ps.codePathString);
18798                    }
18799                }
18800            }
18801
18802            Arrays.sort(uidArr);
18803        }
18804
18805        // Process packages with valid entries.
18806        if (isMounted) {
18807            if (DEBUG_SD_INSTALL)
18808                Log.i(TAG, "Loading packages");
18809            loadMediaPackages(processCids, uidArr, externalStorage);
18810            startCleaningPackages();
18811            mInstallerService.onSecureContainersAvailable();
18812        } else {
18813            if (DEBUG_SD_INSTALL)
18814                Log.i(TAG, "Unloading packages");
18815            unloadMediaPackages(processCids, uidArr, reportStatus);
18816        }
18817    }
18818
18819    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18820            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18821        final int size = infos.size();
18822        final String[] packageNames = new String[size];
18823        final int[] packageUids = new int[size];
18824        for (int i = 0; i < size; i++) {
18825            final ApplicationInfo info = infos.get(i);
18826            packageNames[i] = info.packageName;
18827            packageUids[i] = info.uid;
18828        }
18829        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18830                finishedReceiver);
18831    }
18832
18833    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18834            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18835        sendResourcesChangedBroadcast(mediaStatus, replacing,
18836                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18837    }
18838
18839    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18840            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18841        int size = pkgList.length;
18842        if (size > 0) {
18843            // Send broadcasts here
18844            Bundle extras = new Bundle();
18845            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18846            if (uidArr != null) {
18847                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18848            }
18849            if (replacing) {
18850                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18851            }
18852            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18853                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18854            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18855        }
18856    }
18857
18858   /*
18859     * Look at potentially valid container ids from processCids If package
18860     * information doesn't match the one on record or package scanning fails,
18861     * the cid is added to list of removeCids. We currently don't delete stale
18862     * containers.
18863     */
18864    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18865            boolean externalStorage) {
18866        ArrayList<String> pkgList = new ArrayList<String>();
18867        Set<AsecInstallArgs> keys = processCids.keySet();
18868
18869        for (AsecInstallArgs args : keys) {
18870            String codePath = processCids.get(args);
18871            if (DEBUG_SD_INSTALL)
18872                Log.i(TAG, "Loading container : " + args.cid);
18873            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18874            try {
18875                // Make sure there are no container errors first.
18876                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18877                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18878                            + " when installing from sdcard");
18879                    continue;
18880                }
18881                // Check code path here.
18882                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18883                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18884                            + " does not match one in settings " + codePath);
18885                    continue;
18886                }
18887                // Parse package
18888                int parseFlags = mDefParseFlags;
18889                if (args.isExternalAsec()) {
18890                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18891                }
18892                if (args.isFwdLocked()) {
18893                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18894                }
18895
18896                synchronized (mInstallLock) {
18897                    PackageParser.Package pkg = null;
18898                    try {
18899                        // Sadly we don't know the package name yet to freeze it
18900                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18901                                SCAN_IGNORE_FROZEN, 0, null);
18902                    } catch (PackageManagerException e) {
18903                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18904                    }
18905                    // Scan the package
18906                    if (pkg != null) {
18907                        /*
18908                         * TODO why is the lock being held? doPostInstall is
18909                         * called in other places without the lock. This needs
18910                         * to be straightened out.
18911                         */
18912                        // writer
18913                        synchronized (mPackages) {
18914                            retCode = PackageManager.INSTALL_SUCCEEDED;
18915                            pkgList.add(pkg.packageName);
18916                            // Post process args
18917                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18918                                    pkg.applicationInfo.uid);
18919                        }
18920                    } else {
18921                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18922                    }
18923                }
18924
18925            } finally {
18926                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18927                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18928                }
18929            }
18930        }
18931        // writer
18932        synchronized (mPackages) {
18933            // If the platform SDK has changed since the last time we booted,
18934            // we need to re-grant app permission to catch any new ones that
18935            // appear. This is really a hack, and means that apps can in some
18936            // cases get permissions that the user didn't initially explicitly
18937            // allow... it would be nice to have some better way to handle
18938            // this situation.
18939            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18940                    : mSettings.getInternalVersion();
18941            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18942                    : StorageManager.UUID_PRIVATE_INTERNAL;
18943
18944            int updateFlags = UPDATE_PERMISSIONS_ALL;
18945            if (ver.sdkVersion != mSdkVersion) {
18946                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18947                        + mSdkVersion + "; regranting permissions for external");
18948                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18949            }
18950            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18951
18952            // Yay, everything is now upgraded
18953            ver.forceCurrent();
18954
18955            // can downgrade to reader
18956            // Persist settings
18957            mSettings.writeLPr();
18958        }
18959        // Send a broadcast to let everyone know we are done processing
18960        if (pkgList.size() > 0) {
18961            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18962        }
18963    }
18964
18965   /*
18966     * Utility method to unload a list of specified containers
18967     */
18968    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18969        // Just unmount all valid containers.
18970        for (AsecInstallArgs arg : cidArgs) {
18971            synchronized (mInstallLock) {
18972                arg.doPostDeleteLI(false);
18973           }
18974       }
18975   }
18976
18977    /*
18978     * Unload packages mounted on external media. This involves deleting package
18979     * data from internal structures, sending broadcasts about disabled packages,
18980     * gc'ing to free up references, unmounting all secure containers
18981     * corresponding to packages on external media, and posting a
18982     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18983     * that we always have to post this message if status has been requested no
18984     * matter what.
18985     */
18986    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18987            final boolean reportStatus) {
18988        if (DEBUG_SD_INSTALL)
18989            Log.i(TAG, "unloading media packages");
18990        ArrayList<String> pkgList = new ArrayList<String>();
18991        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18992        final Set<AsecInstallArgs> keys = processCids.keySet();
18993        for (AsecInstallArgs args : keys) {
18994            String pkgName = args.getPackageName();
18995            if (DEBUG_SD_INSTALL)
18996                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18997            // Delete package internally
18998            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18999            synchronized (mInstallLock) {
19000                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19001                final boolean res;
19002                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19003                        "unloadMediaPackages")) {
19004                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19005                            null);
19006                }
19007                if (res) {
19008                    pkgList.add(pkgName);
19009                } else {
19010                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19011                    failedList.add(args);
19012                }
19013            }
19014        }
19015
19016        // reader
19017        synchronized (mPackages) {
19018            // We didn't update the settings after removing each package;
19019            // write them now for all packages.
19020            mSettings.writeLPr();
19021        }
19022
19023        // We have to absolutely send UPDATED_MEDIA_STATUS only
19024        // after confirming that all the receivers processed the ordered
19025        // broadcast when packages get disabled, force a gc to clean things up.
19026        // and unload all the containers.
19027        if (pkgList.size() > 0) {
19028            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19029                    new IIntentReceiver.Stub() {
19030                public void performReceive(Intent intent, int resultCode, String data,
19031                        Bundle extras, boolean ordered, boolean sticky,
19032                        int sendingUser) throws RemoteException {
19033                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19034                            reportStatus ? 1 : 0, 1, keys);
19035                    mHandler.sendMessage(msg);
19036                }
19037            });
19038        } else {
19039            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19040                    keys);
19041            mHandler.sendMessage(msg);
19042        }
19043    }
19044
19045    private void loadPrivatePackages(final VolumeInfo vol) {
19046        mHandler.post(new Runnable() {
19047            @Override
19048            public void run() {
19049                loadPrivatePackagesInner(vol);
19050            }
19051        });
19052    }
19053
19054    private void loadPrivatePackagesInner(VolumeInfo vol) {
19055        final String volumeUuid = vol.fsUuid;
19056        if (TextUtils.isEmpty(volumeUuid)) {
19057            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19058            return;
19059        }
19060
19061        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19062        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19063        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19064
19065        final VersionInfo ver;
19066        final List<PackageSetting> packages;
19067        synchronized (mPackages) {
19068            ver = mSettings.findOrCreateVersion(volumeUuid);
19069            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19070        }
19071
19072        for (PackageSetting ps : packages) {
19073            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19074            synchronized (mInstallLock) {
19075                final PackageParser.Package pkg;
19076                try {
19077                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19078                    loaded.add(pkg.applicationInfo);
19079
19080                } catch (PackageManagerException e) {
19081                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19082                }
19083
19084                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19085                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19086                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19087                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19088                }
19089            }
19090        }
19091
19092        // Reconcile app data for all started/unlocked users
19093        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19094        final UserManager um = mContext.getSystemService(UserManager.class);
19095        UserManagerInternal umInternal = getUserManagerInternal();
19096        for (UserInfo user : um.getUsers()) {
19097            final int flags;
19098            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19099                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19100            } else if (umInternal.isUserRunning(user.id)) {
19101                flags = StorageManager.FLAG_STORAGE_DE;
19102            } else {
19103                continue;
19104            }
19105
19106            try {
19107                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19108                synchronized (mInstallLock) {
19109                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19110                }
19111            } catch (IllegalStateException e) {
19112                // Device was probably ejected, and we'll process that event momentarily
19113                Slog.w(TAG, "Failed to prepare storage: " + e);
19114            }
19115        }
19116
19117        synchronized (mPackages) {
19118            int updateFlags = UPDATE_PERMISSIONS_ALL;
19119            if (ver.sdkVersion != mSdkVersion) {
19120                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19121                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19122                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19123            }
19124            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19125
19126            // Yay, everything is now upgraded
19127            ver.forceCurrent();
19128
19129            mSettings.writeLPr();
19130        }
19131
19132        for (PackageFreezer freezer : freezers) {
19133            freezer.close();
19134        }
19135
19136        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19137        sendResourcesChangedBroadcast(true, false, loaded, null);
19138    }
19139
19140    private void unloadPrivatePackages(final VolumeInfo vol) {
19141        mHandler.post(new Runnable() {
19142            @Override
19143            public void run() {
19144                unloadPrivatePackagesInner(vol);
19145            }
19146        });
19147    }
19148
19149    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19150        final String volumeUuid = vol.fsUuid;
19151        if (TextUtils.isEmpty(volumeUuid)) {
19152            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19153            return;
19154        }
19155
19156        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19157        synchronized (mInstallLock) {
19158        synchronized (mPackages) {
19159            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19160            for (PackageSetting ps : packages) {
19161                if (ps.pkg == null) continue;
19162
19163                final ApplicationInfo info = ps.pkg.applicationInfo;
19164                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19165                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19166
19167                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19168                        "unloadPrivatePackagesInner")) {
19169                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19170                            false, null)) {
19171                        unloaded.add(info);
19172                    } else {
19173                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19174                    }
19175                }
19176            }
19177
19178            mSettings.writeLPr();
19179        }
19180        }
19181
19182        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19183        sendResourcesChangedBroadcast(false, false, unloaded, null);
19184    }
19185
19186    /**
19187     * Prepare storage areas for given user on all mounted devices.
19188     */
19189    void prepareUserData(int userId, int userSerial, int flags) {
19190        synchronized (mInstallLock) {
19191            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19192            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19193                final String volumeUuid = vol.getFsUuid();
19194                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19195            }
19196        }
19197    }
19198
19199    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19200            boolean allowRecover) {
19201        // Prepare storage and verify that serial numbers are consistent; if
19202        // there's a mismatch we need to destroy to avoid leaking data
19203        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19204        try {
19205            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19206
19207            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19208                UserManagerService.enforceSerialNumber(
19209                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19210            }
19211            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19212                UserManagerService.enforceSerialNumber(
19213                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19214            }
19215
19216            synchronized (mInstallLock) {
19217                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19218            }
19219        } catch (Exception e) {
19220            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19221                    + " because we failed to prepare: " + e);
19222            destroyUserDataLI(volumeUuid, userId,
19223                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19224
19225            if (allowRecover) {
19226                // Try one last time; if we fail again we're really in trouble
19227                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19228            }
19229        }
19230    }
19231
19232    /**
19233     * Destroy storage areas for given user on all mounted devices.
19234     */
19235    void destroyUserData(int userId, int flags) {
19236        synchronized (mInstallLock) {
19237            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19238            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19239                final String volumeUuid = vol.getFsUuid();
19240                destroyUserDataLI(volumeUuid, userId, flags);
19241            }
19242        }
19243    }
19244
19245    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19246        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19247        try {
19248            // Clean up app data, profile data, and media data
19249            mInstaller.destroyUserData(volumeUuid, userId, flags);
19250
19251            // Clean up system data
19252            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19253                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19254                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19255                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19256                }
19257                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19258                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19259                }
19260            }
19261
19262            // Data with special labels is now gone, so finish the job
19263            storage.destroyUserStorage(volumeUuid, userId, flags);
19264
19265        } catch (Exception e) {
19266            logCriticalInfo(Log.WARN,
19267                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19268        }
19269    }
19270
19271    /**
19272     * Examine all users present on given mounted volume, and destroy data
19273     * belonging to users that are no longer valid, or whose user ID has been
19274     * recycled.
19275     */
19276    private void reconcileUsers(String volumeUuid) {
19277        final List<File> files = new ArrayList<>();
19278        Collections.addAll(files, FileUtils
19279                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19280        Collections.addAll(files, FileUtils
19281                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19282        for (File file : files) {
19283            if (!file.isDirectory()) continue;
19284
19285            final int userId;
19286            final UserInfo info;
19287            try {
19288                userId = Integer.parseInt(file.getName());
19289                info = sUserManager.getUserInfo(userId);
19290            } catch (NumberFormatException e) {
19291                Slog.w(TAG, "Invalid user directory " + file);
19292                continue;
19293            }
19294
19295            boolean destroyUser = false;
19296            if (info == null) {
19297                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19298                        + " because no matching user was found");
19299                destroyUser = true;
19300            } else if (!mOnlyCore) {
19301                try {
19302                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19303                } catch (IOException e) {
19304                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19305                            + " because we failed to enforce serial number: " + e);
19306                    destroyUser = true;
19307                }
19308            }
19309
19310            if (destroyUser) {
19311                synchronized (mInstallLock) {
19312                    destroyUserDataLI(volumeUuid, userId,
19313                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19314                }
19315            }
19316        }
19317    }
19318
19319    private void assertPackageKnown(String volumeUuid, String packageName)
19320            throws PackageManagerException {
19321        synchronized (mPackages) {
19322            final PackageSetting ps = mSettings.mPackages.get(packageName);
19323            if (ps == null) {
19324                throw new PackageManagerException("Package " + packageName + " is unknown");
19325            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19326                throw new PackageManagerException(
19327                        "Package " + packageName + " found on unknown volume " + volumeUuid
19328                                + "; expected volume " + ps.volumeUuid);
19329            }
19330        }
19331    }
19332
19333    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19334            throws PackageManagerException {
19335        synchronized (mPackages) {
19336            final PackageSetting ps = mSettings.mPackages.get(packageName);
19337            if (ps == null) {
19338                throw new PackageManagerException("Package " + packageName + " is unknown");
19339            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19340                throw new PackageManagerException(
19341                        "Package " + packageName + " found on unknown volume " + volumeUuid
19342                                + "; expected volume " + ps.volumeUuid);
19343            } else if (!ps.getInstalled(userId)) {
19344                throw new PackageManagerException(
19345                        "Package " + packageName + " not installed for user " + userId);
19346            }
19347        }
19348    }
19349
19350    /**
19351     * Examine all apps present on given mounted volume, and destroy apps that
19352     * aren't expected, either due to uninstallation or reinstallation on
19353     * another volume.
19354     */
19355    private void reconcileApps(String volumeUuid) {
19356        final File[] files = FileUtils
19357                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19358        for (File file : files) {
19359            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19360                    && !PackageInstallerService.isStageName(file.getName());
19361            if (!isPackage) {
19362                // Ignore entries which are not packages
19363                continue;
19364            }
19365
19366            try {
19367                final PackageLite pkg = PackageParser.parsePackageLite(file,
19368                        PackageParser.PARSE_MUST_BE_APK);
19369                assertPackageKnown(volumeUuid, pkg.packageName);
19370
19371            } catch (PackageParserException | PackageManagerException e) {
19372                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19373                synchronized (mInstallLock) {
19374                    removeCodePathLI(file);
19375                }
19376            }
19377        }
19378    }
19379
19380    /**
19381     * Reconcile all app data for the given user.
19382     * <p>
19383     * Verifies that directories exist and that ownership and labeling is
19384     * correct for all installed apps on all mounted volumes.
19385     */
19386    void reconcileAppsData(int userId, int flags) {
19387        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19388        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19389            final String volumeUuid = vol.getFsUuid();
19390            synchronized (mInstallLock) {
19391                reconcileAppsDataLI(volumeUuid, userId, flags);
19392            }
19393        }
19394    }
19395
19396    /**
19397     * Reconcile all app data on given mounted volume.
19398     * <p>
19399     * Destroys app data that isn't expected, either due to uninstallation or
19400     * reinstallation on another volume.
19401     * <p>
19402     * Verifies that directories exist and that ownership and labeling is
19403     * correct for all installed apps.
19404     */
19405    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19406        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19407                + Integer.toHexString(flags));
19408
19409        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19410        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19411
19412        boolean restoreconNeeded = false;
19413
19414        // First look for stale data that doesn't belong, and check if things
19415        // have changed since we did our last restorecon
19416        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19417            if (StorageManager.isFileEncryptedNativeOrEmulated()
19418                    && !StorageManager.isUserKeyUnlocked(userId)) {
19419                throw new RuntimeException(
19420                        "Yikes, someone asked us to reconcile CE storage while " + userId
19421                                + " was still locked; this would have caused massive data loss!");
19422            }
19423
19424            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19425
19426            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19427            for (File file : files) {
19428                final String packageName = file.getName();
19429                try {
19430                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19431                } catch (PackageManagerException e) {
19432                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19433                    try {
19434                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19435                                StorageManager.FLAG_STORAGE_CE, 0);
19436                    } catch (InstallerException e2) {
19437                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19438                    }
19439                }
19440            }
19441        }
19442        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19443            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19444
19445            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19446            for (File file : files) {
19447                final String packageName = file.getName();
19448                try {
19449                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19450                } catch (PackageManagerException e) {
19451                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19452                    try {
19453                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19454                                StorageManager.FLAG_STORAGE_DE, 0);
19455                    } catch (InstallerException e2) {
19456                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19457                    }
19458                }
19459            }
19460        }
19461
19462        // Ensure that data directories are ready to roll for all packages
19463        // installed for this volume and user
19464        final List<PackageSetting> packages;
19465        synchronized (mPackages) {
19466            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19467        }
19468        int preparedCount = 0;
19469        for (PackageSetting ps : packages) {
19470            final String packageName = ps.name;
19471            if (ps.pkg == null) {
19472                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19473                // TODO: might be due to legacy ASEC apps; we should circle back
19474                // and reconcile again once they're scanned
19475                continue;
19476            }
19477
19478            if (ps.getInstalled(userId)) {
19479                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19480
19481                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19482                    // We may have just shuffled around app data directories, so
19483                    // prepare them one more time
19484                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19485                }
19486
19487                preparedCount++;
19488            }
19489        }
19490
19491        if (restoreconNeeded) {
19492            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19493                SELinuxMMAC.setRestoreconDone(ceDir);
19494            }
19495            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19496                SELinuxMMAC.setRestoreconDone(deDir);
19497            }
19498        }
19499
19500        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19501                + " packages; restoreconNeeded was " + restoreconNeeded);
19502    }
19503
19504    /**
19505     * Prepare app data for the given app just after it was installed or
19506     * upgraded. This method carefully only touches users that it's installed
19507     * for, and it forces a restorecon to handle any seinfo changes.
19508     * <p>
19509     * Verifies that directories exist and that ownership and labeling is
19510     * correct for all installed apps. If there is an ownership mismatch, it
19511     * will try recovering system apps by wiping data; third-party app data is
19512     * left intact.
19513     * <p>
19514     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19515     */
19516    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19517        final PackageSetting ps;
19518        synchronized (mPackages) {
19519            ps = mSettings.mPackages.get(pkg.packageName);
19520            mSettings.writeKernelMappingLPr(ps);
19521        }
19522
19523        final UserManager um = mContext.getSystemService(UserManager.class);
19524        UserManagerInternal umInternal = getUserManagerInternal();
19525        for (UserInfo user : um.getUsers()) {
19526            final int flags;
19527            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19528                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19529            } else if (umInternal.isUserRunning(user.id)) {
19530                flags = StorageManager.FLAG_STORAGE_DE;
19531            } else {
19532                continue;
19533            }
19534
19535            if (ps.getInstalled(user.id)) {
19536                // Whenever an app changes, force a restorecon of its data
19537                // TODO: when user data is locked, mark that we're still dirty
19538                prepareAppDataLIF(pkg, user.id, flags, true);
19539            }
19540        }
19541    }
19542
19543    /**
19544     * Prepare app data for the given app.
19545     * <p>
19546     * Verifies that directories exist and that ownership and labeling is
19547     * correct for all installed apps. If there is an ownership mismatch, this
19548     * will try recovering system apps by wiping data; third-party app data is
19549     * left intact.
19550     */
19551    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19552            boolean restoreconNeeded) {
19553        if (pkg == null) {
19554            Slog.wtf(TAG, "Package was null!", new Throwable());
19555            return;
19556        }
19557        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19558        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19559        for (int i = 0; i < childCount; i++) {
19560            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19561        }
19562    }
19563
19564    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19565            boolean restoreconNeeded) {
19566        if (DEBUG_APP_DATA) {
19567            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19568                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19569        }
19570
19571        final String volumeUuid = pkg.volumeUuid;
19572        final String packageName = pkg.packageName;
19573        final ApplicationInfo app = pkg.applicationInfo;
19574        final int appId = UserHandle.getAppId(app.uid);
19575
19576        Preconditions.checkNotNull(app.seinfo);
19577
19578        try {
19579            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19580                    appId, app.seinfo, app.targetSdkVersion);
19581        } catch (InstallerException e) {
19582            if (app.isSystemApp()) {
19583                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19584                        + ", but trying to recover: " + e);
19585                destroyAppDataLeafLIF(pkg, userId, flags);
19586                try {
19587                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19588                            appId, app.seinfo, app.targetSdkVersion);
19589                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19590                } catch (InstallerException e2) {
19591                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19592                }
19593            } else {
19594                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19595            }
19596        }
19597
19598        if (restoreconNeeded) {
19599            try {
19600                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19601                        app.seinfo);
19602            } catch (InstallerException e) {
19603                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19604            }
19605        }
19606
19607        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19608            try {
19609                // CE storage is unlocked right now, so read out the inode and
19610                // remember for use later when it's locked
19611                // TODO: mark this structure as dirty so we persist it!
19612                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19613                        StorageManager.FLAG_STORAGE_CE);
19614                synchronized (mPackages) {
19615                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19616                    if (ps != null) {
19617                        ps.setCeDataInode(ceDataInode, userId);
19618                    }
19619                }
19620            } catch (InstallerException e) {
19621                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19622            }
19623        }
19624
19625        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19626    }
19627
19628    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19629        if (pkg == null) {
19630            Slog.wtf(TAG, "Package was null!", new Throwable());
19631            return;
19632        }
19633        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19634        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19635        for (int i = 0; i < childCount; i++) {
19636            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19637        }
19638    }
19639
19640    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19641        final String volumeUuid = pkg.volumeUuid;
19642        final String packageName = pkg.packageName;
19643        final ApplicationInfo app = pkg.applicationInfo;
19644
19645        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19646            // Create a native library symlink only if we have native libraries
19647            // and if the native libraries are 32 bit libraries. We do not provide
19648            // this symlink for 64 bit libraries.
19649            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19650                final String nativeLibPath = app.nativeLibraryDir;
19651                try {
19652                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19653                            nativeLibPath, userId);
19654                } catch (InstallerException e) {
19655                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19656                }
19657            }
19658        }
19659    }
19660
19661    /**
19662     * For system apps on non-FBE devices, this method migrates any existing
19663     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19664     * requested by the app.
19665     */
19666    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19667        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19668                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19669            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19670                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19671            try {
19672                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19673                        storageTarget);
19674            } catch (InstallerException e) {
19675                logCriticalInfo(Log.WARN,
19676                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19677            }
19678            return true;
19679        } else {
19680            return false;
19681        }
19682    }
19683
19684    public PackageFreezer freezePackage(String packageName, String killReason) {
19685        return new PackageFreezer(packageName, killReason);
19686    }
19687
19688    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19689            String killReason) {
19690        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19691            return new PackageFreezer();
19692        } else {
19693            return freezePackage(packageName, killReason);
19694        }
19695    }
19696
19697    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19698            String killReason) {
19699        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19700            return new PackageFreezer();
19701        } else {
19702            return freezePackage(packageName, killReason);
19703        }
19704    }
19705
19706    /**
19707     * Class that freezes and kills the given package upon creation, and
19708     * unfreezes it upon closing. This is typically used when doing surgery on
19709     * app code/data to prevent the app from running while you're working.
19710     */
19711    private class PackageFreezer implements AutoCloseable {
19712        private final String mPackageName;
19713        private final PackageFreezer[] mChildren;
19714
19715        private final boolean mWeFroze;
19716
19717        private final AtomicBoolean mClosed = new AtomicBoolean();
19718        private final CloseGuard mCloseGuard = CloseGuard.get();
19719
19720        /**
19721         * Create and return a stub freezer that doesn't actually do anything,
19722         * typically used when someone requested
19723         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19724         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19725         */
19726        public PackageFreezer() {
19727            mPackageName = null;
19728            mChildren = null;
19729            mWeFroze = false;
19730            mCloseGuard.open("close");
19731        }
19732
19733        public PackageFreezer(String packageName, String killReason) {
19734            synchronized (mPackages) {
19735                mPackageName = packageName;
19736                mWeFroze = mFrozenPackages.add(mPackageName);
19737
19738                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19739                if (ps != null) {
19740                    killApplication(ps.name, ps.appId, killReason);
19741                }
19742
19743                final PackageParser.Package p = mPackages.get(packageName);
19744                if (p != null && p.childPackages != null) {
19745                    final int N = p.childPackages.size();
19746                    mChildren = new PackageFreezer[N];
19747                    for (int i = 0; i < N; i++) {
19748                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19749                                killReason);
19750                    }
19751                } else {
19752                    mChildren = null;
19753                }
19754            }
19755            mCloseGuard.open("close");
19756        }
19757
19758        @Override
19759        protected void finalize() throws Throwable {
19760            try {
19761                mCloseGuard.warnIfOpen();
19762                close();
19763            } finally {
19764                super.finalize();
19765            }
19766        }
19767
19768        @Override
19769        public void close() {
19770            mCloseGuard.close();
19771            if (mClosed.compareAndSet(false, true)) {
19772                synchronized (mPackages) {
19773                    if (mWeFroze) {
19774                        mFrozenPackages.remove(mPackageName);
19775                    }
19776
19777                    if (mChildren != null) {
19778                        for (PackageFreezer freezer : mChildren) {
19779                            freezer.close();
19780                        }
19781                    }
19782                }
19783            }
19784        }
19785    }
19786
19787    /**
19788     * Verify that given package is currently frozen.
19789     */
19790    private void checkPackageFrozen(String packageName) {
19791        synchronized (mPackages) {
19792            if (!mFrozenPackages.contains(packageName)) {
19793                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19794            }
19795        }
19796    }
19797
19798    @Override
19799    public int movePackage(final String packageName, final String volumeUuid) {
19800        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19801
19802        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19803        final int moveId = mNextMoveId.getAndIncrement();
19804        mHandler.post(new Runnable() {
19805            @Override
19806            public void run() {
19807                try {
19808                    movePackageInternal(packageName, volumeUuid, moveId, user);
19809                } catch (PackageManagerException e) {
19810                    Slog.w(TAG, "Failed to move " + packageName, e);
19811                    mMoveCallbacks.notifyStatusChanged(moveId,
19812                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19813                }
19814            }
19815        });
19816        return moveId;
19817    }
19818
19819    private void movePackageInternal(final String packageName, final String volumeUuid,
19820            final int moveId, UserHandle user) throws PackageManagerException {
19821        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19822        final PackageManager pm = mContext.getPackageManager();
19823
19824        final boolean currentAsec;
19825        final String currentVolumeUuid;
19826        final File codeFile;
19827        final String installerPackageName;
19828        final String packageAbiOverride;
19829        final int appId;
19830        final String seinfo;
19831        final String label;
19832        final int targetSdkVersion;
19833        final PackageFreezer freezer;
19834        final int[] installedUserIds;
19835
19836        // reader
19837        synchronized (mPackages) {
19838            final PackageParser.Package pkg = mPackages.get(packageName);
19839            final PackageSetting ps = mSettings.mPackages.get(packageName);
19840            if (pkg == null || ps == null) {
19841                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19842            }
19843
19844            if (pkg.applicationInfo.isSystemApp()) {
19845                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19846                        "Cannot move system application");
19847            }
19848
19849            if (pkg.applicationInfo.isExternalAsec()) {
19850                currentAsec = true;
19851                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19852            } else if (pkg.applicationInfo.isForwardLocked()) {
19853                currentAsec = true;
19854                currentVolumeUuid = "forward_locked";
19855            } else {
19856                currentAsec = false;
19857                currentVolumeUuid = ps.volumeUuid;
19858
19859                final File probe = new File(pkg.codePath);
19860                final File probeOat = new File(probe, "oat");
19861                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19862                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19863                            "Move only supported for modern cluster style installs");
19864                }
19865            }
19866
19867            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19868                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19869                        "Package already moved to " + volumeUuid);
19870            }
19871            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19872                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19873                        "Device admin cannot be moved");
19874            }
19875
19876            if (mFrozenPackages.contains(packageName)) {
19877                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19878                        "Failed to move already frozen package");
19879            }
19880
19881            codeFile = new File(pkg.codePath);
19882            installerPackageName = ps.installerPackageName;
19883            packageAbiOverride = ps.cpuAbiOverrideString;
19884            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19885            seinfo = pkg.applicationInfo.seinfo;
19886            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19887            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19888            freezer = new PackageFreezer(packageName, "movePackageInternal");
19889            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19890        }
19891
19892        final Bundle extras = new Bundle();
19893        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19894        extras.putString(Intent.EXTRA_TITLE, label);
19895        mMoveCallbacks.notifyCreated(moveId, extras);
19896
19897        int installFlags;
19898        final boolean moveCompleteApp;
19899        final File measurePath;
19900
19901        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19902            installFlags = INSTALL_INTERNAL;
19903            moveCompleteApp = !currentAsec;
19904            measurePath = Environment.getDataAppDirectory(volumeUuid);
19905        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19906            installFlags = INSTALL_EXTERNAL;
19907            moveCompleteApp = false;
19908            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19909        } else {
19910            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19911            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19912                    || !volume.isMountedWritable()) {
19913                freezer.close();
19914                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19915                        "Move location not mounted private volume");
19916            }
19917
19918            Preconditions.checkState(!currentAsec);
19919
19920            installFlags = INSTALL_INTERNAL;
19921            moveCompleteApp = true;
19922            measurePath = Environment.getDataAppDirectory(volumeUuid);
19923        }
19924
19925        final PackageStats stats = new PackageStats(null, -1);
19926        synchronized (mInstaller) {
19927            for (int userId : installedUserIds) {
19928                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
19929                    freezer.close();
19930                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19931                            "Failed to measure package size");
19932                }
19933            }
19934        }
19935
19936        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19937                + stats.dataSize);
19938
19939        final long startFreeBytes = measurePath.getFreeSpace();
19940        final long sizeBytes;
19941        if (moveCompleteApp) {
19942            sizeBytes = stats.codeSize + stats.dataSize;
19943        } else {
19944            sizeBytes = stats.codeSize;
19945        }
19946
19947        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19948            freezer.close();
19949            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19950                    "Not enough free space to move");
19951        }
19952
19953        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19954
19955        final CountDownLatch installedLatch = new CountDownLatch(1);
19956        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19957            @Override
19958            public void onUserActionRequired(Intent intent) throws RemoteException {
19959                throw new IllegalStateException();
19960            }
19961
19962            @Override
19963            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19964                    Bundle extras) throws RemoteException {
19965                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19966                        + PackageManager.installStatusToString(returnCode, msg));
19967
19968                installedLatch.countDown();
19969                freezer.close();
19970
19971                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19972                switch (status) {
19973                    case PackageInstaller.STATUS_SUCCESS:
19974                        mMoveCallbacks.notifyStatusChanged(moveId,
19975                                PackageManager.MOVE_SUCCEEDED);
19976                        break;
19977                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19978                        mMoveCallbacks.notifyStatusChanged(moveId,
19979                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19980                        break;
19981                    default:
19982                        mMoveCallbacks.notifyStatusChanged(moveId,
19983                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19984                        break;
19985                }
19986            }
19987        };
19988
19989        final MoveInfo move;
19990        if (moveCompleteApp) {
19991            // Kick off a thread to report progress estimates
19992            new Thread() {
19993                @Override
19994                public void run() {
19995                    while (true) {
19996                        try {
19997                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19998                                break;
19999                            }
20000                        } catch (InterruptedException ignored) {
20001                        }
20002
20003                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20004                        final int progress = 10 + (int) MathUtils.constrain(
20005                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20006                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20007                    }
20008                }
20009            }.start();
20010
20011            final String dataAppName = codeFile.getName();
20012            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20013                    dataAppName, appId, seinfo, targetSdkVersion);
20014        } else {
20015            move = null;
20016        }
20017
20018        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20019
20020        final Message msg = mHandler.obtainMessage(INIT_COPY);
20021        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20022        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20023                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20024                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20025        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20026        msg.obj = params;
20027
20028        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20029                System.identityHashCode(msg.obj));
20030        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20031                System.identityHashCode(msg.obj));
20032
20033        mHandler.sendMessage(msg);
20034    }
20035
20036    @Override
20037    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20038        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20039
20040        final int realMoveId = mNextMoveId.getAndIncrement();
20041        final Bundle extras = new Bundle();
20042        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20043        mMoveCallbacks.notifyCreated(realMoveId, extras);
20044
20045        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20046            @Override
20047            public void onCreated(int moveId, Bundle extras) {
20048                // Ignored
20049            }
20050
20051            @Override
20052            public void onStatusChanged(int moveId, int status, long estMillis) {
20053                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20054            }
20055        };
20056
20057        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20058        storage.setPrimaryStorageUuid(volumeUuid, callback);
20059        return realMoveId;
20060    }
20061
20062    @Override
20063    public int getMoveStatus(int moveId) {
20064        mContext.enforceCallingOrSelfPermission(
20065                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20066        return mMoveCallbacks.mLastStatus.get(moveId);
20067    }
20068
20069    @Override
20070    public void registerMoveCallback(IPackageMoveObserver callback) {
20071        mContext.enforceCallingOrSelfPermission(
20072                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20073        mMoveCallbacks.register(callback);
20074    }
20075
20076    @Override
20077    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20078        mContext.enforceCallingOrSelfPermission(
20079                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20080        mMoveCallbacks.unregister(callback);
20081    }
20082
20083    @Override
20084    public boolean setInstallLocation(int loc) {
20085        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20086                null);
20087        if (getInstallLocation() == loc) {
20088            return true;
20089        }
20090        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20091                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20092            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20093                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20094            return true;
20095        }
20096        return false;
20097   }
20098
20099    @Override
20100    public int getInstallLocation() {
20101        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20102                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20103                PackageHelper.APP_INSTALL_AUTO);
20104    }
20105
20106    /** Called by UserManagerService */
20107    void cleanUpUser(UserManagerService userManager, int userHandle) {
20108        synchronized (mPackages) {
20109            mDirtyUsers.remove(userHandle);
20110            mUserNeedsBadging.delete(userHandle);
20111            mSettings.removeUserLPw(userHandle);
20112            mPendingBroadcasts.remove(userHandle);
20113            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20114            removeUnusedPackagesLPw(userManager, userHandle);
20115        }
20116    }
20117
20118    /**
20119     * We're removing userHandle and would like to remove any downloaded packages
20120     * that are no longer in use by any other user.
20121     * @param userHandle the user being removed
20122     */
20123    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20124        final boolean DEBUG_CLEAN_APKS = false;
20125        int [] users = userManager.getUserIds();
20126        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20127        while (psit.hasNext()) {
20128            PackageSetting ps = psit.next();
20129            if (ps.pkg == null) {
20130                continue;
20131            }
20132            final String packageName = ps.pkg.packageName;
20133            // Skip over if system app
20134            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20135                continue;
20136            }
20137            if (DEBUG_CLEAN_APKS) {
20138                Slog.i(TAG, "Checking package " + packageName);
20139            }
20140            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20141            if (keep) {
20142                if (DEBUG_CLEAN_APKS) {
20143                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20144                }
20145            } else {
20146                for (int i = 0; i < users.length; i++) {
20147                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20148                        keep = true;
20149                        if (DEBUG_CLEAN_APKS) {
20150                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20151                                    + users[i]);
20152                        }
20153                        break;
20154                    }
20155                }
20156            }
20157            if (!keep) {
20158                if (DEBUG_CLEAN_APKS) {
20159                    Slog.i(TAG, "  Removing package " + packageName);
20160                }
20161                mHandler.post(new Runnable() {
20162                    public void run() {
20163                        deletePackageX(packageName, userHandle, 0);
20164                    } //end run
20165                });
20166            }
20167        }
20168    }
20169
20170    /** Called by UserManagerService */
20171    void createNewUser(int userId) {
20172        synchronized (mInstallLock) {
20173            mSettings.createNewUserLI(this, mInstaller, userId);
20174        }
20175        synchronized (mPackages) {
20176            scheduleWritePackageRestrictionsLocked(userId);
20177            scheduleWritePackageListLocked(userId);
20178            applyFactoryDefaultBrowserLPw(userId);
20179            primeDomainVerificationsLPw(userId);
20180        }
20181    }
20182
20183    void onBeforeUserStartUninitialized(final int userId) {
20184        synchronized (mPackages) {
20185            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20186                return;
20187            }
20188        }
20189        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20190        // If permission review for legacy apps is required, we represent
20191        // dagerous permissions for such apps as always granted runtime
20192        // permissions to keep per user flag state whether review is needed.
20193        // Hence, if a new user is added we have to propagate dangerous
20194        // permission grants for these legacy apps.
20195        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20196            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20197                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20198        }
20199    }
20200
20201    @Override
20202    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20203        mContext.enforceCallingOrSelfPermission(
20204                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20205                "Only package verification agents can read the verifier device identity");
20206
20207        synchronized (mPackages) {
20208            return mSettings.getVerifierDeviceIdentityLPw();
20209        }
20210    }
20211
20212    @Override
20213    public void setPermissionEnforced(String permission, boolean enforced) {
20214        // TODO: Now that we no longer change GID for storage, this should to away.
20215        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20216                "setPermissionEnforced");
20217        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20218            synchronized (mPackages) {
20219                if (mSettings.mReadExternalStorageEnforced == null
20220                        || mSettings.mReadExternalStorageEnforced != enforced) {
20221                    mSettings.mReadExternalStorageEnforced = enforced;
20222                    mSettings.writeLPr();
20223                }
20224            }
20225            // kill any non-foreground processes so we restart them and
20226            // grant/revoke the GID.
20227            final IActivityManager am = ActivityManagerNative.getDefault();
20228            if (am != null) {
20229                final long token = Binder.clearCallingIdentity();
20230                try {
20231                    am.killProcessesBelowForeground("setPermissionEnforcement");
20232                } catch (RemoteException e) {
20233                } finally {
20234                    Binder.restoreCallingIdentity(token);
20235                }
20236            }
20237        } else {
20238            throw new IllegalArgumentException("No selective enforcement for " + permission);
20239        }
20240    }
20241
20242    @Override
20243    @Deprecated
20244    public boolean isPermissionEnforced(String permission) {
20245        return true;
20246    }
20247
20248    @Override
20249    public boolean isStorageLow() {
20250        final long token = Binder.clearCallingIdentity();
20251        try {
20252            final DeviceStorageMonitorInternal
20253                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20254            if (dsm != null) {
20255                return dsm.isMemoryLow();
20256            } else {
20257                return false;
20258            }
20259        } finally {
20260            Binder.restoreCallingIdentity(token);
20261        }
20262    }
20263
20264    @Override
20265    public IPackageInstaller getPackageInstaller() {
20266        return mInstallerService;
20267    }
20268
20269    private boolean userNeedsBadging(int userId) {
20270        int index = mUserNeedsBadging.indexOfKey(userId);
20271        if (index < 0) {
20272            final UserInfo userInfo;
20273            final long token = Binder.clearCallingIdentity();
20274            try {
20275                userInfo = sUserManager.getUserInfo(userId);
20276            } finally {
20277                Binder.restoreCallingIdentity(token);
20278            }
20279            final boolean b;
20280            if (userInfo != null && userInfo.isManagedProfile()) {
20281                b = true;
20282            } else {
20283                b = false;
20284            }
20285            mUserNeedsBadging.put(userId, b);
20286            return b;
20287        }
20288        return mUserNeedsBadging.valueAt(index);
20289    }
20290
20291    @Override
20292    public KeySet getKeySetByAlias(String packageName, String alias) {
20293        if (packageName == null || alias == null) {
20294            return null;
20295        }
20296        synchronized(mPackages) {
20297            final PackageParser.Package pkg = mPackages.get(packageName);
20298            if (pkg == null) {
20299                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20300                throw new IllegalArgumentException("Unknown package: " + packageName);
20301            }
20302            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20303            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20304        }
20305    }
20306
20307    @Override
20308    public KeySet getSigningKeySet(String packageName) {
20309        if (packageName == null) {
20310            return null;
20311        }
20312        synchronized(mPackages) {
20313            final PackageParser.Package pkg = mPackages.get(packageName);
20314            if (pkg == null) {
20315                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20316                throw new IllegalArgumentException("Unknown package: " + packageName);
20317            }
20318            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20319                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20320                throw new SecurityException("May not access signing KeySet of other apps.");
20321            }
20322            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20323            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20324        }
20325    }
20326
20327    @Override
20328    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20329        if (packageName == null || ks == null) {
20330            return false;
20331        }
20332        synchronized(mPackages) {
20333            final PackageParser.Package pkg = mPackages.get(packageName);
20334            if (pkg == null) {
20335                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20336                throw new IllegalArgumentException("Unknown package: " + packageName);
20337            }
20338            IBinder ksh = ks.getToken();
20339            if (ksh instanceof KeySetHandle) {
20340                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20341                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20342            }
20343            return false;
20344        }
20345    }
20346
20347    @Override
20348    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20349        if (packageName == null || ks == null) {
20350            return false;
20351        }
20352        synchronized(mPackages) {
20353            final PackageParser.Package pkg = mPackages.get(packageName);
20354            if (pkg == null) {
20355                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20356                throw new IllegalArgumentException("Unknown package: " + packageName);
20357            }
20358            IBinder ksh = ks.getToken();
20359            if (ksh instanceof KeySetHandle) {
20360                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20361                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20362            }
20363            return false;
20364        }
20365    }
20366
20367    private void deletePackageIfUnusedLPr(final String packageName) {
20368        PackageSetting ps = mSettings.mPackages.get(packageName);
20369        if (ps == null) {
20370            return;
20371        }
20372        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20373            // TODO Implement atomic delete if package is unused
20374            // It is currently possible that the package will be deleted even if it is installed
20375            // after this method returns.
20376            mHandler.post(new Runnable() {
20377                public void run() {
20378                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20379                }
20380            });
20381        }
20382    }
20383
20384    /**
20385     * Check and throw if the given before/after packages would be considered a
20386     * downgrade.
20387     */
20388    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20389            throws PackageManagerException {
20390        if (after.versionCode < before.mVersionCode) {
20391            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20392                    "Update version code " + after.versionCode + " is older than current "
20393                    + before.mVersionCode);
20394        } else if (after.versionCode == before.mVersionCode) {
20395            if (after.baseRevisionCode < before.baseRevisionCode) {
20396                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20397                        "Update base revision code " + after.baseRevisionCode
20398                        + " is older than current " + before.baseRevisionCode);
20399            }
20400
20401            if (!ArrayUtils.isEmpty(after.splitNames)) {
20402                for (int i = 0; i < after.splitNames.length; i++) {
20403                    final String splitName = after.splitNames[i];
20404                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20405                    if (j != -1) {
20406                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20407                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20408                                    "Update split " + splitName + " revision code "
20409                                    + after.splitRevisionCodes[i] + " is older than current "
20410                                    + before.splitRevisionCodes[j]);
20411                        }
20412                    }
20413                }
20414            }
20415        }
20416    }
20417
20418    private static class MoveCallbacks extends Handler {
20419        private static final int MSG_CREATED = 1;
20420        private static final int MSG_STATUS_CHANGED = 2;
20421
20422        private final RemoteCallbackList<IPackageMoveObserver>
20423                mCallbacks = new RemoteCallbackList<>();
20424
20425        private final SparseIntArray mLastStatus = new SparseIntArray();
20426
20427        public MoveCallbacks(Looper looper) {
20428            super(looper);
20429        }
20430
20431        public void register(IPackageMoveObserver callback) {
20432            mCallbacks.register(callback);
20433        }
20434
20435        public void unregister(IPackageMoveObserver callback) {
20436            mCallbacks.unregister(callback);
20437        }
20438
20439        @Override
20440        public void handleMessage(Message msg) {
20441            final SomeArgs args = (SomeArgs) msg.obj;
20442            final int n = mCallbacks.beginBroadcast();
20443            for (int i = 0; i < n; i++) {
20444                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20445                try {
20446                    invokeCallback(callback, msg.what, args);
20447                } catch (RemoteException ignored) {
20448                }
20449            }
20450            mCallbacks.finishBroadcast();
20451            args.recycle();
20452        }
20453
20454        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20455                throws RemoteException {
20456            switch (what) {
20457                case MSG_CREATED: {
20458                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20459                    break;
20460                }
20461                case MSG_STATUS_CHANGED: {
20462                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20463                    break;
20464                }
20465            }
20466        }
20467
20468        private void notifyCreated(int moveId, Bundle extras) {
20469            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20470
20471            final SomeArgs args = SomeArgs.obtain();
20472            args.argi1 = moveId;
20473            args.arg2 = extras;
20474            obtainMessage(MSG_CREATED, args).sendToTarget();
20475        }
20476
20477        private void notifyStatusChanged(int moveId, int status) {
20478            notifyStatusChanged(moveId, status, -1);
20479        }
20480
20481        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20482            Slog.v(TAG, "Move " + moveId + " status " + status);
20483
20484            final SomeArgs args = SomeArgs.obtain();
20485            args.argi1 = moveId;
20486            args.argi2 = status;
20487            args.arg3 = estMillis;
20488            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20489
20490            synchronized (mLastStatus) {
20491                mLastStatus.put(moveId, status);
20492            }
20493        }
20494    }
20495
20496    private final static class OnPermissionChangeListeners extends Handler {
20497        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20498
20499        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20500                new RemoteCallbackList<>();
20501
20502        public OnPermissionChangeListeners(Looper looper) {
20503            super(looper);
20504        }
20505
20506        @Override
20507        public void handleMessage(Message msg) {
20508            switch (msg.what) {
20509                case MSG_ON_PERMISSIONS_CHANGED: {
20510                    final int uid = msg.arg1;
20511                    handleOnPermissionsChanged(uid);
20512                } break;
20513            }
20514        }
20515
20516        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20517            mPermissionListeners.register(listener);
20518
20519        }
20520
20521        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20522            mPermissionListeners.unregister(listener);
20523        }
20524
20525        public void onPermissionsChanged(int uid) {
20526            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20527                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20528            }
20529        }
20530
20531        private void handleOnPermissionsChanged(int uid) {
20532            final int count = mPermissionListeners.beginBroadcast();
20533            try {
20534                for (int i = 0; i < count; i++) {
20535                    IOnPermissionsChangeListener callback = mPermissionListeners
20536                            .getBroadcastItem(i);
20537                    try {
20538                        callback.onPermissionsChanged(uid);
20539                    } catch (RemoteException e) {
20540                        Log.e(TAG, "Permission listener is dead", e);
20541                    }
20542                }
20543            } finally {
20544                mPermissionListeners.finishBroadcast();
20545            }
20546        }
20547    }
20548
20549    private class PackageManagerInternalImpl extends PackageManagerInternal {
20550        @Override
20551        public void setLocationPackagesProvider(PackagesProvider provider) {
20552            synchronized (mPackages) {
20553                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20554            }
20555        }
20556
20557        @Override
20558        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20559            synchronized (mPackages) {
20560                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20561            }
20562        }
20563
20564        @Override
20565        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20566            synchronized (mPackages) {
20567                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20568            }
20569        }
20570
20571        @Override
20572        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20573            synchronized (mPackages) {
20574                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20575            }
20576        }
20577
20578        @Override
20579        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20580            synchronized (mPackages) {
20581                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20582            }
20583        }
20584
20585        @Override
20586        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20587            synchronized (mPackages) {
20588                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20589            }
20590        }
20591
20592        @Override
20593        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20594            synchronized (mPackages) {
20595                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20596                        packageName, userId);
20597            }
20598        }
20599
20600        @Override
20601        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20602            synchronized (mPackages) {
20603                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20604                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20605                        packageName, userId);
20606            }
20607        }
20608
20609        @Override
20610        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20611            synchronized (mPackages) {
20612                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20613                        packageName, userId);
20614            }
20615        }
20616
20617        @Override
20618        public void setKeepUninstalledPackages(final List<String> packageList) {
20619            Preconditions.checkNotNull(packageList);
20620            List<String> removedFromList = null;
20621            synchronized (mPackages) {
20622                if (mKeepUninstalledPackages != null) {
20623                    final int packagesCount = mKeepUninstalledPackages.size();
20624                    for (int i = 0; i < packagesCount; i++) {
20625                        String oldPackage = mKeepUninstalledPackages.get(i);
20626                        if (packageList != null && packageList.contains(oldPackage)) {
20627                            continue;
20628                        }
20629                        if (removedFromList == null) {
20630                            removedFromList = new ArrayList<>();
20631                        }
20632                        removedFromList.add(oldPackage);
20633                    }
20634                }
20635                mKeepUninstalledPackages = new ArrayList<>(packageList);
20636                if (removedFromList != null) {
20637                    final int removedCount = removedFromList.size();
20638                    for (int i = 0; i < removedCount; i++) {
20639                        deletePackageIfUnusedLPr(removedFromList.get(i));
20640                    }
20641                }
20642            }
20643        }
20644
20645        @Override
20646        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20647            synchronized (mPackages) {
20648                // If we do not support permission review, done.
20649                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20650                    return false;
20651                }
20652
20653                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20654                if (packageSetting == null) {
20655                    return false;
20656                }
20657
20658                // Permission review applies only to apps not supporting the new permission model.
20659                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20660                    return false;
20661                }
20662
20663                // Legacy apps have the permission and get user consent on launch.
20664                PermissionsState permissionsState = packageSetting.getPermissionsState();
20665                return permissionsState.isPermissionReviewRequired(userId);
20666            }
20667        }
20668
20669        @Override
20670        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20671            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20672        }
20673
20674        @Override
20675        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20676                int userId) {
20677            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20678        }
20679    }
20680
20681    @Override
20682    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20683        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20684        synchronized (mPackages) {
20685            final long identity = Binder.clearCallingIdentity();
20686            try {
20687                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20688                        packageNames, userId);
20689            } finally {
20690                Binder.restoreCallingIdentity(identity);
20691            }
20692        }
20693    }
20694
20695    private static void enforceSystemOrPhoneCaller(String tag) {
20696        int callingUid = Binder.getCallingUid();
20697        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20698            throw new SecurityException(
20699                    "Cannot call " + tag + " from UID " + callingUid);
20700        }
20701    }
20702
20703    boolean isHistoricalPackageUsageAvailable() {
20704        return mPackageUsage.isHistoricalPackageUsageAvailable();
20705    }
20706
20707    /**
20708     * Return a <b>copy</b> of the collection of packages known to the package manager.
20709     * @return A copy of the values of mPackages.
20710     */
20711    Collection<PackageParser.Package> getPackages() {
20712        synchronized (mPackages) {
20713            return new ArrayList<>(mPackages.values());
20714        }
20715    }
20716
20717    /**
20718     * Logs process start information (including base APK hash) to the security log.
20719     * @hide
20720     */
20721    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20722            String apkFile, int pid) {
20723        if (!SecurityLog.isLoggingEnabled()) {
20724            return;
20725        }
20726        Bundle data = new Bundle();
20727        data.putLong("startTimestamp", System.currentTimeMillis());
20728        data.putString("processName", processName);
20729        data.putInt("uid", uid);
20730        data.putString("seinfo", seinfo);
20731        data.putString("apkFile", apkFile);
20732        data.putInt("pid", pid);
20733        Message msg = mProcessLoggingHandler.obtainMessage(
20734                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20735        msg.setData(data);
20736        mProcessLoggingHandler.sendMessage(msg);
20737    }
20738}
20739