PackageManagerService.java revision 93193135b184a2f1c7518d8beeff7c51b2880606
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                }
2727                ver.fingerprint = Build.FINGERPRINT;
2728            }
2729
2730            checkDefaultBrowser();
2731
2732            // clear only after permissions and other defaults have been updated
2733            mExistingSystemPackages.clear();
2734            mPromoteSystemApps = false;
2735
2736            // All the changes are done during package scanning.
2737            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2738
2739            // can downgrade to reader
2740            mSettings.writeLPr();
2741
2742            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2743                    SystemClock.uptimeMillis());
2744
2745            if (!mOnlyCore) {
2746                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2747                mRequiredInstallerPackage = getRequiredInstallerLPr();
2748                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2749                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2750                        mIntentFilterVerifierComponent);
2751                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2752                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2753                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2754                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2755            } else {
2756                mRequiredVerifierPackage = null;
2757                mRequiredInstallerPackage = null;
2758                mIntentFilterVerifierComponent = null;
2759                mIntentFilterVerifier = null;
2760                mServicesSystemSharedLibraryPackageName = null;
2761                mSharedSystemSharedLibraryPackageName = null;
2762            }
2763
2764            mInstallerService = new PackageInstallerService(context, this);
2765
2766            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2767            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2768            // both the installer and resolver must be present to enable ephemeral
2769            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2770                if (DEBUG_EPHEMERAL) {
2771                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2772                            + " installer:" + ephemeralInstallerComponent);
2773                }
2774                mEphemeralResolverComponent = ephemeralResolverComponent;
2775                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2776                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2777                mEphemeralResolverConnection =
2778                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2779            } else {
2780                if (DEBUG_EPHEMERAL) {
2781                    final String missingComponent =
2782                            (ephemeralResolverComponent == null)
2783                            ? (ephemeralInstallerComponent == null)
2784                                    ? "resolver and installer"
2785                                    : "resolver"
2786                            : "installer";
2787                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2788                }
2789                mEphemeralResolverComponent = null;
2790                mEphemeralInstallerComponent = null;
2791                mEphemeralResolverConnection = null;
2792            }
2793
2794            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2795        } // synchronized (mPackages)
2796        } // synchronized (mInstallLock)
2797
2798        // Now after opening every single application zip, make sure they
2799        // are all flushed.  Not really needed, but keeps things nice and
2800        // tidy.
2801        Runtime.getRuntime().gc();
2802
2803        // The initial scanning above does many calls into installd while
2804        // holding the mPackages lock, but we're mostly interested in yelling
2805        // once we have a booted system.
2806        mInstaller.setWarnIfHeld(mPackages);
2807
2808        // Expose private service for system components to use.
2809        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2810    }
2811
2812    @Override
2813    public boolean isFirstBoot() {
2814        return !mRestoredSettings;
2815    }
2816
2817    @Override
2818    public boolean isOnlyCoreApps() {
2819        return mOnlyCore;
2820    }
2821
2822    @Override
2823    public boolean isUpgrade() {
2824        return mIsUpgrade;
2825    }
2826
2827    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2828        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2829
2830        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2831                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2832                UserHandle.USER_SYSTEM);
2833        if (matches.size() == 1) {
2834            return matches.get(0).getComponentInfo().packageName;
2835        } else {
2836            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2837            return null;
2838        }
2839    }
2840
2841    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2842        synchronized (mPackages) {
2843            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2844            if (libraryEntry == null) {
2845                throw new IllegalStateException("Missing required shared library:" + libraryName);
2846            }
2847            return libraryEntry.apk;
2848        }
2849    }
2850
2851    private @NonNull String getRequiredInstallerLPr() {
2852        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2853        intent.addCategory(Intent.CATEGORY_DEFAULT);
2854        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2855
2856        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2857                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2858                UserHandle.USER_SYSTEM);
2859        if (matches.size() == 1) {
2860            ResolveInfo resolveInfo = matches.get(0);
2861            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2862                throw new RuntimeException("The installer must be a privileged app");
2863            }
2864            return matches.get(0).getComponentInfo().packageName;
2865        } else {
2866            throw new RuntimeException("There must be exactly one installer; found " + matches);
2867        }
2868    }
2869
2870    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2871        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2872
2873        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2874                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2875                UserHandle.USER_SYSTEM);
2876        ResolveInfo best = null;
2877        final int N = matches.size();
2878        for (int i = 0; i < N; i++) {
2879            final ResolveInfo cur = matches.get(i);
2880            final String packageName = cur.getComponentInfo().packageName;
2881            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2882                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2883                continue;
2884            }
2885
2886            if (best == null || cur.priority > best.priority) {
2887                best = cur;
2888            }
2889        }
2890
2891        if (best != null) {
2892            return best.getComponentInfo().getComponentName();
2893        } else {
2894            throw new RuntimeException("There must be at least one intent filter verifier");
2895        }
2896    }
2897
2898    private @Nullable ComponentName getEphemeralResolverLPr() {
2899        final String[] packageArray =
2900                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2901        if (packageArray.length == 0) {
2902            if (DEBUG_EPHEMERAL) {
2903                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2904            }
2905            return null;
2906        }
2907
2908        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2909        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2910                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2911                UserHandle.USER_SYSTEM);
2912
2913        final int N = resolvers.size();
2914        if (N == 0) {
2915            if (DEBUG_EPHEMERAL) {
2916                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2917            }
2918            return null;
2919        }
2920
2921        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2922        for (int i = 0; i < N; i++) {
2923            final ResolveInfo info = resolvers.get(i);
2924
2925            if (info.serviceInfo == null) {
2926                continue;
2927            }
2928
2929            final String packageName = info.serviceInfo.packageName;
2930            if (!possiblePackages.contains(packageName)) {
2931                if (DEBUG_EPHEMERAL) {
2932                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2933                            + " pkg: " + packageName + ", info:" + info);
2934                }
2935                continue;
2936            }
2937
2938            if (DEBUG_EPHEMERAL) {
2939                Slog.v(TAG, "Ephemeral resolver found;"
2940                        + " pkg: " + packageName + ", info:" + info);
2941            }
2942            return new ComponentName(packageName, info.serviceInfo.name);
2943        }
2944        if (DEBUG_EPHEMERAL) {
2945            Slog.v(TAG, "Ephemeral resolver NOT found");
2946        }
2947        return null;
2948    }
2949
2950    private @Nullable ComponentName getEphemeralInstallerLPr() {
2951        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2952        intent.addCategory(Intent.CATEGORY_DEFAULT);
2953        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2954
2955        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2956                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2957                UserHandle.USER_SYSTEM);
2958        if (matches.size() == 0) {
2959            return null;
2960        } else if (matches.size() == 1) {
2961            return matches.get(0).getComponentInfo().getComponentName();
2962        } else {
2963            throw new RuntimeException(
2964                    "There must be at most one ephemeral installer; found " + matches);
2965        }
2966    }
2967
2968    private void primeDomainVerificationsLPw(int userId) {
2969        if (DEBUG_DOMAIN_VERIFICATION) {
2970            Slog.d(TAG, "Priming domain verifications in user " + userId);
2971        }
2972
2973        SystemConfig systemConfig = SystemConfig.getInstance();
2974        ArraySet<String> packages = systemConfig.getLinkedApps();
2975        ArraySet<String> domains = new ArraySet<String>();
2976
2977        for (String packageName : packages) {
2978            PackageParser.Package pkg = mPackages.get(packageName);
2979            if (pkg != null) {
2980                if (!pkg.isSystemApp()) {
2981                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2982                    continue;
2983                }
2984
2985                domains.clear();
2986                for (PackageParser.Activity a : pkg.activities) {
2987                    for (ActivityIntentInfo filter : a.intents) {
2988                        if (hasValidDomains(filter)) {
2989                            domains.addAll(filter.getHostsList());
2990                        }
2991                    }
2992                }
2993
2994                if (domains.size() > 0) {
2995                    if (DEBUG_DOMAIN_VERIFICATION) {
2996                        Slog.v(TAG, "      + " + packageName);
2997                    }
2998                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2999                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3000                    // and then 'always' in the per-user state actually used for intent resolution.
3001                    final IntentFilterVerificationInfo ivi;
3002                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3003                            new ArrayList<String>(domains));
3004                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3005                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3006                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3007                } else {
3008                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3009                            + "' does not handle web links");
3010                }
3011            } else {
3012                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3013            }
3014        }
3015
3016        scheduleWritePackageRestrictionsLocked(userId);
3017        scheduleWriteSettingsLocked();
3018    }
3019
3020    private void applyFactoryDefaultBrowserLPw(int userId) {
3021        // The default browser app's package name is stored in a string resource,
3022        // with a product-specific overlay used for vendor customization.
3023        String browserPkg = mContext.getResources().getString(
3024                com.android.internal.R.string.default_browser);
3025        if (!TextUtils.isEmpty(browserPkg)) {
3026            // non-empty string => required to be a known package
3027            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3028            if (ps == null) {
3029                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3030                browserPkg = null;
3031            } else {
3032                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3033            }
3034        }
3035
3036        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3037        // default.  If there's more than one, just leave everything alone.
3038        if (browserPkg == null) {
3039            calculateDefaultBrowserLPw(userId);
3040        }
3041    }
3042
3043    private void calculateDefaultBrowserLPw(int userId) {
3044        List<String> allBrowsers = resolveAllBrowserApps(userId);
3045        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3046        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3047    }
3048
3049    private List<String> resolveAllBrowserApps(int userId) {
3050        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3051        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3052                PackageManager.MATCH_ALL, userId);
3053
3054        final int count = list.size();
3055        List<String> result = new ArrayList<String>(count);
3056        for (int i=0; i<count; i++) {
3057            ResolveInfo info = list.get(i);
3058            if (info.activityInfo == null
3059                    || !info.handleAllWebDataURI
3060                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3061                    || result.contains(info.activityInfo.packageName)) {
3062                continue;
3063            }
3064            result.add(info.activityInfo.packageName);
3065        }
3066
3067        return result;
3068    }
3069
3070    private boolean packageIsBrowser(String packageName, int userId) {
3071        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3072                PackageManager.MATCH_ALL, userId);
3073        final int N = list.size();
3074        for (int i = 0; i < N; i++) {
3075            ResolveInfo info = list.get(i);
3076            if (packageName.equals(info.activityInfo.packageName)) {
3077                return true;
3078            }
3079        }
3080        return false;
3081    }
3082
3083    private void checkDefaultBrowser() {
3084        final int myUserId = UserHandle.myUserId();
3085        final String packageName = getDefaultBrowserPackageName(myUserId);
3086        if (packageName != null) {
3087            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3088            if (info == null) {
3089                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3090                synchronized (mPackages) {
3091                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3092                }
3093            }
3094        }
3095    }
3096
3097    @Override
3098    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3099            throws RemoteException {
3100        try {
3101            return super.onTransact(code, data, reply, flags);
3102        } catch (RuntimeException e) {
3103            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3104                Slog.wtf(TAG, "Package Manager Crash", e);
3105            }
3106            throw e;
3107        }
3108    }
3109
3110    static int[] appendInts(int[] cur, int[] add) {
3111        if (add == null) return cur;
3112        if (cur == null) return add;
3113        final int N = add.length;
3114        for (int i=0; i<N; i++) {
3115            cur = appendInt(cur, add[i]);
3116        }
3117        return cur;
3118    }
3119
3120    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3121        if (!sUserManager.exists(userId)) return null;
3122        if (ps == null) {
3123            return null;
3124        }
3125        final PackageParser.Package p = ps.pkg;
3126        if (p == null) {
3127            return null;
3128        }
3129
3130        final PermissionsState permissionsState = ps.getPermissionsState();
3131
3132        final int[] gids = permissionsState.computeGids(userId);
3133        final Set<String> permissions = permissionsState.getPermissions(userId);
3134        final PackageUserState state = ps.readUserState(userId);
3135
3136        return PackageParser.generatePackageInfo(p, gids, flags,
3137                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3138    }
3139
3140    @Override
3141    public void checkPackageStartable(String packageName, int userId) {
3142        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3143
3144        synchronized (mPackages) {
3145            final PackageSetting ps = mSettings.mPackages.get(packageName);
3146            if (ps == null) {
3147                throw new SecurityException("Package " + packageName + " was not found!");
3148            }
3149
3150            if (!ps.getInstalled(userId)) {
3151                throw new SecurityException(
3152                        "Package " + packageName + " was not installed for user " + userId + "!");
3153            }
3154
3155            if (mSafeMode && !ps.isSystem()) {
3156                throw new SecurityException("Package " + packageName + " not a system app!");
3157            }
3158
3159            if (mFrozenPackages.contains(packageName)) {
3160                throw new SecurityException("Package " + packageName + " is currently frozen!");
3161            }
3162
3163            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3164                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3165                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3166            }
3167        }
3168    }
3169
3170    @Override
3171    public boolean isPackageAvailable(String packageName, int userId) {
3172        if (!sUserManager.exists(userId)) return false;
3173        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3174                false /* requireFullPermission */, false /* checkShell */, "is package available");
3175        synchronized (mPackages) {
3176            PackageParser.Package p = mPackages.get(packageName);
3177            if (p != null) {
3178                final PackageSetting ps = (PackageSetting) p.mExtras;
3179                if (ps != null) {
3180                    final PackageUserState state = ps.readUserState(userId);
3181                    if (state != null) {
3182                        return PackageParser.isAvailable(state);
3183                    }
3184                }
3185            }
3186        }
3187        return false;
3188    }
3189
3190    @Override
3191    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3192        if (!sUserManager.exists(userId)) return null;
3193        flags = updateFlagsForPackage(flags, userId, packageName);
3194        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3195                false /* requireFullPermission */, false /* checkShell */, "get package info");
3196        // reader
3197        synchronized (mPackages) {
3198            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3199            PackageParser.Package p = null;
3200            if (matchFactoryOnly) {
3201                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3202                if (ps != null) {
3203                    return generatePackageInfo(ps, flags, userId);
3204                }
3205            }
3206            if (p == null) {
3207                p = mPackages.get(packageName);
3208                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3209                    return null;
3210                }
3211            }
3212            if (DEBUG_PACKAGE_INFO)
3213                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3214            if (p != null) {
3215                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3216            }
3217            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3218                final PackageSetting ps = mSettings.mPackages.get(packageName);
3219                return generatePackageInfo(ps, flags, userId);
3220            }
3221        }
3222        return null;
3223    }
3224
3225    @Override
3226    public String[] currentToCanonicalPackageNames(String[] names) {
3227        String[] out = new String[names.length];
3228        // reader
3229        synchronized (mPackages) {
3230            for (int i=names.length-1; i>=0; i--) {
3231                PackageSetting ps = mSettings.mPackages.get(names[i]);
3232                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3233            }
3234        }
3235        return out;
3236    }
3237
3238    @Override
3239    public String[] canonicalToCurrentPackageNames(String[] names) {
3240        String[] out = new String[names.length];
3241        // reader
3242        synchronized (mPackages) {
3243            for (int i=names.length-1; i>=0; i--) {
3244                String cur = mSettings.mRenamedPackages.get(names[i]);
3245                out[i] = cur != null ? cur : names[i];
3246            }
3247        }
3248        return out;
3249    }
3250
3251    @Override
3252    public int getPackageUid(String packageName, int flags, int userId) {
3253        if (!sUserManager.exists(userId)) return -1;
3254        flags = updateFlagsForPackage(flags, userId, packageName);
3255        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3256                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3257
3258        // reader
3259        synchronized (mPackages) {
3260            final PackageParser.Package p = mPackages.get(packageName);
3261            if (p != null && p.isMatch(flags)) {
3262                return UserHandle.getUid(userId, p.applicationInfo.uid);
3263            }
3264            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3265                final PackageSetting ps = mSettings.mPackages.get(packageName);
3266                if (ps != null && ps.isMatch(flags)) {
3267                    return UserHandle.getUid(userId, ps.appId);
3268                }
3269            }
3270        }
3271
3272        return -1;
3273    }
3274
3275    @Override
3276    public int[] getPackageGids(String packageName, int flags, int userId) {
3277        if (!sUserManager.exists(userId)) return null;
3278        flags = updateFlagsForPackage(flags, userId, packageName);
3279        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3280                false /* requireFullPermission */, false /* checkShell */,
3281                "getPackageGids");
3282
3283        // reader
3284        synchronized (mPackages) {
3285            final PackageParser.Package p = mPackages.get(packageName);
3286            if (p != null && p.isMatch(flags)) {
3287                PackageSetting ps = (PackageSetting) p.mExtras;
3288                return ps.getPermissionsState().computeGids(userId);
3289            }
3290            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3291                final PackageSetting ps = mSettings.mPackages.get(packageName);
3292                if (ps != null && ps.isMatch(flags)) {
3293                    return ps.getPermissionsState().computeGids(userId);
3294                }
3295            }
3296        }
3297
3298        return null;
3299    }
3300
3301    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3302        if (bp.perm != null) {
3303            return PackageParser.generatePermissionInfo(bp.perm, flags);
3304        }
3305        PermissionInfo pi = new PermissionInfo();
3306        pi.name = bp.name;
3307        pi.packageName = bp.sourcePackage;
3308        pi.nonLocalizedLabel = bp.name;
3309        pi.protectionLevel = bp.protectionLevel;
3310        return pi;
3311    }
3312
3313    @Override
3314    public PermissionInfo getPermissionInfo(String name, int flags) {
3315        // reader
3316        synchronized (mPackages) {
3317            final BasePermission p = mSettings.mPermissions.get(name);
3318            if (p != null) {
3319                return generatePermissionInfo(p, flags);
3320            }
3321            return null;
3322        }
3323    }
3324
3325    @Override
3326    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3327            int flags) {
3328        // reader
3329        synchronized (mPackages) {
3330            if (group != null && !mPermissionGroups.containsKey(group)) {
3331                // This is thrown as NameNotFoundException
3332                return null;
3333            }
3334
3335            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3336            for (BasePermission p : mSettings.mPermissions.values()) {
3337                if (group == null) {
3338                    if (p.perm == null || p.perm.info.group == null) {
3339                        out.add(generatePermissionInfo(p, flags));
3340                    }
3341                } else {
3342                    if (p.perm != null && group.equals(p.perm.info.group)) {
3343                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3344                    }
3345                }
3346            }
3347            return new ParceledListSlice<>(out);
3348        }
3349    }
3350
3351    @Override
3352    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3353        // reader
3354        synchronized (mPackages) {
3355            return PackageParser.generatePermissionGroupInfo(
3356                    mPermissionGroups.get(name), flags);
3357        }
3358    }
3359
3360    @Override
3361    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3362        // reader
3363        synchronized (mPackages) {
3364            final int N = mPermissionGroups.size();
3365            ArrayList<PermissionGroupInfo> out
3366                    = new ArrayList<PermissionGroupInfo>(N);
3367            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3368                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3369            }
3370            return new ParceledListSlice<>(out);
3371        }
3372    }
3373
3374    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3375            int userId) {
3376        if (!sUserManager.exists(userId)) return null;
3377        PackageSetting ps = mSettings.mPackages.get(packageName);
3378        if (ps != null) {
3379            if (ps.pkg == null) {
3380                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3381                if (pInfo != null) {
3382                    return pInfo.applicationInfo;
3383                }
3384                return null;
3385            }
3386            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3387                    ps.readUserState(userId), userId);
3388        }
3389        return null;
3390    }
3391
3392    @Override
3393    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3394        if (!sUserManager.exists(userId)) return null;
3395        flags = updateFlagsForApplication(flags, userId, packageName);
3396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3397                false /* requireFullPermission */, false /* checkShell */, "get application info");
3398        // writer
3399        synchronized (mPackages) {
3400            PackageParser.Package p = mPackages.get(packageName);
3401            if (DEBUG_PACKAGE_INFO) Log.v(
3402                    TAG, "getApplicationInfo " + packageName
3403                    + ": " + p);
3404            if (p != null) {
3405                PackageSetting ps = mSettings.mPackages.get(packageName);
3406                if (ps == null) return null;
3407                // Note: isEnabledLP() does not apply here - always return info
3408                return PackageParser.generateApplicationInfo(
3409                        p, flags, ps.readUserState(userId), userId);
3410            }
3411            if ("android".equals(packageName)||"system".equals(packageName)) {
3412                return mAndroidApplication;
3413            }
3414            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3415                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3416            }
3417        }
3418        return null;
3419    }
3420
3421    @Override
3422    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3423            final IPackageDataObserver observer) {
3424        mContext.enforceCallingOrSelfPermission(
3425                android.Manifest.permission.CLEAR_APP_CACHE, null);
3426        // Queue up an async operation since clearing cache may take a little while.
3427        mHandler.post(new Runnable() {
3428            public void run() {
3429                mHandler.removeCallbacks(this);
3430                boolean success = true;
3431                synchronized (mInstallLock) {
3432                    try {
3433                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3434                    } catch (InstallerException e) {
3435                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3436                        success = false;
3437                    }
3438                }
3439                if (observer != null) {
3440                    try {
3441                        observer.onRemoveCompleted(null, success);
3442                    } catch (RemoteException e) {
3443                        Slog.w(TAG, "RemoveException when invoking call back");
3444                    }
3445                }
3446            }
3447        });
3448    }
3449
3450    @Override
3451    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3452            final IntentSender pi) {
3453        mContext.enforceCallingOrSelfPermission(
3454                android.Manifest.permission.CLEAR_APP_CACHE, null);
3455        // Queue up an async operation since clearing cache may take a little while.
3456        mHandler.post(new Runnable() {
3457            public void run() {
3458                mHandler.removeCallbacks(this);
3459                boolean success = true;
3460                synchronized (mInstallLock) {
3461                    try {
3462                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3463                    } catch (InstallerException e) {
3464                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3465                        success = false;
3466                    }
3467                }
3468                if(pi != null) {
3469                    try {
3470                        // Callback via pending intent
3471                        int code = success ? 1 : 0;
3472                        pi.sendIntent(null, code, null,
3473                                null, null);
3474                    } catch (SendIntentException e1) {
3475                        Slog.i(TAG, "Failed to send pending intent");
3476                    }
3477                }
3478            }
3479        });
3480    }
3481
3482    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3483        synchronized (mInstallLock) {
3484            try {
3485                mInstaller.freeCache(volumeUuid, freeStorageSize);
3486            } catch (InstallerException e) {
3487                throw new IOException("Failed to free enough space", e);
3488            }
3489        }
3490    }
3491
3492    /**
3493     * Update given flags based on encryption status of current user.
3494     */
3495    private int updateFlags(int flags, int userId) {
3496        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3497                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3498            // Caller expressed an explicit opinion about what encryption
3499            // aware/unaware components they want to see, so fall through and
3500            // give them what they want
3501        } else {
3502            // Caller expressed no opinion, so match based on user state
3503            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3504                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3505            } else {
3506                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3507            }
3508        }
3509        return flags;
3510    }
3511
3512    private UserManagerInternal getUserManagerInternal() {
3513        if (mUserManagerInternal == null) {
3514            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3515        }
3516        return mUserManagerInternal;
3517    }
3518
3519    /**
3520     * Update given flags when being used to request {@link PackageInfo}.
3521     */
3522    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3523        boolean triaged = true;
3524        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3525                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3526            // Caller is asking for component details, so they'd better be
3527            // asking for specific encryption matching behavior, or be triaged
3528            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3529                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3530                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3531                triaged = false;
3532            }
3533        }
3534        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3535                | PackageManager.MATCH_SYSTEM_ONLY
3536                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3537            triaged = false;
3538        }
3539        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3540            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3541                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3542        }
3543        return updateFlags(flags, userId);
3544    }
3545
3546    /**
3547     * Update given flags when being used to request {@link ApplicationInfo}.
3548     */
3549    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3550        return updateFlagsForPackage(flags, userId, cookie);
3551    }
3552
3553    /**
3554     * Update given flags when being used to request {@link ComponentInfo}.
3555     */
3556    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3557        if (cookie instanceof Intent) {
3558            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3559                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3560            }
3561        }
3562
3563        boolean triaged = true;
3564        // Caller is asking for component details, so they'd better be
3565        // asking for specific encryption matching behavior, or be triaged
3566        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3567                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3568                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3569            triaged = false;
3570        }
3571        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3572            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3573                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3574        }
3575
3576        return updateFlags(flags, userId);
3577    }
3578
3579    /**
3580     * Update given flags when being used to request {@link ResolveInfo}.
3581     */
3582    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3583        // Safe mode means we shouldn't match any third-party components
3584        if (mSafeMode) {
3585            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3586        }
3587
3588        return updateFlagsForComponent(flags, userId, cookie);
3589    }
3590
3591    @Override
3592    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3593        if (!sUserManager.exists(userId)) return null;
3594        flags = updateFlagsForComponent(flags, userId, component);
3595        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3596                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3597        synchronized (mPackages) {
3598            PackageParser.Activity a = mActivities.mActivities.get(component);
3599
3600            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3601            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3602                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3603                if (ps == null) return null;
3604                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3605                        userId);
3606            }
3607            if (mResolveComponentName.equals(component)) {
3608                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3609                        new PackageUserState(), userId);
3610            }
3611        }
3612        return null;
3613    }
3614
3615    @Override
3616    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3617            String resolvedType) {
3618        synchronized (mPackages) {
3619            if (component.equals(mResolveComponentName)) {
3620                // The resolver supports EVERYTHING!
3621                return true;
3622            }
3623            PackageParser.Activity a = mActivities.mActivities.get(component);
3624            if (a == null) {
3625                return false;
3626            }
3627            for (int i=0; i<a.intents.size(); i++) {
3628                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3629                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3630                    return true;
3631                }
3632            }
3633            return false;
3634        }
3635    }
3636
3637    @Override
3638    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3639        if (!sUserManager.exists(userId)) return null;
3640        flags = updateFlagsForComponent(flags, userId, component);
3641        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3642                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3643        synchronized (mPackages) {
3644            PackageParser.Activity a = mReceivers.mActivities.get(component);
3645            if (DEBUG_PACKAGE_INFO) Log.v(
3646                TAG, "getReceiverInfo " + component + ": " + a);
3647            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3648                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3649                if (ps == null) return null;
3650                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3651                        userId);
3652            }
3653        }
3654        return null;
3655    }
3656
3657    @Override
3658    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3659        if (!sUserManager.exists(userId)) return null;
3660        flags = updateFlagsForComponent(flags, userId, component);
3661        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3662                false /* requireFullPermission */, false /* checkShell */, "get service info");
3663        synchronized (mPackages) {
3664            PackageParser.Service s = mServices.mServices.get(component);
3665            if (DEBUG_PACKAGE_INFO) Log.v(
3666                TAG, "getServiceInfo " + component + ": " + s);
3667            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3668                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3669                if (ps == null) return null;
3670                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3671                        userId);
3672            }
3673        }
3674        return null;
3675    }
3676
3677    @Override
3678    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3679        if (!sUserManager.exists(userId)) return null;
3680        flags = updateFlagsForComponent(flags, userId, component);
3681        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3682                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3683        synchronized (mPackages) {
3684            PackageParser.Provider p = mProviders.mProviders.get(component);
3685            if (DEBUG_PACKAGE_INFO) Log.v(
3686                TAG, "getProviderInfo " + component + ": " + p);
3687            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3688                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3689                if (ps == null) return null;
3690                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3691                        userId);
3692            }
3693        }
3694        return null;
3695    }
3696
3697    @Override
3698    public String[] getSystemSharedLibraryNames() {
3699        Set<String> libSet;
3700        synchronized (mPackages) {
3701            libSet = mSharedLibraries.keySet();
3702            int size = libSet.size();
3703            if (size > 0) {
3704                String[] libs = new String[size];
3705                libSet.toArray(libs);
3706                return libs;
3707            }
3708        }
3709        return null;
3710    }
3711
3712    @Override
3713    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3714        synchronized (mPackages) {
3715            return mServicesSystemSharedLibraryPackageName;
3716        }
3717    }
3718
3719    @Override
3720    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3721        synchronized (mPackages) {
3722            return mSharedSystemSharedLibraryPackageName;
3723        }
3724    }
3725
3726    @Override
3727    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3728        synchronized (mPackages) {
3729            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3730
3731            final FeatureInfo fi = new FeatureInfo();
3732            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3733                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3734            res.add(fi);
3735
3736            return new ParceledListSlice<>(res);
3737        }
3738    }
3739
3740    @Override
3741    public boolean hasSystemFeature(String name, int version) {
3742        synchronized (mPackages) {
3743            final FeatureInfo feat = mAvailableFeatures.get(name);
3744            if (feat == null) {
3745                return false;
3746            } else {
3747                return feat.version >= version;
3748            }
3749        }
3750    }
3751
3752    @Override
3753    public int checkPermission(String permName, String pkgName, int userId) {
3754        if (!sUserManager.exists(userId)) {
3755            return PackageManager.PERMISSION_DENIED;
3756        }
3757
3758        synchronized (mPackages) {
3759            final PackageParser.Package p = mPackages.get(pkgName);
3760            if (p != null && p.mExtras != null) {
3761                final PackageSetting ps = (PackageSetting) p.mExtras;
3762                final PermissionsState permissionsState = ps.getPermissionsState();
3763                if (permissionsState.hasPermission(permName, userId)) {
3764                    return PackageManager.PERMISSION_GRANTED;
3765                }
3766                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3767                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3768                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3769                    return PackageManager.PERMISSION_GRANTED;
3770                }
3771            }
3772        }
3773
3774        return PackageManager.PERMISSION_DENIED;
3775    }
3776
3777    @Override
3778    public int checkUidPermission(String permName, int uid) {
3779        final int userId = UserHandle.getUserId(uid);
3780
3781        if (!sUserManager.exists(userId)) {
3782            return PackageManager.PERMISSION_DENIED;
3783        }
3784
3785        synchronized (mPackages) {
3786            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3787            if (obj != null) {
3788                final SettingBase ps = (SettingBase) obj;
3789                final PermissionsState permissionsState = ps.getPermissionsState();
3790                if (permissionsState.hasPermission(permName, userId)) {
3791                    return PackageManager.PERMISSION_GRANTED;
3792                }
3793                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3794                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3795                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3796                    return PackageManager.PERMISSION_GRANTED;
3797                }
3798            } else {
3799                ArraySet<String> perms = mSystemPermissions.get(uid);
3800                if (perms != null) {
3801                    if (perms.contains(permName)) {
3802                        return PackageManager.PERMISSION_GRANTED;
3803                    }
3804                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3805                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3806                        return PackageManager.PERMISSION_GRANTED;
3807                    }
3808                }
3809            }
3810        }
3811
3812        return PackageManager.PERMISSION_DENIED;
3813    }
3814
3815    @Override
3816    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3817        if (UserHandle.getCallingUserId() != userId) {
3818            mContext.enforceCallingPermission(
3819                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3820                    "isPermissionRevokedByPolicy for user " + userId);
3821        }
3822
3823        if (checkPermission(permission, packageName, userId)
3824                == PackageManager.PERMISSION_GRANTED) {
3825            return false;
3826        }
3827
3828        final long identity = Binder.clearCallingIdentity();
3829        try {
3830            final int flags = getPermissionFlags(permission, packageName, userId);
3831            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3832        } finally {
3833            Binder.restoreCallingIdentity(identity);
3834        }
3835    }
3836
3837    @Override
3838    public String getPermissionControllerPackageName() {
3839        synchronized (mPackages) {
3840            return mRequiredInstallerPackage;
3841        }
3842    }
3843
3844    /**
3845     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3846     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3847     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3848     * @param message the message to log on security exception
3849     */
3850    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3851            boolean checkShell, String message) {
3852        if (userId < 0) {
3853            throw new IllegalArgumentException("Invalid userId " + userId);
3854        }
3855        if (checkShell) {
3856            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3857        }
3858        if (userId == UserHandle.getUserId(callingUid)) return;
3859        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3860            if (requireFullPermission) {
3861                mContext.enforceCallingOrSelfPermission(
3862                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3863            } else {
3864                try {
3865                    mContext.enforceCallingOrSelfPermission(
3866                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3867                } catch (SecurityException se) {
3868                    mContext.enforceCallingOrSelfPermission(
3869                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3870                }
3871            }
3872        }
3873    }
3874
3875    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3876        if (callingUid == Process.SHELL_UID) {
3877            if (userHandle >= 0
3878                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3879                throw new SecurityException("Shell does not have permission to access user "
3880                        + userHandle);
3881            } else if (userHandle < 0) {
3882                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3883                        + Debug.getCallers(3));
3884            }
3885        }
3886    }
3887
3888    private BasePermission findPermissionTreeLP(String permName) {
3889        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3890            if (permName.startsWith(bp.name) &&
3891                    permName.length() > bp.name.length() &&
3892                    permName.charAt(bp.name.length()) == '.') {
3893                return bp;
3894            }
3895        }
3896        return null;
3897    }
3898
3899    private BasePermission checkPermissionTreeLP(String permName) {
3900        if (permName != null) {
3901            BasePermission bp = findPermissionTreeLP(permName);
3902            if (bp != null) {
3903                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3904                    return bp;
3905                }
3906                throw new SecurityException("Calling uid "
3907                        + Binder.getCallingUid()
3908                        + " is not allowed to add to permission tree "
3909                        + bp.name + " owned by uid " + bp.uid);
3910            }
3911        }
3912        throw new SecurityException("No permission tree found for " + permName);
3913    }
3914
3915    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3916        if (s1 == null) {
3917            return s2 == null;
3918        }
3919        if (s2 == null) {
3920            return false;
3921        }
3922        if (s1.getClass() != s2.getClass()) {
3923            return false;
3924        }
3925        return s1.equals(s2);
3926    }
3927
3928    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3929        if (pi1.icon != pi2.icon) return false;
3930        if (pi1.logo != pi2.logo) return false;
3931        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3932        if (!compareStrings(pi1.name, pi2.name)) return false;
3933        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3934        // We'll take care of setting this one.
3935        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3936        // These are not currently stored in settings.
3937        //if (!compareStrings(pi1.group, pi2.group)) return false;
3938        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3939        //if (pi1.labelRes != pi2.labelRes) return false;
3940        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3941        return true;
3942    }
3943
3944    int permissionInfoFootprint(PermissionInfo info) {
3945        int size = info.name.length();
3946        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3947        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3948        return size;
3949    }
3950
3951    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3952        int size = 0;
3953        for (BasePermission perm : mSettings.mPermissions.values()) {
3954            if (perm.uid == tree.uid) {
3955                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3956            }
3957        }
3958        return size;
3959    }
3960
3961    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3962        // We calculate the max size of permissions defined by this uid and throw
3963        // if that plus the size of 'info' would exceed our stated maximum.
3964        if (tree.uid != Process.SYSTEM_UID) {
3965            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3966            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3967                throw new SecurityException("Permission tree size cap exceeded");
3968            }
3969        }
3970    }
3971
3972    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3973        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3974            throw new SecurityException("Label must be specified in permission");
3975        }
3976        BasePermission tree = checkPermissionTreeLP(info.name);
3977        BasePermission bp = mSettings.mPermissions.get(info.name);
3978        boolean added = bp == null;
3979        boolean changed = true;
3980        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3981        if (added) {
3982            enforcePermissionCapLocked(info, tree);
3983            bp = new BasePermission(info.name, tree.sourcePackage,
3984                    BasePermission.TYPE_DYNAMIC);
3985        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3986            throw new SecurityException(
3987                    "Not allowed to modify non-dynamic permission "
3988                    + info.name);
3989        } else {
3990            if (bp.protectionLevel == fixedLevel
3991                    && bp.perm.owner.equals(tree.perm.owner)
3992                    && bp.uid == tree.uid
3993                    && comparePermissionInfos(bp.perm.info, info)) {
3994                changed = false;
3995            }
3996        }
3997        bp.protectionLevel = fixedLevel;
3998        info = new PermissionInfo(info);
3999        info.protectionLevel = fixedLevel;
4000        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4001        bp.perm.info.packageName = tree.perm.info.packageName;
4002        bp.uid = tree.uid;
4003        if (added) {
4004            mSettings.mPermissions.put(info.name, bp);
4005        }
4006        if (changed) {
4007            if (!async) {
4008                mSettings.writeLPr();
4009            } else {
4010                scheduleWriteSettingsLocked();
4011            }
4012        }
4013        return added;
4014    }
4015
4016    @Override
4017    public boolean addPermission(PermissionInfo info) {
4018        synchronized (mPackages) {
4019            return addPermissionLocked(info, false);
4020        }
4021    }
4022
4023    @Override
4024    public boolean addPermissionAsync(PermissionInfo info) {
4025        synchronized (mPackages) {
4026            return addPermissionLocked(info, true);
4027        }
4028    }
4029
4030    @Override
4031    public void removePermission(String name) {
4032        synchronized (mPackages) {
4033            checkPermissionTreeLP(name);
4034            BasePermission bp = mSettings.mPermissions.get(name);
4035            if (bp != null) {
4036                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4037                    throw new SecurityException(
4038                            "Not allowed to modify non-dynamic permission "
4039                            + name);
4040                }
4041                mSettings.mPermissions.remove(name);
4042                mSettings.writeLPr();
4043            }
4044        }
4045    }
4046
4047    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4048            BasePermission bp) {
4049        int index = pkg.requestedPermissions.indexOf(bp.name);
4050        if (index == -1) {
4051            throw new SecurityException("Package " + pkg.packageName
4052                    + " has not requested permission " + bp.name);
4053        }
4054        if (!bp.isRuntime() && !bp.isDevelopment()) {
4055            throw new SecurityException("Permission " + bp.name
4056                    + " is not a changeable permission type");
4057        }
4058    }
4059
4060    @Override
4061    public void grantRuntimePermission(String packageName, String name, final int userId) {
4062        if (!sUserManager.exists(userId)) {
4063            Log.e(TAG, "No such user:" + userId);
4064            return;
4065        }
4066
4067        mContext.enforceCallingOrSelfPermission(
4068                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4069                "grantRuntimePermission");
4070
4071        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4072                true /* requireFullPermission */, true /* checkShell */,
4073                "grantRuntimePermission");
4074
4075        final int uid;
4076        final SettingBase sb;
4077
4078        synchronized (mPackages) {
4079            final PackageParser.Package pkg = mPackages.get(packageName);
4080            if (pkg == null) {
4081                throw new IllegalArgumentException("Unknown package: " + packageName);
4082            }
4083
4084            final BasePermission bp = mSettings.mPermissions.get(name);
4085            if (bp == null) {
4086                throw new IllegalArgumentException("Unknown permission: " + name);
4087            }
4088
4089            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4090
4091            // If a permission review is required for legacy apps we represent
4092            // their permissions as always granted runtime ones since we need
4093            // to keep the review required permission flag per user while an
4094            // install permission's state is shared across all users.
4095            if (Build.PERMISSIONS_REVIEW_REQUIRED
4096                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4097                    && bp.isRuntime()) {
4098                return;
4099            }
4100
4101            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4102            sb = (SettingBase) pkg.mExtras;
4103            if (sb == null) {
4104                throw new IllegalArgumentException("Unknown package: " + packageName);
4105            }
4106
4107            final PermissionsState permissionsState = sb.getPermissionsState();
4108
4109            final int flags = permissionsState.getPermissionFlags(name, userId);
4110            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4111                throw new SecurityException("Cannot grant system fixed permission "
4112                        + name + " for package " + packageName);
4113            }
4114
4115            if (bp.isDevelopment()) {
4116                // Development permissions must be handled specially, since they are not
4117                // normal runtime permissions.  For now they apply to all users.
4118                if (permissionsState.grantInstallPermission(bp) !=
4119                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4120                    scheduleWriteSettingsLocked();
4121                }
4122                return;
4123            }
4124
4125            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4126                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4127                return;
4128            }
4129
4130            final int result = permissionsState.grantRuntimePermission(bp, userId);
4131            switch (result) {
4132                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4133                    return;
4134                }
4135
4136                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4137                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4138                    mHandler.post(new Runnable() {
4139                        @Override
4140                        public void run() {
4141                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4142                        }
4143                    });
4144                }
4145                break;
4146            }
4147
4148            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4149
4150            // Not critical if that is lost - app has to request again.
4151            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4152        }
4153
4154        // Only need to do this if user is initialized. Otherwise it's a new user
4155        // and there are no processes running as the user yet and there's no need
4156        // to make an expensive call to remount processes for the changed permissions.
4157        if (READ_EXTERNAL_STORAGE.equals(name)
4158                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4159            final long token = Binder.clearCallingIdentity();
4160            try {
4161                if (sUserManager.isInitialized(userId)) {
4162                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4163                            MountServiceInternal.class);
4164                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4165                }
4166            } finally {
4167                Binder.restoreCallingIdentity(token);
4168            }
4169        }
4170    }
4171
4172    @Override
4173    public void revokeRuntimePermission(String packageName, String name, int userId) {
4174        if (!sUserManager.exists(userId)) {
4175            Log.e(TAG, "No such user:" + userId);
4176            return;
4177        }
4178
4179        mContext.enforceCallingOrSelfPermission(
4180                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4181                "revokeRuntimePermission");
4182
4183        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4184                true /* requireFullPermission */, true /* checkShell */,
4185                "revokeRuntimePermission");
4186
4187        final int appId;
4188
4189        synchronized (mPackages) {
4190            final PackageParser.Package pkg = mPackages.get(packageName);
4191            if (pkg == null) {
4192                throw new IllegalArgumentException("Unknown package: " + packageName);
4193            }
4194
4195            final BasePermission bp = mSettings.mPermissions.get(name);
4196            if (bp == null) {
4197                throw new IllegalArgumentException("Unknown permission: " + name);
4198            }
4199
4200            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4201
4202            // If a permission review is required for legacy apps we represent
4203            // their permissions as always granted runtime ones since we need
4204            // to keep the review required permission flag per user while an
4205            // install permission's state is shared across all users.
4206            if (Build.PERMISSIONS_REVIEW_REQUIRED
4207                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4208                    && bp.isRuntime()) {
4209                return;
4210            }
4211
4212            SettingBase sb = (SettingBase) pkg.mExtras;
4213            if (sb == null) {
4214                throw new IllegalArgumentException("Unknown package: " + packageName);
4215            }
4216
4217            final PermissionsState permissionsState = sb.getPermissionsState();
4218
4219            final int flags = permissionsState.getPermissionFlags(name, userId);
4220            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4221                throw new SecurityException("Cannot revoke system fixed permission "
4222                        + name + " for package " + packageName);
4223            }
4224
4225            if (bp.isDevelopment()) {
4226                // Development permissions must be handled specially, since they are not
4227                // normal runtime permissions.  For now they apply to all users.
4228                if (permissionsState.revokeInstallPermission(bp) !=
4229                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4230                    scheduleWriteSettingsLocked();
4231                }
4232                return;
4233            }
4234
4235            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4236                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4237                return;
4238            }
4239
4240            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4241
4242            // Critical, after this call app should never have the permission.
4243            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4244
4245            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4246        }
4247
4248        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4249    }
4250
4251    @Override
4252    public void resetRuntimePermissions() {
4253        mContext.enforceCallingOrSelfPermission(
4254                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4255                "revokeRuntimePermission");
4256
4257        int callingUid = Binder.getCallingUid();
4258        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4259            mContext.enforceCallingOrSelfPermission(
4260                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4261                    "resetRuntimePermissions");
4262        }
4263
4264        synchronized (mPackages) {
4265            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4266            for (int userId : UserManagerService.getInstance().getUserIds()) {
4267                final int packageCount = mPackages.size();
4268                for (int i = 0; i < packageCount; i++) {
4269                    PackageParser.Package pkg = mPackages.valueAt(i);
4270                    if (!(pkg.mExtras instanceof PackageSetting)) {
4271                        continue;
4272                    }
4273                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4274                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4275                }
4276            }
4277        }
4278    }
4279
4280    @Override
4281    public int getPermissionFlags(String name, String packageName, int userId) {
4282        if (!sUserManager.exists(userId)) {
4283            return 0;
4284        }
4285
4286        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4287
4288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4289                true /* requireFullPermission */, false /* checkShell */,
4290                "getPermissionFlags");
4291
4292        synchronized (mPackages) {
4293            final PackageParser.Package pkg = mPackages.get(packageName);
4294            if (pkg == null) {
4295                return 0;
4296            }
4297
4298            final BasePermission bp = mSettings.mPermissions.get(name);
4299            if (bp == null) {
4300                return 0;
4301            }
4302
4303            SettingBase sb = (SettingBase) pkg.mExtras;
4304            if (sb == null) {
4305                return 0;
4306            }
4307
4308            PermissionsState permissionsState = sb.getPermissionsState();
4309            return permissionsState.getPermissionFlags(name, userId);
4310        }
4311    }
4312
4313    @Override
4314    public void updatePermissionFlags(String name, String packageName, int flagMask,
4315            int flagValues, int userId) {
4316        if (!sUserManager.exists(userId)) {
4317            return;
4318        }
4319
4320        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4321
4322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4323                true /* requireFullPermission */, true /* checkShell */,
4324                "updatePermissionFlags");
4325
4326        // Only the system can change these flags and nothing else.
4327        if (getCallingUid() != Process.SYSTEM_UID) {
4328            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4329            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4330            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4331            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4332            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4333        }
4334
4335        synchronized (mPackages) {
4336            final PackageParser.Package pkg = mPackages.get(packageName);
4337            if (pkg == null) {
4338                throw new IllegalArgumentException("Unknown package: " + packageName);
4339            }
4340
4341            final BasePermission bp = mSettings.mPermissions.get(name);
4342            if (bp == null) {
4343                throw new IllegalArgumentException("Unknown permission: " + name);
4344            }
4345
4346            SettingBase sb = (SettingBase) pkg.mExtras;
4347            if (sb == null) {
4348                throw new IllegalArgumentException("Unknown package: " + packageName);
4349            }
4350
4351            PermissionsState permissionsState = sb.getPermissionsState();
4352
4353            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4354
4355            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4356                // Install and runtime permissions are stored in different places,
4357                // so figure out what permission changed and persist the change.
4358                if (permissionsState.getInstallPermissionState(name) != null) {
4359                    scheduleWriteSettingsLocked();
4360                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4361                        || hadState) {
4362                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4363                }
4364            }
4365        }
4366    }
4367
4368    /**
4369     * Update the permission flags for all packages and runtime permissions of a user in order
4370     * to allow device or profile owner to remove POLICY_FIXED.
4371     */
4372    @Override
4373    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4374        if (!sUserManager.exists(userId)) {
4375            return;
4376        }
4377
4378        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4379
4380        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4381                true /* requireFullPermission */, true /* checkShell */,
4382                "updatePermissionFlagsForAllApps");
4383
4384        // Only the system can change system fixed flags.
4385        if (getCallingUid() != Process.SYSTEM_UID) {
4386            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4387            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4388        }
4389
4390        synchronized (mPackages) {
4391            boolean changed = false;
4392            final int packageCount = mPackages.size();
4393            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4394                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4395                SettingBase sb = (SettingBase) pkg.mExtras;
4396                if (sb == null) {
4397                    continue;
4398                }
4399                PermissionsState permissionsState = sb.getPermissionsState();
4400                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4401                        userId, flagMask, flagValues);
4402            }
4403            if (changed) {
4404                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4405            }
4406        }
4407    }
4408
4409    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4410        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4411                != PackageManager.PERMISSION_GRANTED
4412            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4413                != PackageManager.PERMISSION_GRANTED) {
4414            throw new SecurityException(message + " requires "
4415                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4416                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4417        }
4418    }
4419
4420    @Override
4421    public boolean shouldShowRequestPermissionRationale(String permissionName,
4422            String packageName, int userId) {
4423        if (UserHandle.getCallingUserId() != userId) {
4424            mContext.enforceCallingPermission(
4425                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4426                    "canShowRequestPermissionRationale for user " + userId);
4427        }
4428
4429        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4430        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4431            return false;
4432        }
4433
4434        if (checkPermission(permissionName, packageName, userId)
4435                == PackageManager.PERMISSION_GRANTED) {
4436            return false;
4437        }
4438
4439        final int flags;
4440
4441        final long identity = Binder.clearCallingIdentity();
4442        try {
4443            flags = getPermissionFlags(permissionName,
4444                    packageName, userId);
4445        } finally {
4446            Binder.restoreCallingIdentity(identity);
4447        }
4448
4449        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4450                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4451                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4452
4453        if ((flags & fixedFlags) != 0) {
4454            return false;
4455        }
4456
4457        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4458    }
4459
4460    @Override
4461    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4462        mContext.enforceCallingOrSelfPermission(
4463                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4464                "addOnPermissionsChangeListener");
4465
4466        synchronized (mPackages) {
4467            mOnPermissionChangeListeners.addListenerLocked(listener);
4468        }
4469    }
4470
4471    @Override
4472    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4473        synchronized (mPackages) {
4474            mOnPermissionChangeListeners.removeListenerLocked(listener);
4475        }
4476    }
4477
4478    @Override
4479    public boolean isProtectedBroadcast(String actionName) {
4480        synchronized (mPackages) {
4481            if (mProtectedBroadcasts.contains(actionName)) {
4482                return true;
4483            } else if (actionName != null) {
4484                // TODO: remove these terrible hacks
4485                if (actionName.startsWith("android.net.netmon.lingerExpired")
4486                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4487                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4488                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4489                    return true;
4490                }
4491            }
4492        }
4493        return false;
4494    }
4495
4496    @Override
4497    public int checkSignatures(String pkg1, String pkg2) {
4498        synchronized (mPackages) {
4499            final PackageParser.Package p1 = mPackages.get(pkg1);
4500            final PackageParser.Package p2 = mPackages.get(pkg2);
4501            if (p1 == null || p1.mExtras == null
4502                    || p2 == null || p2.mExtras == null) {
4503                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4504            }
4505            return compareSignatures(p1.mSignatures, p2.mSignatures);
4506        }
4507    }
4508
4509    @Override
4510    public int checkUidSignatures(int uid1, int uid2) {
4511        // Map to base uids.
4512        uid1 = UserHandle.getAppId(uid1);
4513        uid2 = UserHandle.getAppId(uid2);
4514        // reader
4515        synchronized (mPackages) {
4516            Signature[] s1;
4517            Signature[] s2;
4518            Object obj = mSettings.getUserIdLPr(uid1);
4519            if (obj != null) {
4520                if (obj instanceof SharedUserSetting) {
4521                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4522                } else if (obj instanceof PackageSetting) {
4523                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4524                } else {
4525                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4526                }
4527            } else {
4528                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4529            }
4530            obj = mSettings.getUserIdLPr(uid2);
4531            if (obj != null) {
4532                if (obj instanceof SharedUserSetting) {
4533                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4534                } else if (obj instanceof PackageSetting) {
4535                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4536                } else {
4537                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4538                }
4539            } else {
4540                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4541            }
4542            return compareSignatures(s1, s2);
4543        }
4544    }
4545
4546    /**
4547     * This method should typically only be used when granting or revoking
4548     * permissions, since the app may immediately restart after this call.
4549     * <p>
4550     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4551     * guard your work against the app being relaunched.
4552     */
4553    private void killUid(int appId, int userId, String reason) {
4554        final long identity = Binder.clearCallingIdentity();
4555        try {
4556            IActivityManager am = ActivityManagerNative.getDefault();
4557            if (am != null) {
4558                try {
4559                    am.killUid(appId, userId, reason);
4560                } catch (RemoteException e) {
4561                    /* ignore - same process */
4562                }
4563            }
4564        } finally {
4565            Binder.restoreCallingIdentity(identity);
4566        }
4567    }
4568
4569    /**
4570     * Compares two sets of signatures. Returns:
4571     * <br />
4572     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4573     * <br />
4574     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4575     * <br />
4576     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4577     * <br />
4578     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4579     * <br />
4580     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4581     */
4582    static int compareSignatures(Signature[] s1, Signature[] s2) {
4583        if (s1 == null) {
4584            return s2 == null
4585                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4586                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4587        }
4588
4589        if (s2 == null) {
4590            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4591        }
4592
4593        if (s1.length != s2.length) {
4594            return PackageManager.SIGNATURE_NO_MATCH;
4595        }
4596
4597        // Since both signature sets are of size 1, we can compare without HashSets.
4598        if (s1.length == 1) {
4599            return s1[0].equals(s2[0]) ?
4600                    PackageManager.SIGNATURE_MATCH :
4601                    PackageManager.SIGNATURE_NO_MATCH;
4602        }
4603
4604        ArraySet<Signature> set1 = new ArraySet<Signature>();
4605        for (Signature sig : s1) {
4606            set1.add(sig);
4607        }
4608        ArraySet<Signature> set2 = new ArraySet<Signature>();
4609        for (Signature sig : s2) {
4610            set2.add(sig);
4611        }
4612        // Make sure s2 contains all signatures in s1.
4613        if (set1.equals(set2)) {
4614            return PackageManager.SIGNATURE_MATCH;
4615        }
4616        return PackageManager.SIGNATURE_NO_MATCH;
4617    }
4618
4619    /**
4620     * If the database version for this type of package (internal storage or
4621     * external storage) is less than the version where package signatures
4622     * were updated, return true.
4623     */
4624    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4625        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4626        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4627    }
4628
4629    /**
4630     * Used for backward compatibility to make sure any packages with
4631     * certificate chains get upgraded to the new style. {@code existingSigs}
4632     * will be in the old format (since they were stored on disk from before the
4633     * system upgrade) and {@code scannedSigs} will be in the newer format.
4634     */
4635    private int compareSignaturesCompat(PackageSignatures existingSigs,
4636            PackageParser.Package scannedPkg) {
4637        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4638            return PackageManager.SIGNATURE_NO_MATCH;
4639        }
4640
4641        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4642        for (Signature sig : existingSigs.mSignatures) {
4643            existingSet.add(sig);
4644        }
4645        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4646        for (Signature sig : scannedPkg.mSignatures) {
4647            try {
4648                Signature[] chainSignatures = sig.getChainSignatures();
4649                for (Signature chainSig : chainSignatures) {
4650                    scannedCompatSet.add(chainSig);
4651                }
4652            } catch (CertificateEncodingException e) {
4653                scannedCompatSet.add(sig);
4654            }
4655        }
4656        /*
4657         * Make sure the expanded scanned set contains all signatures in the
4658         * existing one.
4659         */
4660        if (scannedCompatSet.equals(existingSet)) {
4661            // Migrate the old signatures to the new scheme.
4662            existingSigs.assignSignatures(scannedPkg.mSignatures);
4663            // The new KeySets will be re-added later in the scanning process.
4664            synchronized (mPackages) {
4665                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4666            }
4667            return PackageManager.SIGNATURE_MATCH;
4668        }
4669        return PackageManager.SIGNATURE_NO_MATCH;
4670    }
4671
4672    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4673        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4674        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4675    }
4676
4677    private int compareSignaturesRecover(PackageSignatures existingSigs,
4678            PackageParser.Package scannedPkg) {
4679        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4680            return PackageManager.SIGNATURE_NO_MATCH;
4681        }
4682
4683        String msg = null;
4684        try {
4685            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4686                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4687                        + scannedPkg.packageName);
4688                return PackageManager.SIGNATURE_MATCH;
4689            }
4690        } catch (CertificateException e) {
4691            msg = e.getMessage();
4692        }
4693
4694        logCriticalInfo(Log.INFO,
4695                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4696        return PackageManager.SIGNATURE_NO_MATCH;
4697    }
4698
4699    @Override
4700    public List<String> getAllPackages() {
4701        synchronized (mPackages) {
4702            return new ArrayList<String>(mPackages.keySet());
4703        }
4704    }
4705
4706    @Override
4707    public String[] getPackagesForUid(int uid) {
4708        uid = UserHandle.getAppId(uid);
4709        // reader
4710        synchronized (mPackages) {
4711            Object obj = mSettings.getUserIdLPr(uid);
4712            if (obj instanceof SharedUserSetting) {
4713                final SharedUserSetting sus = (SharedUserSetting) obj;
4714                final int N = sus.packages.size();
4715                final String[] res = new String[N];
4716                final Iterator<PackageSetting> it = sus.packages.iterator();
4717                int i = 0;
4718                while (it.hasNext()) {
4719                    res[i++] = it.next().name;
4720                }
4721                return res;
4722            } else if (obj instanceof PackageSetting) {
4723                final PackageSetting ps = (PackageSetting) obj;
4724                return new String[] { ps.name };
4725            }
4726        }
4727        return null;
4728    }
4729
4730    @Override
4731    public String getNameForUid(int uid) {
4732        // reader
4733        synchronized (mPackages) {
4734            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4735            if (obj instanceof SharedUserSetting) {
4736                final SharedUserSetting sus = (SharedUserSetting) obj;
4737                return sus.name + ":" + sus.userId;
4738            } else if (obj instanceof PackageSetting) {
4739                final PackageSetting ps = (PackageSetting) obj;
4740                return ps.name;
4741            }
4742        }
4743        return null;
4744    }
4745
4746    @Override
4747    public int getUidForSharedUser(String sharedUserName) {
4748        if(sharedUserName == null) {
4749            return -1;
4750        }
4751        // reader
4752        synchronized (mPackages) {
4753            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4754            if (suid == null) {
4755                return -1;
4756            }
4757            return suid.userId;
4758        }
4759    }
4760
4761    @Override
4762    public int getFlagsForUid(int uid) {
4763        synchronized (mPackages) {
4764            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4765            if (obj instanceof SharedUserSetting) {
4766                final SharedUserSetting sus = (SharedUserSetting) obj;
4767                return sus.pkgFlags;
4768            } else if (obj instanceof PackageSetting) {
4769                final PackageSetting ps = (PackageSetting) obj;
4770                return ps.pkgFlags;
4771            }
4772        }
4773        return 0;
4774    }
4775
4776    @Override
4777    public int getPrivateFlagsForUid(int uid) {
4778        synchronized (mPackages) {
4779            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4780            if (obj instanceof SharedUserSetting) {
4781                final SharedUserSetting sus = (SharedUserSetting) obj;
4782                return sus.pkgPrivateFlags;
4783            } else if (obj instanceof PackageSetting) {
4784                final PackageSetting ps = (PackageSetting) obj;
4785                return ps.pkgPrivateFlags;
4786            }
4787        }
4788        return 0;
4789    }
4790
4791    @Override
4792    public boolean isUidPrivileged(int uid) {
4793        uid = UserHandle.getAppId(uid);
4794        // reader
4795        synchronized (mPackages) {
4796            Object obj = mSettings.getUserIdLPr(uid);
4797            if (obj instanceof SharedUserSetting) {
4798                final SharedUserSetting sus = (SharedUserSetting) obj;
4799                final Iterator<PackageSetting> it = sus.packages.iterator();
4800                while (it.hasNext()) {
4801                    if (it.next().isPrivileged()) {
4802                        return true;
4803                    }
4804                }
4805            } else if (obj instanceof PackageSetting) {
4806                final PackageSetting ps = (PackageSetting) obj;
4807                return ps.isPrivileged();
4808            }
4809        }
4810        return false;
4811    }
4812
4813    @Override
4814    public String[] getAppOpPermissionPackages(String permissionName) {
4815        synchronized (mPackages) {
4816            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4817            if (pkgs == null) {
4818                return null;
4819            }
4820            return pkgs.toArray(new String[pkgs.size()]);
4821        }
4822    }
4823
4824    @Override
4825    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4826            int flags, int userId) {
4827        try {
4828            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4829
4830            if (!sUserManager.exists(userId)) return null;
4831            flags = updateFlagsForResolve(flags, userId, intent);
4832            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4833                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4834
4835            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4836            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4837                    flags, userId);
4838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4839
4840            final ResolveInfo bestChoice =
4841                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4842
4843            if (isEphemeralAllowed(intent, query, userId)) {
4844                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4845                final EphemeralResolveInfo ai =
4846                        getEphemeralResolveInfo(intent, resolvedType, userId);
4847                if (ai != null) {
4848                    if (DEBUG_EPHEMERAL) {
4849                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4850                    }
4851                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4852                    bestChoice.ephemeralResolveInfo = ai;
4853                }
4854                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4855            }
4856            return bestChoice;
4857        } finally {
4858            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4859        }
4860    }
4861
4862    @Override
4863    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4864            IntentFilter filter, int match, ComponentName activity) {
4865        final int userId = UserHandle.getCallingUserId();
4866        if (DEBUG_PREFERRED) {
4867            Log.v(TAG, "setLastChosenActivity intent=" + intent
4868                + " resolvedType=" + resolvedType
4869                + " flags=" + flags
4870                + " filter=" + filter
4871                + " match=" + match
4872                + " activity=" + activity);
4873            filter.dump(new PrintStreamPrinter(System.out), "    ");
4874        }
4875        intent.setComponent(null);
4876        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4877                userId);
4878        // Find any earlier preferred or last chosen entries and nuke them
4879        findPreferredActivity(intent, resolvedType,
4880                flags, query, 0, false, true, false, userId);
4881        // Add the new activity as the last chosen for this filter
4882        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4883                "Setting last chosen");
4884    }
4885
4886    @Override
4887    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4888        final int userId = UserHandle.getCallingUserId();
4889        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4890        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4891                userId);
4892        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4893                false, false, false, userId);
4894    }
4895
4896
4897    private boolean isEphemeralAllowed(
4898            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4899        // Short circuit and return early if possible.
4900        if (DISABLE_EPHEMERAL_APPS) {
4901            return false;
4902        }
4903        final int callingUser = UserHandle.getCallingUserId();
4904        if (callingUser != UserHandle.USER_SYSTEM) {
4905            return false;
4906        }
4907        if (mEphemeralResolverConnection == null) {
4908            return false;
4909        }
4910        if (intent.getComponent() != null) {
4911            return false;
4912        }
4913        if (intent.getPackage() != null) {
4914            return false;
4915        }
4916        final boolean isWebUri = hasWebURI(intent);
4917        if (!isWebUri) {
4918            return false;
4919        }
4920        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4921        synchronized (mPackages) {
4922            final int count = resolvedActivites.size();
4923            for (int n = 0; n < count; n++) {
4924                ResolveInfo info = resolvedActivites.get(n);
4925                String packageName = info.activityInfo.packageName;
4926                PackageSetting ps = mSettings.mPackages.get(packageName);
4927                if (ps != null) {
4928                    // Try to get the status from User settings first
4929                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4930                    int status = (int) (packedStatus >> 32);
4931                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4932                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4933                        if (DEBUG_EPHEMERAL) {
4934                            Slog.v(TAG, "DENY ephemeral apps;"
4935                                + " pkg: " + packageName + ", status: " + status);
4936                        }
4937                        return false;
4938                    }
4939                }
4940            }
4941        }
4942        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4943        return true;
4944    }
4945
4946    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4947            int userId) {
4948        MessageDigest digest = null;
4949        try {
4950            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4951        } catch (NoSuchAlgorithmException e) {
4952            // If we can't create a digest, ignore ephemeral apps.
4953            return null;
4954        }
4955
4956        final byte[] hostBytes = intent.getData().getHost().getBytes();
4957        final byte[] digestBytes = digest.digest(hostBytes);
4958        int shaPrefix =
4959                digestBytes[0] << 24
4960                | digestBytes[1] << 16
4961                | digestBytes[2] << 8
4962                | digestBytes[3] << 0;
4963        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4964                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4965        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4966            // No hash prefix match; there are no ephemeral apps for this domain.
4967            return null;
4968        }
4969        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4970            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4971            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4972                continue;
4973            }
4974            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4975            // No filters; this should never happen.
4976            if (filters.isEmpty()) {
4977                continue;
4978            }
4979            // We have a domain match; resolve the filters to see if anything matches.
4980            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4981            for (int j = filters.size() - 1; j >= 0; --j) {
4982                final EphemeralResolveIntentInfo intentInfo =
4983                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4984                ephemeralResolver.addFilter(intentInfo);
4985            }
4986            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4987                    intent, resolvedType, false /*defaultOnly*/, userId);
4988            if (!matchedResolveInfoList.isEmpty()) {
4989                return matchedResolveInfoList.get(0);
4990            }
4991        }
4992        // Hash or filter mis-match; no ephemeral apps for this domain.
4993        return null;
4994    }
4995
4996    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4997            int flags, List<ResolveInfo> query, int userId) {
4998        if (query != null) {
4999            final int N = query.size();
5000            if (N == 1) {
5001                return query.get(0);
5002            } else if (N > 1) {
5003                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5004                // If there is more than one activity with the same priority,
5005                // then let the user decide between them.
5006                ResolveInfo r0 = query.get(0);
5007                ResolveInfo r1 = query.get(1);
5008                if (DEBUG_INTENT_MATCHING || debug) {
5009                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5010                            + r1.activityInfo.name + "=" + r1.priority);
5011                }
5012                // If the first activity has a higher priority, or a different
5013                // default, then it is always desirable to pick it.
5014                if (r0.priority != r1.priority
5015                        || r0.preferredOrder != r1.preferredOrder
5016                        || r0.isDefault != r1.isDefault) {
5017                    return query.get(0);
5018                }
5019                // If we have saved a preference for a preferred activity for
5020                // this Intent, use that.
5021                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5022                        flags, query, r0.priority, true, false, debug, userId);
5023                if (ri != null) {
5024                    return ri;
5025                }
5026                ri = new ResolveInfo(mResolveInfo);
5027                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5028                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5029                // If all of the options come from the same package, show the application's
5030                // label and icon instead of the generic resolver's.
5031                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5032                // and then throw away the ResolveInfo itself, meaning that the caller loses
5033                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5034                // a fallback for this case; we only set the target package's resources on
5035                // the ResolveInfo, not the ActivityInfo.
5036                final String intentPackage = intent.getPackage();
5037                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5038                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5039                    ri.resolvePackageName = intentPackage;
5040                    if (userNeedsBadging(userId)) {
5041                        ri.noResourceId = true;
5042                    } else {
5043                        ri.icon = appi.icon;
5044                    }
5045                    ri.iconResourceId = appi.icon;
5046                    ri.labelRes = appi.labelRes;
5047                }
5048                ri.activityInfo.applicationInfo = new ApplicationInfo(
5049                        ri.activityInfo.applicationInfo);
5050                if (userId != 0) {
5051                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5052                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5053                }
5054                // Make sure that the resolver is displayable in car mode
5055                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5056                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5057                return ri;
5058            }
5059        }
5060        return null;
5061    }
5062
5063    /**
5064     * Return true if the given list is not empty and all of its contents have
5065     * an activityInfo with the given package name.
5066     */
5067    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5068        if (ArrayUtils.isEmpty(list)) {
5069            return false;
5070        }
5071        for (int i = 0, N = list.size(); i < N; i++) {
5072            final ResolveInfo ri = list.get(i);
5073            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5074            if (ai == null || !packageName.equals(ai.packageName)) {
5075                return false;
5076            }
5077        }
5078        return true;
5079    }
5080
5081    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5082            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5083        final int N = query.size();
5084        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5085                .get(userId);
5086        // Get the list of persistent preferred activities that handle the intent
5087        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5088        List<PersistentPreferredActivity> pprefs = ppir != null
5089                ? ppir.queryIntent(intent, resolvedType,
5090                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5091                : null;
5092        if (pprefs != null && pprefs.size() > 0) {
5093            final int M = pprefs.size();
5094            for (int i=0; i<M; i++) {
5095                final PersistentPreferredActivity ppa = pprefs.get(i);
5096                if (DEBUG_PREFERRED || debug) {
5097                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5098                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5099                            + "\n  component=" + ppa.mComponent);
5100                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5101                }
5102                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5103                        flags | MATCH_DISABLED_COMPONENTS, userId);
5104                if (DEBUG_PREFERRED || debug) {
5105                    Slog.v(TAG, "Found persistent preferred activity:");
5106                    if (ai != null) {
5107                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5108                    } else {
5109                        Slog.v(TAG, "  null");
5110                    }
5111                }
5112                if (ai == null) {
5113                    // This previously registered persistent preferred activity
5114                    // component is no longer known. Ignore it and do NOT remove it.
5115                    continue;
5116                }
5117                for (int j=0; j<N; j++) {
5118                    final ResolveInfo ri = query.get(j);
5119                    if (!ri.activityInfo.applicationInfo.packageName
5120                            .equals(ai.applicationInfo.packageName)) {
5121                        continue;
5122                    }
5123                    if (!ri.activityInfo.name.equals(ai.name)) {
5124                        continue;
5125                    }
5126                    //  Found a persistent preference that can handle the intent.
5127                    if (DEBUG_PREFERRED || debug) {
5128                        Slog.v(TAG, "Returning persistent preferred activity: " +
5129                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5130                    }
5131                    return ri;
5132                }
5133            }
5134        }
5135        return null;
5136    }
5137
5138    // TODO: handle preferred activities missing while user has amnesia
5139    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5140            List<ResolveInfo> query, int priority, boolean always,
5141            boolean removeMatches, boolean debug, int userId) {
5142        if (!sUserManager.exists(userId)) return null;
5143        flags = updateFlagsForResolve(flags, userId, intent);
5144        // writer
5145        synchronized (mPackages) {
5146            if (intent.getSelector() != null) {
5147                intent = intent.getSelector();
5148            }
5149            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5150
5151            // Try to find a matching persistent preferred activity.
5152            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5153                    debug, userId);
5154
5155            // If a persistent preferred activity matched, use it.
5156            if (pri != null) {
5157                return pri;
5158            }
5159
5160            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5161            // Get the list of preferred activities that handle the intent
5162            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5163            List<PreferredActivity> prefs = pir != null
5164                    ? pir.queryIntent(intent, resolvedType,
5165                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5166                    : null;
5167            if (prefs != null && prefs.size() > 0) {
5168                boolean changed = false;
5169                try {
5170                    // First figure out how good the original match set is.
5171                    // We will only allow preferred activities that came
5172                    // from the same match quality.
5173                    int match = 0;
5174
5175                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5176
5177                    final int N = query.size();
5178                    for (int j=0; j<N; j++) {
5179                        final ResolveInfo ri = query.get(j);
5180                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5181                                + ": 0x" + Integer.toHexString(match));
5182                        if (ri.match > match) {
5183                            match = ri.match;
5184                        }
5185                    }
5186
5187                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5188                            + Integer.toHexString(match));
5189
5190                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5191                    final int M = prefs.size();
5192                    for (int i=0; i<M; i++) {
5193                        final PreferredActivity pa = prefs.get(i);
5194                        if (DEBUG_PREFERRED || debug) {
5195                            Slog.v(TAG, "Checking PreferredActivity ds="
5196                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5197                                    + "\n  component=" + pa.mPref.mComponent);
5198                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5199                        }
5200                        if (pa.mPref.mMatch != match) {
5201                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5202                                    + Integer.toHexString(pa.mPref.mMatch));
5203                            continue;
5204                        }
5205                        // If it's not an "always" type preferred activity and that's what we're
5206                        // looking for, skip it.
5207                        if (always && !pa.mPref.mAlways) {
5208                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5209                            continue;
5210                        }
5211                        final ActivityInfo ai = getActivityInfo(
5212                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5213                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5214                                userId);
5215                        if (DEBUG_PREFERRED || debug) {
5216                            Slog.v(TAG, "Found preferred activity:");
5217                            if (ai != null) {
5218                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5219                            } else {
5220                                Slog.v(TAG, "  null");
5221                            }
5222                        }
5223                        if (ai == null) {
5224                            // This previously registered preferred activity
5225                            // component is no longer known.  Most likely an update
5226                            // to the app was installed and in the new version this
5227                            // component no longer exists.  Clean it up by removing
5228                            // it from the preferred activities list, and skip it.
5229                            Slog.w(TAG, "Removing dangling preferred activity: "
5230                                    + pa.mPref.mComponent);
5231                            pir.removeFilter(pa);
5232                            changed = true;
5233                            continue;
5234                        }
5235                        for (int j=0; j<N; j++) {
5236                            final ResolveInfo ri = query.get(j);
5237                            if (!ri.activityInfo.applicationInfo.packageName
5238                                    .equals(ai.applicationInfo.packageName)) {
5239                                continue;
5240                            }
5241                            if (!ri.activityInfo.name.equals(ai.name)) {
5242                                continue;
5243                            }
5244
5245                            if (removeMatches) {
5246                                pir.removeFilter(pa);
5247                                changed = true;
5248                                if (DEBUG_PREFERRED) {
5249                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5250                                }
5251                                break;
5252                            }
5253
5254                            // Okay we found a previously set preferred or last chosen app.
5255                            // If the result set is different from when this
5256                            // was created, we need to clear it and re-ask the
5257                            // user their preference, if we're looking for an "always" type entry.
5258                            if (always && !pa.mPref.sameSet(query)) {
5259                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5260                                        + intent + " type " + resolvedType);
5261                                if (DEBUG_PREFERRED) {
5262                                    Slog.v(TAG, "Removing preferred activity since set changed "
5263                                            + pa.mPref.mComponent);
5264                                }
5265                                pir.removeFilter(pa);
5266                                // Re-add the filter as a "last chosen" entry (!always)
5267                                PreferredActivity lastChosen = new PreferredActivity(
5268                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5269                                pir.addFilter(lastChosen);
5270                                changed = true;
5271                                return null;
5272                            }
5273
5274                            // Yay! Either the set matched or we're looking for the last chosen
5275                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5276                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5277                            return ri;
5278                        }
5279                    }
5280                } finally {
5281                    if (changed) {
5282                        if (DEBUG_PREFERRED) {
5283                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5284                        }
5285                        scheduleWritePackageRestrictionsLocked(userId);
5286                    }
5287                }
5288            }
5289        }
5290        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5291        return null;
5292    }
5293
5294    /*
5295     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5296     */
5297    @Override
5298    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5299            int targetUserId) {
5300        mContext.enforceCallingOrSelfPermission(
5301                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5302        List<CrossProfileIntentFilter> matches =
5303                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5304        if (matches != null) {
5305            int size = matches.size();
5306            for (int i = 0; i < size; i++) {
5307                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5308            }
5309        }
5310        if (hasWebURI(intent)) {
5311            // cross-profile app linking works only towards the parent.
5312            final UserInfo parent = getProfileParent(sourceUserId);
5313            synchronized(mPackages) {
5314                int flags = updateFlagsForResolve(0, parent.id, intent);
5315                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5316                        intent, resolvedType, flags, sourceUserId, parent.id);
5317                return xpDomainInfo != null;
5318            }
5319        }
5320        return false;
5321    }
5322
5323    private UserInfo getProfileParent(int userId) {
5324        final long identity = Binder.clearCallingIdentity();
5325        try {
5326            return sUserManager.getProfileParent(userId);
5327        } finally {
5328            Binder.restoreCallingIdentity(identity);
5329        }
5330    }
5331
5332    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5333            String resolvedType, int userId) {
5334        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5335        if (resolver != null) {
5336            return resolver.queryIntent(intent, resolvedType, false, userId);
5337        }
5338        return null;
5339    }
5340
5341    @Override
5342    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5343            String resolvedType, int flags, int userId) {
5344        try {
5345            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5346
5347            return new ParceledListSlice<>(
5348                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5349        } finally {
5350            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5351        }
5352    }
5353
5354    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5355            String resolvedType, int flags, int userId) {
5356        if (!sUserManager.exists(userId)) return Collections.emptyList();
5357        flags = updateFlagsForResolve(flags, userId, intent);
5358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5359                false /* requireFullPermission */, false /* checkShell */,
5360                "query intent activities");
5361        ComponentName comp = intent.getComponent();
5362        if (comp == null) {
5363            if (intent.getSelector() != null) {
5364                intent = intent.getSelector();
5365                comp = intent.getComponent();
5366            }
5367        }
5368
5369        if (comp != null) {
5370            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5371            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5372            if (ai != null) {
5373                final ResolveInfo ri = new ResolveInfo();
5374                ri.activityInfo = ai;
5375                list.add(ri);
5376            }
5377            return list;
5378        }
5379
5380        // reader
5381        synchronized (mPackages) {
5382            final String pkgName = intent.getPackage();
5383            if (pkgName == null) {
5384                List<CrossProfileIntentFilter> matchingFilters =
5385                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5386                // Check for results that need to skip the current profile.
5387                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5388                        resolvedType, flags, userId);
5389                if (xpResolveInfo != null) {
5390                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5391                    result.add(xpResolveInfo);
5392                    return filterIfNotSystemUser(result, userId);
5393                }
5394
5395                // Check for results in the current profile.
5396                List<ResolveInfo> result = mActivities.queryIntent(
5397                        intent, resolvedType, flags, userId);
5398                result = filterIfNotSystemUser(result, userId);
5399
5400                // Check for cross profile results.
5401                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5402                xpResolveInfo = queryCrossProfileIntents(
5403                        matchingFilters, intent, resolvedType, flags, userId,
5404                        hasNonNegativePriorityResult);
5405                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5406                    boolean isVisibleToUser = filterIfNotSystemUser(
5407                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5408                    if (isVisibleToUser) {
5409                        result.add(xpResolveInfo);
5410                        Collections.sort(result, mResolvePrioritySorter);
5411                    }
5412                }
5413                if (hasWebURI(intent)) {
5414                    CrossProfileDomainInfo xpDomainInfo = null;
5415                    final UserInfo parent = getProfileParent(userId);
5416                    if (parent != null) {
5417                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5418                                flags, userId, parent.id);
5419                    }
5420                    if (xpDomainInfo != null) {
5421                        if (xpResolveInfo != null) {
5422                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5423                            // in the result.
5424                            result.remove(xpResolveInfo);
5425                        }
5426                        if (result.size() == 0) {
5427                            result.add(xpDomainInfo.resolveInfo);
5428                            return result;
5429                        }
5430                    } else if (result.size() <= 1) {
5431                        return result;
5432                    }
5433                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5434                            xpDomainInfo, userId);
5435                    Collections.sort(result, mResolvePrioritySorter);
5436                }
5437                return result;
5438            }
5439            final PackageParser.Package pkg = mPackages.get(pkgName);
5440            if (pkg != null) {
5441                return filterIfNotSystemUser(
5442                        mActivities.queryIntentForPackage(
5443                                intent, resolvedType, flags, pkg.activities, userId),
5444                        userId);
5445            }
5446            return new ArrayList<ResolveInfo>();
5447        }
5448    }
5449
5450    private static class CrossProfileDomainInfo {
5451        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5452        ResolveInfo resolveInfo;
5453        /* Best domain verification status of the activities found in the other profile */
5454        int bestDomainVerificationStatus;
5455    }
5456
5457    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5458            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5459        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5460                sourceUserId)) {
5461            return null;
5462        }
5463        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5464                resolvedType, flags, parentUserId);
5465
5466        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5467            return null;
5468        }
5469        CrossProfileDomainInfo result = null;
5470        int size = resultTargetUser.size();
5471        for (int i = 0; i < size; i++) {
5472            ResolveInfo riTargetUser = resultTargetUser.get(i);
5473            // Intent filter verification is only for filters that specify a host. So don't return
5474            // those that handle all web uris.
5475            if (riTargetUser.handleAllWebDataURI) {
5476                continue;
5477            }
5478            String packageName = riTargetUser.activityInfo.packageName;
5479            PackageSetting ps = mSettings.mPackages.get(packageName);
5480            if (ps == null) {
5481                continue;
5482            }
5483            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5484            int status = (int)(verificationState >> 32);
5485            if (result == null) {
5486                result = new CrossProfileDomainInfo();
5487                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5488                        sourceUserId, parentUserId);
5489                result.bestDomainVerificationStatus = status;
5490            } else {
5491                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5492                        result.bestDomainVerificationStatus);
5493            }
5494        }
5495        // Don't consider matches with status NEVER across profiles.
5496        if (result != null && result.bestDomainVerificationStatus
5497                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5498            return null;
5499        }
5500        return result;
5501    }
5502
5503    /**
5504     * Verification statuses are ordered from the worse to the best, except for
5505     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5506     */
5507    private int bestDomainVerificationStatus(int status1, int status2) {
5508        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5509            return status2;
5510        }
5511        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5512            return status1;
5513        }
5514        return (int) MathUtils.max(status1, status2);
5515    }
5516
5517    private boolean isUserEnabled(int userId) {
5518        long callingId = Binder.clearCallingIdentity();
5519        try {
5520            UserInfo userInfo = sUserManager.getUserInfo(userId);
5521            return userInfo != null && userInfo.isEnabled();
5522        } finally {
5523            Binder.restoreCallingIdentity(callingId);
5524        }
5525    }
5526
5527    /**
5528     * Filter out activities with systemUserOnly flag set, when current user is not System.
5529     *
5530     * @return filtered list
5531     */
5532    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5533        if (userId == UserHandle.USER_SYSTEM) {
5534            return resolveInfos;
5535        }
5536        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5537            ResolveInfo info = resolveInfos.get(i);
5538            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5539                resolveInfos.remove(i);
5540            }
5541        }
5542        return resolveInfos;
5543    }
5544
5545    /**
5546     * @param resolveInfos list of resolve infos in descending priority order
5547     * @return if the list contains a resolve info with non-negative priority
5548     */
5549    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5550        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5551    }
5552
5553    private static boolean hasWebURI(Intent intent) {
5554        if (intent.getData() == null) {
5555            return false;
5556        }
5557        final String scheme = intent.getScheme();
5558        if (TextUtils.isEmpty(scheme)) {
5559            return false;
5560        }
5561        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5562    }
5563
5564    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5565            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5566            int userId) {
5567        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5568
5569        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5570            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5571                    candidates.size());
5572        }
5573
5574        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5575        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5576        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5577        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5578        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5579        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5580
5581        synchronized (mPackages) {
5582            final int count = candidates.size();
5583            // First, try to use linked apps. Partition the candidates into four lists:
5584            // one for the final results, one for the "do not use ever", one for "undefined status"
5585            // and finally one for "browser app type".
5586            for (int n=0; n<count; n++) {
5587                ResolveInfo info = candidates.get(n);
5588                String packageName = info.activityInfo.packageName;
5589                PackageSetting ps = mSettings.mPackages.get(packageName);
5590                if (ps != null) {
5591                    // Add to the special match all list (Browser use case)
5592                    if (info.handleAllWebDataURI) {
5593                        matchAllList.add(info);
5594                        continue;
5595                    }
5596                    // Try to get the status from User settings first
5597                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5598                    int status = (int)(packedStatus >> 32);
5599                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5600                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5601                        if (DEBUG_DOMAIN_VERIFICATION) {
5602                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5603                                    + " : linkgen=" + linkGeneration);
5604                        }
5605                        // Use link-enabled generation as preferredOrder, i.e.
5606                        // prefer newly-enabled over earlier-enabled.
5607                        info.preferredOrder = linkGeneration;
5608                        alwaysList.add(info);
5609                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5610                        if (DEBUG_DOMAIN_VERIFICATION) {
5611                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5612                        }
5613                        neverList.add(info);
5614                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5615                        if (DEBUG_DOMAIN_VERIFICATION) {
5616                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5617                        }
5618                        alwaysAskList.add(info);
5619                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5620                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5621                        if (DEBUG_DOMAIN_VERIFICATION) {
5622                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5623                        }
5624                        undefinedList.add(info);
5625                    }
5626                }
5627            }
5628
5629            // We'll want to include browser possibilities in a few cases
5630            boolean includeBrowser = false;
5631
5632            // First try to add the "always" resolution(s) for the current user, if any
5633            if (alwaysList.size() > 0) {
5634                result.addAll(alwaysList);
5635            } else {
5636                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5637                result.addAll(undefinedList);
5638                // Maybe add one for the other profile.
5639                if (xpDomainInfo != null && (
5640                        xpDomainInfo.bestDomainVerificationStatus
5641                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5642                    result.add(xpDomainInfo.resolveInfo);
5643                }
5644                includeBrowser = true;
5645            }
5646
5647            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5648            // If there were 'always' entries their preferred order has been set, so we also
5649            // back that off to make the alternatives equivalent
5650            if (alwaysAskList.size() > 0) {
5651                for (ResolveInfo i : result) {
5652                    i.preferredOrder = 0;
5653                }
5654                result.addAll(alwaysAskList);
5655                includeBrowser = true;
5656            }
5657
5658            if (includeBrowser) {
5659                // Also add browsers (all of them or only the default one)
5660                if (DEBUG_DOMAIN_VERIFICATION) {
5661                    Slog.v(TAG, "   ...including browsers in candidate set");
5662                }
5663                if ((matchFlags & MATCH_ALL) != 0) {
5664                    result.addAll(matchAllList);
5665                } else {
5666                    // Browser/generic handling case.  If there's a default browser, go straight
5667                    // to that (but only if there is no other higher-priority match).
5668                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5669                    int maxMatchPrio = 0;
5670                    ResolveInfo defaultBrowserMatch = null;
5671                    final int numCandidates = matchAllList.size();
5672                    for (int n = 0; n < numCandidates; n++) {
5673                        ResolveInfo info = matchAllList.get(n);
5674                        // track the highest overall match priority...
5675                        if (info.priority > maxMatchPrio) {
5676                            maxMatchPrio = info.priority;
5677                        }
5678                        // ...and the highest-priority default browser match
5679                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5680                            if (defaultBrowserMatch == null
5681                                    || (defaultBrowserMatch.priority < info.priority)) {
5682                                if (debug) {
5683                                    Slog.v(TAG, "Considering default browser match " + info);
5684                                }
5685                                defaultBrowserMatch = info;
5686                            }
5687                        }
5688                    }
5689                    if (defaultBrowserMatch != null
5690                            && defaultBrowserMatch.priority >= maxMatchPrio
5691                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5692                    {
5693                        if (debug) {
5694                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5695                        }
5696                        result.add(defaultBrowserMatch);
5697                    } else {
5698                        result.addAll(matchAllList);
5699                    }
5700                }
5701
5702                // If there is nothing selected, add all candidates and remove the ones that the user
5703                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5704                if (result.size() == 0) {
5705                    result.addAll(candidates);
5706                    result.removeAll(neverList);
5707                }
5708            }
5709        }
5710        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5711            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5712                    result.size());
5713            for (ResolveInfo info : result) {
5714                Slog.v(TAG, "  + " + info.activityInfo);
5715            }
5716        }
5717        return result;
5718    }
5719
5720    // Returns a packed value as a long:
5721    //
5722    // high 'int'-sized word: link status: undefined/ask/never/always.
5723    // low 'int'-sized word: relative priority among 'always' results.
5724    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5725        long result = ps.getDomainVerificationStatusForUser(userId);
5726        // if none available, get the master status
5727        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5728            if (ps.getIntentFilterVerificationInfo() != null) {
5729                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5730            }
5731        }
5732        return result;
5733    }
5734
5735    private ResolveInfo querySkipCurrentProfileIntents(
5736            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5737            int flags, int sourceUserId) {
5738        if (matchingFilters != null) {
5739            int size = matchingFilters.size();
5740            for (int i = 0; i < size; i ++) {
5741                CrossProfileIntentFilter filter = matchingFilters.get(i);
5742                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5743                    // Checking if there are activities in the target user that can handle the
5744                    // intent.
5745                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5746                            resolvedType, flags, sourceUserId);
5747                    if (resolveInfo != null) {
5748                        return resolveInfo;
5749                    }
5750                }
5751            }
5752        }
5753        return null;
5754    }
5755
5756    // Return matching ResolveInfo in target user if any.
5757    private ResolveInfo queryCrossProfileIntents(
5758            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5759            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5760        if (matchingFilters != null) {
5761            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5762            // match the same intent. For performance reasons, it is better not to
5763            // run queryIntent twice for the same userId
5764            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5765            int size = matchingFilters.size();
5766            for (int i = 0; i < size; i++) {
5767                CrossProfileIntentFilter filter = matchingFilters.get(i);
5768                int targetUserId = filter.getTargetUserId();
5769                boolean skipCurrentProfile =
5770                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5771                boolean skipCurrentProfileIfNoMatchFound =
5772                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5773                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5774                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5775                    // Checking if there are activities in the target user that can handle the
5776                    // intent.
5777                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5778                            resolvedType, flags, sourceUserId);
5779                    if (resolveInfo != null) return resolveInfo;
5780                    alreadyTriedUserIds.put(targetUserId, true);
5781                }
5782            }
5783        }
5784        return null;
5785    }
5786
5787    /**
5788     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5789     * will forward the intent to the filter's target user.
5790     * Otherwise, returns null.
5791     */
5792    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5793            String resolvedType, int flags, int sourceUserId) {
5794        int targetUserId = filter.getTargetUserId();
5795        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5796                resolvedType, flags, targetUserId);
5797        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5798            // If all the matches in the target profile are suspended, return null.
5799            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5800                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5801                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5802                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5803                            targetUserId);
5804                }
5805            }
5806        }
5807        return null;
5808    }
5809
5810    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5811            int sourceUserId, int targetUserId) {
5812        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5813        long ident = Binder.clearCallingIdentity();
5814        boolean targetIsProfile;
5815        try {
5816            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5817        } finally {
5818            Binder.restoreCallingIdentity(ident);
5819        }
5820        String className;
5821        if (targetIsProfile) {
5822            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5823        } else {
5824            className = FORWARD_INTENT_TO_PARENT;
5825        }
5826        ComponentName forwardingActivityComponentName = new ComponentName(
5827                mAndroidApplication.packageName, className);
5828        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5829                sourceUserId);
5830        if (!targetIsProfile) {
5831            forwardingActivityInfo.showUserIcon = targetUserId;
5832            forwardingResolveInfo.noResourceId = true;
5833        }
5834        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5835        forwardingResolveInfo.priority = 0;
5836        forwardingResolveInfo.preferredOrder = 0;
5837        forwardingResolveInfo.match = 0;
5838        forwardingResolveInfo.isDefault = true;
5839        forwardingResolveInfo.filter = filter;
5840        forwardingResolveInfo.targetUserId = targetUserId;
5841        return forwardingResolveInfo;
5842    }
5843
5844    @Override
5845    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5846            Intent[] specifics, String[] specificTypes, Intent intent,
5847            String resolvedType, int flags, int userId) {
5848        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5849                specificTypes, intent, resolvedType, flags, userId));
5850    }
5851
5852    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5853            Intent[] specifics, String[] specificTypes, Intent intent,
5854            String resolvedType, int flags, int userId) {
5855        if (!sUserManager.exists(userId)) return Collections.emptyList();
5856        flags = updateFlagsForResolve(flags, userId, intent);
5857        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5858                false /* requireFullPermission */, false /* checkShell */,
5859                "query intent activity options");
5860        final String resultsAction = intent.getAction();
5861
5862        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5863                | PackageManager.GET_RESOLVED_FILTER, userId);
5864
5865        if (DEBUG_INTENT_MATCHING) {
5866            Log.v(TAG, "Query " + intent + ": " + results);
5867        }
5868
5869        int specificsPos = 0;
5870        int N;
5871
5872        // todo: note that the algorithm used here is O(N^2).  This
5873        // isn't a problem in our current environment, but if we start running
5874        // into situations where we have more than 5 or 10 matches then this
5875        // should probably be changed to something smarter...
5876
5877        // First we go through and resolve each of the specific items
5878        // that were supplied, taking care of removing any corresponding
5879        // duplicate items in the generic resolve list.
5880        if (specifics != null) {
5881            for (int i=0; i<specifics.length; i++) {
5882                final Intent sintent = specifics[i];
5883                if (sintent == null) {
5884                    continue;
5885                }
5886
5887                if (DEBUG_INTENT_MATCHING) {
5888                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5889                }
5890
5891                String action = sintent.getAction();
5892                if (resultsAction != null && resultsAction.equals(action)) {
5893                    // If this action was explicitly requested, then don't
5894                    // remove things that have it.
5895                    action = null;
5896                }
5897
5898                ResolveInfo ri = null;
5899                ActivityInfo ai = null;
5900
5901                ComponentName comp = sintent.getComponent();
5902                if (comp == null) {
5903                    ri = resolveIntent(
5904                        sintent,
5905                        specificTypes != null ? specificTypes[i] : null,
5906                            flags, userId);
5907                    if (ri == null) {
5908                        continue;
5909                    }
5910                    if (ri == mResolveInfo) {
5911                        // ACK!  Must do something better with this.
5912                    }
5913                    ai = ri.activityInfo;
5914                    comp = new ComponentName(ai.applicationInfo.packageName,
5915                            ai.name);
5916                } else {
5917                    ai = getActivityInfo(comp, flags, userId);
5918                    if (ai == null) {
5919                        continue;
5920                    }
5921                }
5922
5923                // Look for any generic query activities that are duplicates
5924                // of this specific one, and remove them from the results.
5925                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5926                N = results.size();
5927                int j;
5928                for (j=specificsPos; j<N; j++) {
5929                    ResolveInfo sri = results.get(j);
5930                    if ((sri.activityInfo.name.equals(comp.getClassName())
5931                            && sri.activityInfo.applicationInfo.packageName.equals(
5932                                    comp.getPackageName()))
5933                        || (action != null && sri.filter.matchAction(action))) {
5934                        results.remove(j);
5935                        if (DEBUG_INTENT_MATCHING) Log.v(
5936                            TAG, "Removing duplicate item from " + j
5937                            + " due to specific " + specificsPos);
5938                        if (ri == null) {
5939                            ri = sri;
5940                        }
5941                        j--;
5942                        N--;
5943                    }
5944                }
5945
5946                // Add this specific item to its proper place.
5947                if (ri == null) {
5948                    ri = new ResolveInfo();
5949                    ri.activityInfo = ai;
5950                }
5951                results.add(specificsPos, ri);
5952                ri.specificIndex = i;
5953                specificsPos++;
5954            }
5955        }
5956
5957        // Now we go through the remaining generic results and remove any
5958        // duplicate actions that are found here.
5959        N = results.size();
5960        for (int i=specificsPos; i<N-1; i++) {
5961            final ResolveInfo rii = results.get(i);
5962            if (rii.filter == null) {
5963                continue;
5964            }
5965
5966            // Iterate over all of the actions of this result's intent
5967            // filter...  typically this should be just one.
5968            final Iterator<String> it = rii.filter.actionsIterator();
5969            if (it == null) {
5970                continue;
5971            }
5972            while (it.hasNext()) {
5973                final String action = it.next();
5974                if (resultsAction != null && resultsAction.equals(action)) {
5975                    // If this action was explicitly requested, then don't
5976                    // remove things that have it.
5977                    continue;
5978                }
5979                for (int j=i+1; j<N; j++) {
5980                    final ResolveInfo rij = results.get(j);
5981                    if (rij.filter != null && rij.filter.hasAction(action)) {
5982                        results.remove(j);
5983                        if (DEBUG_INTENT_MATCHING) Log.v(
5984                            TAG, "Removing duplicate item from " + j
5985                            + " due to action " + action + " at " + i);
5986                        j--;
5987                        N--;
5988                    }
5989                }
5990            }
5991
5992            // If the caller didn't request filter information, drop it now
5993            // so we don't have to marshall/unmarshall it.
5994            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5995                rii.filter = null;
5996            }
5997        }
5998
5999        // Filter out the caller activity if so requested.
6000        if (caller != null) {
6001            N = results.size();
6002            for (int i=0; i<N; i++) {
6003                ActivityInfo ainfo = results.get(i).activityInfo;
6004                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6005                        && caller.getClassName().equals(ainfo.name)) {
6006                    results.remove(i);
6007                    break;
6008                }
6009            }
6010        }
6011
6012        // If the caller didn't request filter information,
6013        // drop them now so we don't have to
6014        // marshall/unmarshall it.
6015        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6016            N = results.size();
6017            for (int i=0; i<N; i++) {
6018                results.get(i).filter = null;
6019            }
6020        }
6021
6022        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6023        return results;
6024    }
6025
6026    @Override
6027    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6028            String resolvedType, int flags, int userId) {
6029        return new ParceledListSlice<>(
6030                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6031    }
6032
6033    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6034            String resolvedType, int flags, int userId) {
6035        if (!sUserManager.exists(userId)) return Collections.emptyList();
6036        flags = updateFlagsForResolve(flags, userId, intent);
6037        ComponentName comp = intent.getComponent();
6038        if (comp == null) {
6039            if (intent.getSelector() != null) {
6040                intent = intent.getSelector();
6041                comp = intent.getComponent();
6042            }
6043        }
6044        if (comp != null) {
6045            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6046            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6047            if (ai != null) {
6048                ResolveInfo ri = new ResolveInfo();
6049                ri.activityInfo = ai;
6050                list.add(ri);
6051            }
6052            return list;
6053        }
6054
6055        // reader
6056        synchronized (mPackages) {
6057            String pkgName = intent.getPackage();
6058            if (pkgName == null) {
6059                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6060            }
6061            final PackageParser.Package pkg = mPackages.get(pkgName);
6062            if (pkg != null) {
6063                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6064                        userId);
6065            }
6066            return Collections.emptyList();
6067        }
6068    }
6069
6070    @Override
6071    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6072        if (!sUserManager.exists(userId)) return null;
6073        flags = updateFlagsForResolve(flags, userId, intent);
6074        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6075        if (query != null) {
6076            if (query.size() >= 1) {
6077                // If there is more than one service with the same priority,
6078                // just arbitrarily pick the first one.
6079                return query.get(0);
6080            }
6081        }
6082        return null;
6083    }
6084
6085    @Override
6086    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6087            String resolvedType, int flags, int userId) {
6088        return new ParceledListSlice<>(
6089                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6090    }
6091
6092    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6093            String resolvedType, int flags, int userId) {
6094        if (!sUserManager.exists(userId)) return Collections.emptyList();
6095        flags = updateFlagsForResolve(flags, userId, intent);
6096        ComponentName comp = intent.getComponent();
6097        if (comp == null) {
6098            if (intent.getSelector() != null) {
6099                intent = intent.getSelector();
6100                comp = intent.getComponent();
6101            }
6102        }
6103        if (comp != null) {
6104            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6105            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6106            if (si != null) {
6107                final ResolveInfo ri = new ResolveInfo();
6108                ri.serviceInfo = si;
6109                list.add(ri);
6110            }
6111            return list;
6112        }
6113
6114        // reader
6115        synchronized (mPackages) {
6116            String pkgName = intent.getPackage();
6117            if (pkgName == null) {
6118                return mServices.queryIntent(intent, resolvedType, flags, userId);
6119            }
6120            final PackageParser.Package pkg = mPackages.get(pkgName);
6121            if (pkg != null) {
6122                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6123                        userId);
6124            }
6125            return Collections.emptyList();
6126        }
6127    }
6128
6129    @Override
6130    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6131            String resolvedType, int flags, int userId) {
6132        return new ParceledListSlice<>(
6133                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6134    }
6135
6136    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6137            Intent intent, String resolvedType, int flags, int userId) {
6138        if (!sUserManager.exists(userId)) return Collections.emptyList();
6139        flags = updateFlagsForResolve(flags, userId, intent);
6140        ComponentName comp = intent.getComponent();
6141        if (comp == null) {
6142            if (intent.getSelector() != null) {
6143                intent = intent.getSelector();
6144                comp = intent.getComponent();
6145            }
6146        }
6147        if (comp != null) {
6148            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6149            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6150            if (pi != null) {
6151                final ResolveInfo ri = new ResolveInfo();
6152                ri.providerInfo = pi;
6153                list.add(ri);
6154            }
6155            return list;
6156        }
6157
6158        // reader
6159        synchronized (mPackages) {
6160            String pkgName = intent.getPackage();
6161            if (pkgName == null) {
6162                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6163            }
6164            final PackageParser.Package pkg = mPackages.get(pkgName);
6165            if (pkg != null) {
6166                return mProviders.queryIntentForPackage(
6167                        intent, resolvedType, flags, pkg.providers, userId);
6168            }
6169            return Collections.emptyList();
6170        }
6171    }
6172
6173    @Override
6174    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6175        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6176        flags = updateFlagsForPackage(flags, userId, null);
6177        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6178        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6179                true /* requireFullPermission */, false /* checkShell */,
6180                "get installed packages");
6181
6182        // writer
6183        synchronized (mPackages) {
6184            ArrayList<PackageInfo> list;
6185            if (listUninstalled) {
6186                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6187                for (PackageSetting ps : mSettings.mPackages.values()) {
6188                    final PackageInfo pi;
6189                    if (ps.pkg != null) {
6190                        pi = generatePackageInfo(ps, flags, userId);
6191                    } else {
6192                        pi = generatePackageInfo(ps, flags, userId);
6193                    }
6194                    if (pi != null) {
6195                        list.add(pi);
6196                    }
6197                }
6198            } else {
6199                list = new ArrayList<PackageInfo>(mPackages.size());
6200                for (PackageParser.Package p : mPackages.values()) {
6201                    final PackageInfo pi =
6202                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6203                    if (pi != null) {
6204                        list.add(pi);
6205                    }
6206                }
6207            }
6208
6209            return new ParceledListSlice<PackageInfo>(list);
6210        }
6211    }
6212
6213    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6214            String[] permissions, boolean[] tmp, int flags, int userId) {
6215        int numMatch = 0;
6216        final PermissionsState permissionsState = ps.getPermissionsState();
6217        for (int i=0; i<permissions.length; i++) {
6218            final String permission = permissions[i];
6219            if (permissionsState.hasPermission(permission, userId)) {
6220                tmp[i] = true;
6221                numMatch++;
6222            } else {
6223                tmp[i] = false;
6224            }
6225        }
6226        if (numMatch == 0) {
6227            return;
6228        }
6229        final PackageInfo pi;
6230        if (ps.pkg != null) {
6231            pi = generatePackageInfo(ps, flags, userId);
6232        } else {
6233            pi = generatePackageInfo(ps, flags, userId);
6234        }
6235        // The above might return null in cases of uninstalled apps or install-state
6236        // skew across users/profiles.
6237        if (pi != null) {
6238            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6239                if (numMatch == permissions.length) {
6240                    pi.requestedPermissions = permissions;
6241                } else {
6242                    pi.requestedPermissions = new String[numMatch];
6243                    numMatch = 0;
6244                    for (int i=0; i<permissions.length; i++) {
6245                        if (tmp[i]) {
6246                            pi.requestedPermissions[numMatch] = permissions[i];
6247                            numMatch++;
6248                        }
6249                    }
6250                }
6251            }
6252            list.add(pi);
6253        }
6254    }
6255
6256    @Override
6257    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6258            String[] permissions, int flags, int userId) {
6259        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6260        flags = updateFlagsForPackage(flags, userId, permissions);
6261        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6262
6263        // writer
6264        synchronized (mPackages) {
6265            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6266            boolean[] tmpBools = new boolean[permissions.length];
6267            if (listUninstalled) {
6268                for (PackageSetting ps : mSettings.mPackages.values()) {
6269                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6270                }
6271            } else {
6272                for (PackageParser.Package pkg : mPackages.values()) {
6273                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6274                    if (ps != null) {
6275                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6276                                userId);
6277                    }
6278                }
6279            }
6280
6281            return new ParceledListSlice<PackageInfo>(list);
6282        }
6283    }
6284
6285    @Override
6286    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6287        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6288        flags = updateFlagsForApplication(flags, userId, null);
6289        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6290
6291        // writer
6292        synchronized (mPackages) {
6293            ArrayList<ApplicationInfo> list;
6294            if (listUninstalled) {
6295                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6296                for (PackageSetting ps : mSettings.mPackages.values()) {
6297                    ApplicationInfo ai;
6298                    if (ps.pkg != null) {
6299                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6300                                ps.readUserState(userId), userId);
6301                    } else {
6302                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6303                    }
6304                    if (ai != null) {
6305                        list.add(ai);
6306                    }
6307                }
6308            } else {
6309                list = new ArrayList<ApplicationInfo>(mPackages.size());
6310                for (PackageParser.Package p : mPackages.values()) {
6311                    if (p.mExtras != null) {
6312                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6313                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6314                        if (ai != null) {
6315                            list.add(ai);
6316                        }
6317                    }
6318                }
6319            }
6320
6321            return new ParceledListSlice<ApplicationInfo>(list);
6322        }
6323    }
6324
6325    @Override
6326    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6327        if (DISABLE_EPHEMERAL_APPS) {
6328            return null;
6329        }
6330
6331        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6332                "getEphemeralApplications");
6333        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6334                true /* requireFullPermission */, false /* checkShell */,
6335                "getEphemeralApplications");
6336        synchronized (mPackages) {
6337            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6338                    .getEphemeralApplicationsLPw(userId);
6339            if (ephemeralApps != null) {
6340                return new ParceledListSlice<>(ephemeralApps);
6341            }
6342        }
6343        return null;
6344    }
6345
6346    @Override
6347    public boolean isEphemeralApplication(String packageName, int userId) {
6348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6349                true /* requireFullPermission */, false /* checkShell */,
6350                "isEphemeral");
6351        if (DISABLE_EPHEMERAL_APPS) {
6352            return false;
6353        }
6354
6355        if (!isCallerSameApp(packageName)) {
6356            return false;
6357        }
6358        synchronized (mPackages) {
6359            PackageParser.Package pkg = mPackages.get(packageName);
6360            if (pkg != null) {
6361                return pkg.applicationInfo.isEphemeralApp();
6362            }
6363        }
6364        return false;
6365    }
6366
6367    @Override
6368    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6369        if (DISABLE_EPHEMERAL_APPS) {
6370            return null;
6371        }
6372
6373        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6374                true /* requireFullPermission */, false /* checkShell */,
6375                "getCookie");
6376        if (!isCallerSameApp(packageName)) {
6377            return null;
6378        }
6379        synchronized (mPackages) {
6380            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6381                    packageName, userId);
6382        }
6383    }
6384
6385    @Override
6386    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6387        if (DISABLE_EPHEMERAL_APPS) {
6388            return true;
6389        }
6390
6391        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6392                true /* requireFullPermission */, true /* checkShell */,
6393                "setCookie");
6394        if (!isCallerSameApp(packageName)) {
6395            return false;
6396        }
6397        synchronized (mPackages) {
6398            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6399                    packageName, cookie, userId);
6400        }
6401    }
6402
6403    @Override
6404    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6405        if (DISABLE_EPHEMERAL_APPS) {
6406            return null;
6407        }
6408
6409        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6410                "getEphemeralApplicationIcon");
6411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6412                true /* requireFullPermission */, false /* checkShell */,
6413                "getEphemeralApplicationIcon");
6414        synchronized (mPackages) {
6415            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6416                    packageName, userId);
6417        }
6418    }
6419
6420    private boolean isCallerSameApp(String packageName) {
6421        PackageParser.Package pkg = mPackages.get(packageName);
6422        return pkg != null
6423                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6424    }
6425
6426    @Override
6427    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6428        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6429    }
6430
6431    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6432        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6433
6434        // reader
6435        synchronized (mPackages) {
6436            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6437            final int userId = UserHandle.getCallingUserId();
6438            while (i.hasNext()) {
6439                final PackageParser.Package p = i.next();
6440                if (p.applicationInfo == null) continue;
6441
6442                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6443                        && !p.applicationInfo.isDirectBootAware();
6444                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6445                        && p.applicationInfo.isDirectBootAware();
6446
6447                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6448                        && (!mSafeMode || isSystemApp(p))
6449                        && (matchesUnaware || matchesAware)) {
6450                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6451                    if (ps != null) {
6452                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6453                                ps.readUserState(userId), userId);
6454                        if (ai != null) {
6455                            finalList.add(ai);
6456                        }
6457                    }
6458                }
6459            }
6460        }
6461
6462        return finalList;
6463    }
6464
6465    @Override
6466    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6467        if (!sUserManager.exists(userId)) return null;
6468        flags = updateFlagsForComponent(flags, userId, name);
6469        // reader
6470        synchronized (mPackages) {
6471            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6472            PackageSetting ps = provider != null
6473                    ? mSettings.mPackages.get(provider.owner.packageName)
6474                    : null;
6475            return ps != null
6476                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6477                    ? PackageParser.generateProviderInfo(provider, flags,
6478                            ps.readUserState(userId), userId)
6479                    : null;
6480        }
6481    }
6482
6483    /**
6484     * @deprecated
6485     */
6486    @Deprecated
6487    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6488        // reader
6489        synchronized (mPackages) {
6490            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6491                    .entrySet().iterator();
6492            final int userId = UserHandle.getCallingUserId();
6493            while (i.hasNext()) {
6494                Map.Entry<String, PackageParser.Provider> entry = i.next();
6495                PackageParser.Provider p = entry.getValue();
6496                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6497
6498                if (ps != null && p.syncable
6499                        && (!mSafeMode || (p.info.applicationInfo.flags
6500                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6501                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6502                            ps.readUserState(userId), userId);
6503                    if (info != null) {
6504                        outNames.add(entry.getKey());
6505                        outInfo.add(info);
6506                    }
6507                }
6508            }
6509        }
6510    }
6511
6512    @Override
6513    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6514            int uid, int flags) {
6515        final int userId = processName != null ? UserHandle.getUserId(uid)
6516                : UserHandle.getCallingUserId();
6517        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6518        flags = updateFlagsForComponent(flags, userId, processName);
6519
6520        ArrayList<ProviderInfo> finalList = null;
6521        // reader
6522        synchronized (mPackages) {
6523            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6524            while (i.hasNext()) {
6525                final PackageParser.Provider p = i.next();
6526                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6527                if (ps != null && p.info.authority != null
6528                        && (processName == null
6529                                || (p.info.processName.equals(processName)
6530                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6531                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6532                    if (finalList == null) {
6533                        finalList = new ArrayList<ProviderInfo>(3);
6534                    }
6535                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6536                            ps.readUserState(userId), userId);
6537                    if (info != null) {
6538                        finalList.add(info);
6539                    }
6540                }
6541            }
6542        }
6543
6544        if (finalList != null) {
6545            Collections.sort(finalList, mProviderInitOrderSorter);
6546            return new ParceledListSlice<ProviderInfo>(finalList);
6547        }
6548
6549        return ParceledListSlice.emptyList();
6550    }
6551
6552    @Override
6553    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6554        // reader
6555        synchronized (mPackages) {
6556            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6557            return PackageParser.generateInstrumentationInfo(i, flags);
6558        }
6559    }
6560
6561    @Override
6562    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6563            String targetPackage, int flags) {
6564        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6565    }
6566
6567    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6568            int flags) {
6569        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6570
6571        // reader
6572        synchronized (mPackages) {
6573            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6574            while (i.hasNext()) {
6575                final PackageParser.Instrumentation p = i.next();
6576                if (targetPackage == null
6577                        || targetPackage.equals(p.info.targetPackage)) {
6578                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6579                            flags);
6580                    if (ii != null) {
6581                        finalList.add(ii);
6582                    }
6583                }
6584            }
6585        }
6586
6587        return finalList;
6588    }
6589
6590    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6591        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6592        if (overlays == null) {
6593            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6594            return;
6595        }
6596        for (PackageParser.Package opkg : overlays.values()) {
6597            // Not much to do if idmap fails: we already logged the error
6598            // and we certainly don't want to abort installation of pkg simply
6599            // because an overlay didn't fit properly. For these reasons,
6600            // ignore the return value of createIdmapForPackagePairLI.
6601            createIdmapForPackagePairLI(pkg, opkg);
6602        }
6603    }
6604
6605    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6606            PackageParser.Package opkg) {
6607        if (!opkg.mTrustedOverlay) {
6608            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6609                    opkg.baseCodePath + ": overlay not trusted");
6610            return false;
6611        }
6612        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6613        if (overlaySet == null) {
6614            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6615                    opkg.baseCodePath + " but target package has no known overlays");
6616            return false;
6617        }
6618        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6619        // TODO: generate idmap for split APKs
6620        try {
6621            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6622        } catch (InstallerException e) {
6623            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6624                    + opkg.baseCodePath);
6625            return false;
6626        }
6627        PackageParser.Package[] overlayArray =
6628            overlaySet.values().toArray(new PackageParser.Package[0]);
6629        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6630            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6631                return p1.mOverlayPriority - p2.mOverlayPriority;
6632            }
6633        };
6634        Arrays.sort(overlayArray, cmp);
6635
6636        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6637        int i = 0;
6638        for (PackageParser.Package p : overlayArray) {
6639            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6640        }
6641        return true;
6642    }
6643
6644    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6645        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6646        try {
6647            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6648        } finally {
6649            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6650        }
6651    }
6652
6653    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6654        final File[] files = dir.listFiles();
6655        if (ArrayUtils.isEmpty(files)) {
6656            Log.d(TAG, "No files in app dir " + dir);
6657            return;
6658        }
6659
6660        if (DEBUG_PACKAGE_SCANNING) {
6661            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6662                    + " flags=0x" + Integer.toHexString(parseFlags));
6663        }
6664
6665        for (File file : files) {
6666            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6667                    && !PackageInstallerService.isStageName(file.getName());
6668            if (!isPackage) {
6669                // Ignore entries which are not packages
6670                continue;
6671            }
6672            try {
6673                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6674                        scanFlags, currentTime, null);
6675            } catch (PackageManagerException e) {
6676                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6677
6678                // Delete invalid userdata apps
6679                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6680                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6681                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6682                    removeCodePathLI(file);
6683                }
6684            }
6685        }
6686    }
6687
6688    private static File getSettingsProblemFile() {
6689        File dataDir = Environment.getDataDirectory();
6690        File systemDir = new File(dataDir, "system");
6691        File fname = new File(systemDir, "uiderrors.txt");
6692        return fname;
6693    }
6694
6695    static void reportSettingsProblem(int priority, String msg) {
6696        logCriticalInfo(priority, msg);
6697    }
6698
6699    static void logCriticalInfo(int priority, String msg) {
6700        Slog.println(priority, TAG, msg);
6701        EventLogTags.writePmCriticalInfo(msg);
6702        try {
6703            File fname = getSettingsProblemFile();
6704            FileOutputStream out = new FileOutputStream(fname, true);
6705            PrintWriter pw = new FastPrintWriter(out);
6706            SimpleDateFormat formatter = new SimpleDateFormat();
6707            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6708            pw.println(dateString + ": " + msg);
6709            pw.close();
6710            FileUtils.setPermissions(
6711                    fname.toString(),
6712                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6713                    -1, -1);
6714        } catch (java.io.IOException e) {
6715        }
6716    }
6717
6718    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6719            final int policyFlags) throws PackageManagerException {
6720        if (ps != null
6721                && ps.codePath.equals(srcFile)
6722                && ps.timeStamp == srcFile.lastModified()
6723                && !isCompatSignatureUpdateNeeded(pkg)
6724                && !isRecoverSignatureUpdateNeeded(pkg)) {
6725            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6726            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6727            ArraySet<PublicKey> signingKs;
6728            synchronized (mPackages) {
6729                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6730            }
6731            if (ps.signatures.mSignatures != null
6732                    && ps.signatures.mSignatures.length != 0
6733                    && signingKs != null) {
6734                // Optimization: reuse the existing cached certificates
6735                // if the package appears to be unchanged.
6736                pkg.mSignatures = ps.signatures.mSignatures;
6737                pkg.mSigningKeys = signingKs;
6738                return;
6739            }
6740
6741            Slog.w(TAG, "PackageSetting for " + ps.name
6742                    + " is missing signatures.  Collecting certs again to recover them.");
6743        } else {
6744            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6745        }
6746
6747        try {
6748            PackageParser.collectCertificates(pkg, policyFlags);
6749        } catch (PackageParserException e) {
6750            throw PackageManagerException.from(e);
6751        }
6752    }
6753
6754    /**
6755     *  Traces a package scan.
6756     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6757     */
6758    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6759            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6760        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6761        try {
6762            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6763        } finally {
6764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6765        }
6766    }
6767
6768    /**
6769     *  Scans a package and returns the newly parsed package.
6770     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6771     */
6772    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6773            long currentTime, UserHandle user) throws PackageManagerException {
6774        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6775        PackageParser pp = new PackageParser();
6776        pp.setSeparateProcesses(mSeparateProcesses);
6777        pp.setOnlyCoreApps(mOnlyCore);
6778        pp.setDisplayMetrics(mMetrics);
6779
6780        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6781            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6782        }
6783
6784        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6785        final PackageParser.Package pkg;
6786        try {
6787            pkg = pp.parsePackage(scanFile, parseFlags);
6788        } catch (PackageParserException e) {
6789            throw PackageManagerException.from(e);
6790        } finally {
6791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6792        }
6793
6794        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6795    }
6796
6797    /**
6798     *  Scans a package and returns the newly parsed package.
6799     *  @throws PackageManagerException on a parse error.
6800     */
6801    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6802            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6803            throws PackageManagerException {
6804        // If the package has children and this is the first dive in the function
6805        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6806        // packages (parent and children) would be successfully scanned before the
6807        // actual scan since scanning mutates internal state and we want to atomically
6808        // install the package and its children.
6809        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6810            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6811                scanFlags |= SCAN_CHECK_ONLY;
6812            }
6813        } else {
6814            scanFlags &= ~SCAN_CHECK_ONLY;
6815        }
6816
6817        // Scan the parent
6818        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6819                scanFlags, currentTime, user);
6820
6821        // Scan the children
6822        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6823        for (int i = 0; i < childCount; i++) {
6824            PackageParser.Package childPackage = pkg.childPackages.get(i);
6825            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6826                    currentTime, user);
6827        }
6828
6829
6830        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6831            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6832        }
6833
6834        return scannedPkg;
6835    }
6836
6837    /**
6838     *  Scans a package and returns the newly parsed package.
6839     *  @throws PackageManagerException on a parse error.
6840     */
6841    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6842            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6843            throws PackageManagerException {
6844        PackageSetting ps = null;
6845        PackageSetting updatedPkg;
6846        // reader
6847        synchronized (mPackages) {
6848            // Look to see if we already know about this package.
6849            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6850            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6851                // This package has been renamed to its original name.  Let's
6852                // use that.
6853                ps = mSettings.peekPackageLPr(oldName);
6854            }
6855            // If there was no original package, see one for the real package name.
6856            if (ps == null) {
6857                ps = mSettings.peekPackageLPr(pkg.packageName);
6858            }
6859            // Check to see if this package could be hiding/updating a system
6860            // package.  Must look for it either under the original or real
6861            // package name depending on our state.
6862            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6863            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6864
6865            // If this is a package we don't know about on the system partition, we
6866            // may need to remove disabled child packages on the system partition
6867            // or may need to not add child packages if the parent apk is updated
6868            // on the data partition and no longer defines this child package.
6869            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6870                // If this is a parent package for an updated system app and this system
6871                // app got an OTA update which no longer defines some of the child packages
6872                // we have to prune them from the disabled system packages.
6873                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6874                if (disabledPs != null) {
6875                    final int scannedChildCount = (pkg.childPackages != null)
6876                            ? pkg.childPackages.size() : 0;
6877                    final int disabledChildCount = disabledPs.childPackageNames != null
6878                            ? disabledPs.childPackageNames.size() : 0;
6879                    for (int i = 0; i < disabledChildCount; i++) {
6880                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6881                        boolean disabledPackageAvailable = false;
6882                        for (int j = 0; j < scannedChildCount; j++) {
6883                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6884                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6885                                disabledPackageAvailable = true;
6886                                break;
6887                            }
6888                         }
6889                         if (!disabledPackageAvailable) {
6890                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6891                         }
6892                    }
6893                }
6894            }
6895        }
6896
6897        boolean updatedPkgBetter = false;
6898        // First check if this is a system package that may involve an update
6899        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6900            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6901            // it needs to drop FLAG_PRIVILEGED.
6902            if (locationIsPrivileged(scanFile)) {
6903                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6904            } else {
6905                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6906            }
6907
6908            if (ps != null && !ps.codePath.equals(scanFile)) {
6909                // The path has changed from what was last scanned...  check the
6910                // version of the new path against what we have stored to determine
6911                // what to do.
6912                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6913                if (pkg.mVersionCode <= ps.versionCode) {
6914                    // The system package has been updated and the code path does not match
6915                    // Ignore entry. Skip it.
6916                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6917                            + " ignored: updated version " + ps.versionCode
6918                            + " better than this " + pkg.mVersionCode);
6919                    if (!updatedPkg.codePath.equals(scanFile)) {
6920                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6921                                + ps.name + " changing from " + updatedPkg.codePathString
6922                                + " to " + scanFile);
6923                        updatedPkg.codePath = scanFile;
6924                        updatedPkg.codePathString = scanFile.toString();
6925                        updatedPkg.resourcePath = scanFile;
6926                        updatedPkg.resourcePathString = scanFile.toString();
6927                    }
6928                    updatedPkg.pkg = pkg;
6929                    updatedPkg.versionCode = pkg.mVersionCode;
6930
6931                    // Update the disabled system child packages to point to the package too.
6932                    final int childCount = updatedPkg.childPackageNames != null
6933                            ? updatedPkg.childPackageNames.size() : 0;
6934                    for (int i = 0; i < childCount; i++) {
6935                        String childPackageName = updatedPkg.childPackageNames.get(i);
6936                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6937                                childPackageName);
6938                        if (updatedChildPkg != null) {
6939                            updatedChildPkg.pkg = pkg;
6940                            updatedChildPkg.versionCode = pkg.mVersionCode;
6941                        }
6942                    }
6943
6944                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6945                            + scanFile + " ignored: updated version " + ps.versionCode
6946                            + " better than this " + pkg.mVersionCode);
6947                } else {
6948                    // The current app on the system partition is better than
6949                    // what we have updated to on the data partition; switch
6950                    // back to the system partition version.
6951                    // At this point, its safely assumed that package installation for
6952                    // apps in system partition will go through. If not there won't be a working
6953                    // version of the app
6954                    // writer
6955                    synchronized (mPackages) {
6956                        // Just remove the loaded entries from package lists.
6957                        mPackages.remove(ps.name);
6958                    }
6959
6960                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6961                            + " reverting from " + ps.codePathString
6962                            + ": new version " + pkg.mVersionCode
6963                            + " better than installed " + ps.versionCode);
6964
6965                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6966                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6967                    synchronized (mInstallLock) {
6968                        args.cleanUpResourcesLI();
6969                    }
6970                    synchronized (mPackages) {
6971                        mSettings.enableSystemPackageLPw(ps.name);
6972                    }
6973                    updatedPkgBetter = true;
6974                }
6975            }
6976        }
6977
6978        if (updatedPkg != null) {
6979            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6980            // initially
6981            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6982
6983            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6984            // flag set initially
6985            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6986                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6987            }
6988        }
6989
6990        // Verify certificates against what was last scanned
6991        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6992
6993        /*
6994         * A new system app appeared, but we already had a non-system one of the
6995         * same name installed earlier.
6996         */
6997        boolean shouldHideSystemApp = false;
6998        if (updatedPkg == null && ps != null
6999                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7000            /*
7001             * Check to make sure the signatures match first. If they don't,
7002             * wipe the installed application and its data.
7003             */
7004            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7005                    != PackageManager.SIGNATURE_MATCH) {
7006                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7007                        + " signatures don't match existing userdata copy; removing");
7008                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7009                        "scanPackageInternalLI")) {
7010                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7011                }
7012                ps = null;
7013            } else {
7014                /*
7015                 * If the newly-added system app is an older version than the
7016                 * already installed version, hide it. It will be scanned later
7017                 * and re-added like an update.
7018                 */
7019                if (pkg.mVersionCode <= ps.versionCode) {
7020                    shouldHideSystemApp = true;
7021                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7022                            + " but new version " + pkg.mVersionCode + " better than installed "
7023                            + ps.versionCode + "; hiding system");
7024                } else {
7025                    /*
7026                     * The newly found system app is a newer version that the
7027                     * one previously installed. Simply remove the
7028                     * already-installed application and replace it with our own
7029                     * while keeping the application data.
7030                     */
7031                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7032                            + " reverting from " + ps.codePathString + ": new version "
7033                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7034                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7035                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7036                    synchronized (mInstallLock) {
7037                        args.cleanUpResourcesLI();
7038                    }
7039                }
7040            }
7041        }
7042
7043        // The apk is forward locked (not public) if its code and resources
7044        // are kept in different files. (except for app in either system or
7045        // vendor path).
7046        // TODO grab this value from PackageSettings
7047        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7048            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7049                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7050            }
7051        }
7052
7053        // TODO: extend to support forward-locked splits
7054        String resourcePath = null;
7055        String baseResourcePath = null;
7056        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7057            if (ps != null && ps.resourcePathString != null) {
7058                resourcePath = ps.resourcePathString;
7059                baseResourcePath = ps.resourcePathString;
7060            } else {
7061                // Should not happen at all. Just log an error.
7062                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7063            }
7064        } else {
7065            resourcePath = pkg.codePath;
7066            baseResourcePath = pkg.baseCodePath;
7067        }
7068
7069        // Set application objects path explicitly.
7070        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7071        pkg.setApplicationInfoCodePath(pkg.codePath);
7072        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7073        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7074        pkg.setApplicationInfoResourcePath(resourcePath);
7075        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7076        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7077
7078        // Note that we invoke the following method only if we are about to unpack an application
7079        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7080                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7081
7082        /*
7083         * If the system app should be overridden by a previously installed
7084         * data, hide the system app now and let the /data/app scan pick it up
7085         * again.
7086         */
7087        if (shouldHideSystemApp) {
7088            synchronized (mPackages) {
7089                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7090            }
7091        }
7092
7093        return scannedPkg;
7094    }
7095
7096    private static String fixProcessName(String defProcessName,
7097            String processName, int uid) {
7098        if (processName == null) {
7099            return defProcessName;
7100        }
7101        return processName;
7102    }
7103
7104    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7105            throws PackageManagerException {
7106        if (pkgSetting.signatures.mSignatures != null) {
7107            // Already existing package. Make sure signatures match
7108            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7109                    == PackageManager.SIGNATURE_MATCH;
7110            if (!match) {
7111                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7112                        == PackageManager.SIGNATURE_MATCH;
7113            }
7114            if (!match) {
7115                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7116                        == PackageManager.SIGNATURE_MATCH;
7117            }
7118            if (!match) {
7119                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7120                        + pkg.packageName + " signatures do not match the "
7121                        + "previously installed version; ignoring!");
7122            }
7123        }
7124
7125        // Check for shared user signatures
7126        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7127            // Already existing package. Make sure signatures match
7128            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7129                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7130            if (!match) {
7131                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7132                        == PackageManager.SIGNATURE_MATCH;
7133            }
7134            if (!match) {
7135                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7136                        == PackageManager.SIGNATURE_MATCH;
7137            }
7138            if (!match) {
7139                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7140                        "Package " + pkg.packageName
7141                        + " has no signatures that match those in shared user "
7142                        + pkgSetting.sharedUser.name + "; ignoring!");
7143            }
7144        }
7145    }
7146
7147    /**
7148     * Enforces that only the system UID or root's UID can call a method exposed
7149     * via Binder.
7150     *
7151     * @param message used as message if SecurityException is thrown
7152     * @throws SecurityException if the caller is not system or root
7153     */
7154    private static final void enforceSystemOrRoot(String message) {
7155        final int uid = Binder.getCallingUid();
7156        if (uid != Process.SYSTEM_UID && uid != 0) {
7157            throw new SecurityException(message);
7158        }
7159    }
7160
7161    @Override
7162    public void performFstrimIfNeeded() {
7163        enforceSystemOrRoot("Only the system can request fstrim");
7164
7165        // Before everything else, see whether we need to fstrim.
7166        try {
7167            IMountService ms = PackageHelper.getMountService();
7168            if (ms != null) {
7169                final boolean isUpgrade = isUpgrade();
7170                boolean doTrim = isUpgrade;
7171                if (doTrim) {
7172                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7173                } else {
7174                    final long interval = android.provider.Settings.Global.getLong(
7175                            mContext.getContentResolver(),
7176                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7177                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7178                    if (interval > 0) {
7179                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7180                        if (timeSinceLast > interval) {
7181                            doTrim = true;
7182                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7183                                    + "; running immediately");
7184                        }
7185                    }
7186                }
7187                if (doTrim) {
7188                    if (!isFirstBoot()) {
7189                        try {
7190                            ActivityManagerNative.getDefault().showBootMessage(
7191                                    mContext.getResources().getString(
7192                                            R.string.android_upgrading_fstrim), true);
7193                        } catch (RemoteException e) {
7194                        }
7195                    }
7196                    ms.runMaintenance();
7197                }
7198            } else {
7199                Slog.e(TAG, "Mount service unavailable!");
7200            }
7201        } catch (RemoteException e) {
7202            // Can't happen; MountService is local
7203        }
7204    }
7205
7206    @Override
7207    public void updatePackagesIfNeeded() {
7208        enforceSystemOrRoot("Only the system can request package update");
7209
7210        // We need to re-extract after an OTA.
7211        boolean causeUpgrade = isUpgrade();
7212
7213        // First boot or factory reset.
7214        // Note: we also handle devices that are upgrading to N right now as if it is their
7215        //       first boot, as they do not have profile data.
7216        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7217
7218        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7219        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7220
7221        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7222            return;
7223        }
7224
7225        List<PackageParser.Package> pkgs;
7226        synchronized (mPackages) {
7227            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7228        }
7229
7230        int numberOfPackagesVisited = 0;
7231        int numberOfPackagesOptimized = 0;
7232        int numberOfPackagesSkipped = 0;
7233        int numberOfPackagesFailed = 0;
7234        final int numberOfPackagesToDexopt = pkgs.size();
7235        final long startTime = System.nanoTime();
7236
7237        for (PackageParser.Package pkg : pkgs) {
7238            numberOfPackagesVisited++;
7239
7240            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7241                if (DEBUG_DEXOPT) {
7242                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7243                }
7244                numberOfPackagesSkipped++;
7245                continue;
7246            }
7247
7248            if (DEBUG_DEXOPT) {
7249                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7250                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7251            }
7252
7253            if (mIsPreNUpgrade) {
7254                try {
7255                    ActivityManagerNative.getDefault().showBootMessage(
7256                            mContext.getResources().getString(R.string.android_upgrading_apk,
7257                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7258                } catch (RemoteException e) {
7259                }
7260            }
7261
7262            // checkProfiles is false to avoid merging profiles during boot which
7263            // might interfere with background compilation (b/28612421).
7264            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7265            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7266            // trade-off worth doing to save boot time work.
7267            int dexOptStatus = performDexOptTraced(pkg.packageName,
7268                    false /* checkProfiles */,
7269                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
7270                    false /* force */);
7271            switch (dexOptStatus) {
7272                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7273                    numberOfPackagesOptimized++;
7274                    break;
7275                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7276                    numberOfPackagesSkipped++;
7277                    break;
7278                case PackageDexOptimizer.DEX_OPT_FAILED:
7279                    numberOfPackagesFailed++;
7280                    break;
7281                default:
7282                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7283                    break;
7284            }
7285        }
7286
7287        final int elapsedTimeSeconds =
7288                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7289        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized);
7290        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped);
7291        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed);
7292        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7293        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7294    }
7295
7296    @Override
7297    public void notifyPackageUse(String packageName, int reason) {
7298        synchronized (mPackages) {
7299            PackageParser.Package p = mPackages.get(packageName);
7300            if (p == null) {
7301                return;
7302            }
7303            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7304        }
7305    }
7306
7307    // TODO: this is not used nor needed. Delete it.
7308    @Override
7309    public boolean performDexOptIfNeeded(String packageName) {
7310        int dexOptStatus = performDexOptTraced(packageName,
7311                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7312        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7313    }
7314
7315    @Override
7316    public boolean performDexOpt(String packageName,
7317            boolean checkProfiles, int compileReason, boolean force) {
7318        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7319                getCompilerFilterForReason(compileReason), force);
7320        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7321    }
7322
7323    @Override
7324    public boolean performDexOptMode(String packageName,
7325            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7326        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7327                targetCompilerFilter, force);
7328        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7329    }
7330
7331    private int performDexOptTraced(String packageName,
7332                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7333        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7334        try {
7335            return performDexOptInternal(packageName, checkProfiles,
7336                    targetCompilerFilter, force);
7337        } finally {
7338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7339        }
7340    }
7341
7342    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7343    // if the package can now be considered up to date for the given filter.
7344    private int performDexOptInternal(String packageName,
7345                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7346        PackageParser.Package p;
7347        synchronized (mPackages) {
7348            p = mPackages.get(packageName);
7349            if (p == null) {
7350                // Package could not be found. Report failure.
7351                return PackageDexOptimizer.DEX_OPT_FAILED;
7352            }
7353            mPackageUsage.write(false);
7354        }
7355        long callingId = Binder.clearCallingIdentity();
7356        try {
7357            synchronized (mInstallLock) {
7358                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7359                        targetCompilerFilter, force);
7360            }
7361        } finally {
7362            Binder.restoreCallingIdentity(callingId);
7363        }
7364    }
7365
7366    public ArraySet<String> getOptimizablePackages() {
7367        ArraySet<String> pkgs = new ArraySet<String>();
7368        synchronized (mPackages) {
7369            for (PackageParser.Package p : mPackages.values()) {
7370                if (PackageDexOptimizer.canOptimizePackage(p)) {
7371                    pkgs.add(p.packageName);
7372                }
7373            }
7374        }
7375        return pkgs;
7376    }
7377
7378    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7379            boolean checkProfiles, String targetCompilerFilter,
7380            boolean force) {
7381        // Select the dex optimizer based on the force parameter.
7382        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7383        //       allocate an object here.
7384        PackageDexOptimizer pdo = force
7385                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7386                : mPackageDexOptimizer;
7387
7388        // Optimize all dependencies first. Note: we ignore the return value and march on
7389        // on errors.
7390        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7391        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7392        if (!deps.isEmpty()) {
7393            for (PackageParser.Package depPackage : deps) {
7394                // TODO: Analyze and investigate if we (should) profile libraries.
7395                // Currently this will do a full compilation of the library by default.
7396                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7397                        false /* checkProfiles */,
7398                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7399            }
7400        }
7401        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7402                targetCompilerFilter);
7403    }
7404
7405    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7406        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7407            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7408            Set<String> collectedNames = new HashSet<>();
7409            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7410
7411            retValue.remove(p);
7412
7413            return retValue;
7414        } else {
7415            return Collections.emptyList();
7416        }
7417    }
7418
7419    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7420            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7421        if (!collectedNames.contains(p.packageName)) {
7422            collectedNames.add(p.packageName);
7423            collected.add(p);
7424
7425            if (p.usesLibraries != null) {
7426                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7427            }
7428            if (p.usesOptionalLibraries != null) {
7429                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7430                        collectedNames);
7431            }
7432        }
7433    }
7434
7435    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7436            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7437        for (String libName : libs) {
7438            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7439            if (libPkg != null) {
7440                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7441            }
7442        }
7443    }
7444
7445    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7446        synchronized (mPackages) {
7447            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7448            if (lib != null && lib.apk != null) {
7449                return mPackages.get(lib.apk);
7450            }
7451        }
7452        return null;
7453    }
7454
7455    public void shutdown() {
7456        mPackageUsage.write(true);
7457    }
7458
7459    @Override
7460    public void forceDexOpt(String packageName) {
7461        enforceSystemOrRoot("forceDexOpt");
7462
7463        PackageParser.Package pkg;
7464        synchronized (mPackages) {
7465            pkg = mPackages.get(packageName);
7466            if (pkg == null) {
7467                throw new IllegalArgumentException("Unknown package: " + packageName);
7468            }
7469        }
7470
7471        synchronized (mInstallLock) {
7472            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7473
7474            // Whoever is calling forceDexOpt wants a fully compiled package.
7475            // Don't use profiles since that may cause compilation to be skipped.
7476            final int res = performDexOptInternalWithDependenciesLI(pkg,
7477                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7478                    true /* force */);
7479
7480            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7481            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7482                throw new IllegalStateException("Failed to dexopt: " + res);
7483            }
7484        }
7485    }
7486
7487    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7488        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7489            Slog.w(TAG, "Unable to update from " + oldPkg.name
7490                    + " to " + newPkg.packageName
7491                    + ": old package not in system partition");
7492            return false;
7493        } else if (mPackages.get(oldPkg.name) != null) {
7494            Slog.w(TAG, "Unable to update from " + oldPkg.name
7495                    + " to " + newPkg.packageName
7496                    + ": old package still exists");
7497            return false;
7498        }
7499        return true;
7500    }
7501
7502    void removeCodePathLI(File codePath) {
7503        if (codePath.isDirectory()) {
7504            try {
7505                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7506            } catch (InstallerException e) {
7507                Slog.w(TAG, "Failed to remove code path", e);
7508            }
7509        } else {
7510            codePath.delete();
7511        }
7512    }
7513
7514    private int[] resolveUserIds(int userId) {
7515        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7516    }
7517
7518    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7519        if (pkg == null) {
7520            Slog.wtf(TAG, "Package was null!", new Throwable());
7521            return;
7522        }
7523        clearAppDataLeafLIF(pkg, userId, flags);
7524        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7525        for (int i = 0; i < childCount; i++) {
7526            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7527        }
7528    }
7529
7530    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7531        final PackageSetting ps;
7532        synchronized (mPackages) {
7533            ps = mSettings.mPackages.get(pkg.packageName);
7534        }
7535        for (int realUserId : resolveUserIds(userId)) {
7536            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7537            try {
7538                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7539                        ceDataInode);
7540            } catch (InstallerException e) {
7541                Slog.w(TAG, String.valueOf(e));
7542            }
7543        }
7544    }
7545
7546    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7547        if (pkg == null) {
7548            Slog.wtf(TAG, "Package was null!", new Throwable());
7549            return;
7550        }
7551        destroyAppDataLeafLIF(pkg, userId, flags);
7552        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7553        for (int i = 0; i < childCount; i++) {
7554            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7555        }
7556    }
7557
7558    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7559        final PackageSetting ps;
7560        synchronized (mPackages) {
7561            ps = mSettings.mPackages.get(pkg.packageName);
7562        }
7563        for (int realUserId : resolveUserIds(userId)) {
7564            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7565            try {
7566                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7567                        ceDataInode);
7568            } catch (InstallerException e) {
7569                Slog.w(TAG, String.valueOf(e));
7570            }
7571        }
7572    }
7573
7574    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7575        if (pkg == null) {
7576            Slog.wtf(TAG, "Package was null!", new Throwable());
7577            return;
7578        }
7579        destroyAppProfilesLeafLIF(pkg);
7580        destroyAppReferenceProfileLeafLIF(pkg, userId);
7581        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7582        for (int i = 0; i < childCount; i++) {
7583            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7584            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId);
7585        }
7586    }
7587
7588    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) {
7589        if (pkg.isForwardLocked()) {
7590            return;
7591        }
7592
7593        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7594            try {
7595                path = PackageManagerServiceUtils.realpath(new File(path));
7596            } catch (IOException e) {
7597                // TODO: Should we return early here ?
7598                Slog.w(TAG, "Failed to get canonical path", e);
7599                continue;
7600            }
7601
7602            final String useMarker = path.replace('/', '@');
7603            for (int realUserId : resolveUserIds(userId)) {
7604                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7605                File foreignUseMark = new File(profileDir, useMarker);
7606                if (foreignUseMark.exists()) {
7607                    if (!foreignUseMark.delete()) {
7608                        Slog.w(TAG, "Unable to delete foreign user mark for package: "
7609                            + pkg.packageName);
7610                    }
7611                }
7612
7613                File[] markers = profileDir.listFiles();
7614                if (markers != null) {
7615                    final String searchString = "@" + pkg.packageName + "@";
7616                    // We also delete all markers that contain the package name we're
7617                    // uninstalling. These are associated with secondary dex-files belonging
7618                    // to the package. Reconstructing the path of these dex files is messy
7619                    // in general.
7620                    for (File marker : markers) {
7621                        if (marker.getName().indexOf(searchString) > 0) {
7622                            if (!marker.delete()) {
7623                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7624                                    + pkg.packageName);
7625                            }
7626                        }
7627                    }
7628                }
7629            }
7630        }
7631    }
7632
7633    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7634        try {
7635            mInstaller.destroyAppProfiles(pkg.packageName);
7636        } catch (InstallerException e) {
7637            Slog.w(TAG, String.valueOf(e));
7638        }
7639    }
7640
7641    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7642        if (pkg == null) {
7643            Slog.wtf(TAG, "Package was null!", new Throwable());
7644            return;
7645        }
7646        clearAppProfilesLeafLIF(pkg);
7647        destroyAppReferenceProfileLeafLIF(pkg, userId);
7648        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7649        for (int i = 0; i < childCount; i++) {
7650            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7651        }
7652    }
7653
7654    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7655        try {
7656            mInstaller.clearAppProfiles(pkg.packageName);
7657        } catch (InstallerException e) {
7658            Slog.w(TAG, String.valueOf(e));
7659        }
7660    }
7661
7662    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7663            long lastUpdateTime) {
7664        // Set parent install/update time
7665        PackageSetting ps = (PackageSetting) pkg.mExtras;
7666        if (ps != null) {
7667            ps.firstInstallTime = firstInstallTime;
7668            ps.lastUpdateTime = lastUpdateTime;
7669        }
7670        // Set children install/update time
7671        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7672        for (int i = 0; i < childCount; i++) {
7673            PackageParser.Package childPkg = pkg.childPackages.get(i);
7674            ps = (PackageSetting) childPkg.mExtras;
7675            if (ps != null) {
7676                ps.firstInstallTime = firstInstallTime;
7677                ps.lastUpdateTime = lastUpdateTime;
7678            }
7679        }
7680    }
7681
7682    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7683            PackageParser.Package changingLib) {
7684        if (file.path != null) {
7685            usesLibraryFiles.add(file.path);
7686            return;
7687        }
7688        PackageParser.Package p = mPackages.get(file.apk);
7689        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7690            // If we are doing this while in the middle of updating a library apk,
7691            // then we need to make sure to use that new apk for determining the
7692            // dependencies here.  (We haven't yet finished committing the new apk
7693            // to the package manager state.)
7694            if (p == null || p.packageName.equals(changingLib.packageName)) {
7695                p = changingLib;
7696            }
7697        }
7698        if (p != null) {
7699            usesLibraryFiles.addAll(p.getAllCodePaths());
7700        }
7701    }
7702
7703    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7704            PackageParser.Package changingLib) throws PackageManagerException {
7705        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7706            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7707            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7708            for (int i=0; i<N; i++) {
7709                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7710                if (file == null) {
7711                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7712                            "Package " + pkg.packageName + " requires unavailable shared library "
7713                            + pkg.usesLibraries.get(i) + "; failing!");
7714                }
7715                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7716            }
7717            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7718            for (int i=0; i<N; i++) {
7719                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7720                if (file == null) {
7721                    Slog.w(TAG, "Package " + pkg.packageName
7722                            + " desires unavailable shared library "
7723                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7724                } else {
7725                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7726                }
7727            }
7728            N = usesLibraryFiles.size();
7729            if (N > 0) {
7730                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7731            } else {
7732                pkg.usesLibraryFiles = null;
7733            }
7734        }
7735    }
7736
7737    private static boolean hasString(List<String> list, List<String> which) {
7738        if (list == null) {
7739            return false;
7740        }
7741        for (int i=list.size()-1; i>=0; i--) {
7742            for (int j=which.size()-1; j>=0; j--) {
7743                if (which.get(j).equals(list.get(i))) {
7744                    return true;
7745                }
7746            }
7747        }
7748        return false;
7749    }
7750
7751    private void updateAllSharedLibrariesLPw() {
7752        for (PackageParser.Package pkg : mPackages.values()) {
7753            try {
7754                updateSharedLibrariesLPw(pkg, null);
7755            } catch (PackageManagerException e) {
7756                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7757            }
7758        }
7759    }
7760
7761    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7762            PackageParser.Package changingPkg) {
7763        ArrayList<PackageParser.Package> res = null;
7764        for (PackageParser.Package pkg : mPackages.values()) {
7765            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7766                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7767                if (res == null) {
7768                    res = new ArrayList<PackageParser.Package>();
7769                }
7770                res.add(pkg);
7771                try {
7772                    updateSharedLibrariesLPw(pkg, changingPkg);
7773                } catch (PackageManagerException e) {
7774                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7775                }
7776            }
7777        }
7778        return res;
7779    }
7780
7781    /**
7782     * Derive the value of the {@code cpuAbiOverride} based on the provided
7783     * value and an optional stored value from the package settings.
7784     */
7785    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7786        String cpuAbiOverride = null;
7787
7788        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7789            cpuAbiOverride = null;
7790        } else if (abiOverride != null) {
7791            cpuAbiOverride = abiOverride;
7792        } else if (settings != null) {
7793            cpuAbiOverride = settings.cpuAbiOverrideString;
7794        }
7795
7796        return cpuAbiOverride;
7797    }
7798
7799    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7800            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7801                    throws PackageManagerException {
7802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7803        // If the package has children and this is the first dive in the function
7804        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7805        // whether all packages (parent and children) would be successfully scanned
7806        // before the actual scan since scanning mutates internal state and we want
7807        // to atomically install the package and its children.
7808        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7809            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7810                scanFlags |= SCAN_CHECK_ONLY;
7811            }
7812        } else {
7813            scanFlags &= ~SCAN_CHECK_ONLY;
7814        }
7815
7816        final PackageParser.Package scannedPkg;
7817        try {
7818            // Scan the parent
7819            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7820            // Scan the children
7821            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7822            for (int i = 0; i < childCount; i++) {
7823                PackageParser.Package childPkg = pkg.childPackages.get(i);
7824                scanPackageLI(childPkg, policyFlags,
7825                        scanFlags, currentTime, user);
7826            }
7827        } finally {
7828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7829        }
7830
7831        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7832            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7833        }
7834
7835        return scannedPkg;
7836    }
7837
7838    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7839            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7840        boolean success = false;
7841        try {
7842            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7843                    currentTime, user);
7844            success = true;
7845            return res;
7846        } finally {
7847            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7848                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7849                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7850                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7851                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7852            }
7853        }
7854    }
7855
7856    /**
7857     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7858     */
7859    private static boolean apkHasCode(String fileName) {
7860        StrictJarFile jarFile = null;
7861        try {
7862            jarFile = new StrictJarFile(fileName,
7863                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7864            return jarFile.findEntry("classes.dex") != null;
7865        } catch (IOException ignore) {
7866        } finally {
7867            try {
7868                jarFile.close();
7869            } catch (IOException ignore) {}
7870        }
7871        return false;
7872    }
7873
7874    /**
7875     * Enforces code policy for the package. This ensures that if an APK has
7876     * declared hasCode="true" in its manifest that the APK actually contains
7877     * code.
7878     *
7879     * @throws PackageManagerException If bytecode could not be found when it should exist
7880     */
7881    private static void enforceCodePolicy(PackageParser.Package pkg)
7882            throws PackageManagerException {
7883        final boolean shouldHaveCode =
7884                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7885        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7886            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7887                    "Package " + pkg.baseCodePath + " code is missing");
7888        }
7889
7890        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7891            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7892                final boolean splitShouldHaveCode =
7893                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7894                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7895                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7896                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7897                }
7898            }
7899        }
7900    }
7901
7902    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7903            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7904            throws PackageManagerException {
7905        final File scanFile = new File(pkg.codePath);
7906        if (pkg.applicationInfo.getCodePath() == null ||
7907                pkg.applicationInfo.getResourcePath() == null) {
7908            // Bail out. The resource and code paths haven't been set.
7909            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7910                    "Code and resource paths haven't been set correctly");
7911        }
7912
7913        // Apply policy
7914        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7915            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7916            if (pkg.applicationInfo.isDirectBootAware()) {
7917                // we're direct boot aware; set for all components
7918                for (PackageParser.Service s : pkg.services) {
7919                    s.info.encryptionAware = s.info.directBootAware = true;
7920                }
7921                for (PackageParser.Provider p : pkg.providers) {
7922                    p.info.encryptionAware = p.info.directBootAware = true;
7923                }
7924                for (PackageParser.Activity a : pkg.activities) {
7925                    a.info.encryptionAware = a.info.directBootAware = true;
7926                }
7927                for (PackageParser.Activity r : pkg.receivers) {
7928                    r.info.encryptionAware = r.info.directBootAware = true;
7929                }
7930            }
7931        } else {
7932            // Only allow system apps to be flagged as core apps.
7933            pkg.coreApp = false;
7934            // clear flags not applicable to regular apps
7935            pkg.applicationInfo.privateFlags &=
7936                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7937            pkg.applicationInfo.privateFlags &=
7938                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7939        }
7940        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7941
7942        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7943            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7944        }
7945
7946        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7947            enforceCodePolicy(pkg);
7948        }
7949
7950        if (mCustomResolverComponentName != null &&
7951                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7952            setUpCustomResolverActivity(pkg);
7953        }
7954
7955        if (pkg.packageName.equals("android")) {
7956            synchronized (mPackages) {
7957                if (mAndroidApplication != null) {
7958                    Slog.w(TAG, "*************************************************");
7959                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7960                    Slog.w(TAG, " file=" + scanFile);
7961                    Slog.w(TAG, "*************************************************");
7962                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7963                            "Core android package being redefined.  Skipping.");
7964                }
7965
7966                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7967                    // Set up information for our fall-back user intent resolution activity.
7968                    mPlatformPackage = pkg;
7969                    pkg.mVersionCode = mSdkVersion;
7970                    mAndroidApplication = pkg.applicationInfo;
7971
7972                    if (!mResolverReplaced) {
7973                        mResolveActivity.applicationInfo = mAndroidApplication;
7974                        mResolveActivity.name = ResolverActivity.class.getName();
7975                        mResolveActivity.packageName = mAndroidApplication.packageName;
7976                        mResolveActivity.processName = "system:ui";
7977                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7978                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7979                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7980                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7981                        mResolveActivity.exported = true;
7982                        mResolveActivity.enabled = true;
7983                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7984                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7985                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7986                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7987                                | ActivityInfo.CONFIG_ORIENTATION
7988                                | ActivityInfo.CONFIG_KEYBOARD
7989                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7990                        mResolveInfo.activityInfo = mResolveActivity;
7991                        mResolveInfo.priority = 0;
7992                        mResolveInfo.preferredOrder = 0;
7993                        mResolveInfo.match = 0;
7994                        mResolveComponentName = new ComponentName(
7995                                mAndroidApplication.packageName, mResolveActivity.name);
7996                    }
7997                }
7998            }
7999        }
8000
8001        if (DEBUG_PACKAGE_SCANNING) {
8002            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8003                Log.d(TAG, "Scanning package " + pkg.packageName);
8004        }
8005
8006        synchronized (mPackages) {
8007            if (mPackages.containsKey(pkg.packageName)
8008                    || mSharedLibraries.containsKey(pkg.packageName)) {
8009                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8010                        "Application package " + pkg.packageName
8011                                + " already installed.  Skipping duplicate.");
8012            }
8013
8014            // If we're only installing presumed-existing packages, require that the
8015            // scanned APK is both already known and at the path previously established
8016            // for it.  Previously unknown packages we pick up normally, but if we have an
8017            // a priori expectation about this package's install presence, enforce it.
8018            // With a singular exception for new system packages. When an OTA contains
8019            // a new system package, we allow the codepath to change from a system location
8020            // to the user-installed location. If we don't allow this change, any newer,
8021            // user-installed version of the application will be ignored.
8022            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8023                if (mExpectingBetter.containsKey(pkg.packageName)) {
8024                    logCriticalInfo(Log.WARN,
8025                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8026                } else {
8027                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8028                    if (known != null) {
8029                        if (DEBUG_PACKAGE_SCANNING) {
8030                            Log.d(TAG, "Examining " + pkg.codePath
8031                                    + " and requiring known paths " + known.codePathString
8032                                    + " & " + known.resourcePathString);
8033                        }
8034                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8035                                || !pkg.applicationInfo.getResourcePath().equals(
8036                                known.resourcePathString)) {
8037                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8038                                    "Application package " + pkg.packageName
8039                                            + " found at " + pkg.applicationInfo.getCodePath()
8040                                            + " but expected at " + known.codePathString
8041                                            + "; ignoring.");
8042                        }
8043                    }
8044                }
8045            }
8046        }
8047
8048        // Initialize package source and resource directories
8049        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8050        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8051
8052        SharedUserSetting suid = null;
8053        PackageSetting pkgSetting = null;
8054
8055        if (!isSystemApp(pkg)) {
8056            // Only system apps can use these features.
8057            pkg.mOriginalPackages = null;
8058            pkg.mRealPackage = null;
8059            pkg.mAdoptPermissions = null;
8060        }
8061
8062        // Getting the package setting may have a side-effect, so if we
8063        // are only checking if scan would succeed, stash a copy of the
8064        // old setting to restore at the end.
8065        PackageSetting nonMutatedPs = null;
8066
8067        // writer
8068        synchronized (mPackages) {
8069            if (pkg.mSharedUserId != null) {
8070                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8071                if (suid == null) {
8072                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8073                            "Creating application package " + pkg.packageName
8074                            + " for shared user failed");
8075                }
8076                if (DEBUG_PACKAGE_SCANNING) {
8077                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8078                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8079                                + "): packages=" + suid.packages);
8080                }
8081            }
8082
8083            // Check if we are renaming from an original package name.
8084            PackageSetting origPackage = null;
8085            String realName = null;
8086            if (pkg.mOriginalPackages != null) {
8087                // This package may need to be renamed to a previously
8088                // installed name.  Let's check on that...
8089                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8090                if (pkg.mOriginalPackages.contains(renamed)) {
8091                    // This package had originally been installed as the
8092                    // original name, and we have already taken care of
8093                    // transitioning to the new one.  Just update the new
8094                    // one to continue using the old name.
8095                    realName = pkg.mRealPackage;
8096                    if (!pkg.packageName.equals(renamed)) {
8097                        // Callers into this function may have already taken
8098                        // care of renaming the package; only do it here if
8099                        // it is not already done.
8100                        pkg.setPackageName(renamed);
8101                    }
8102
8103                } else {
8104                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8105                        if ((origPackage = mSettings.peekPackageLPr(
8106                                pkg.mOriginalPackages.get(i))) != null) {
8107                            // We do have the package already installed under its
8108                            // original name...  should we use it?
8109                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8110                                // New package is not compatible with original.
8111                                origPackage = null;
8112                                continue;
8113                            } else if (origPackage.sharedUser != null) {
8114                                // Make sure uid is compatible between packages.
8115                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8116                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8117                                            + " to " + pkg.packageName + ": old uid "
8118                                            + origPackage.sharedUser.name
8119                                            + " differs from " + pkg.mSharedUserId);
8120                                    origPackage = null;
8121                                    continue;
8122                                }
8123                                // TODO: Add case when shared user id is added [b/28144775]
8124                            } else {
8125                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8126                                        + pkg.packageName + " to old name " + origPackage.name);
8127                            }
8128                            break;
8129                        }
8130                    }
8131                }
8132            }
8133
8134            if (mTransferedPackages.contains(pkg.packageName)) {
8135                Slog.w(TAG, "Package " + pkg.packageName
8136                        + " was transferred to another, but its .apk remains");
8137            }
8138
8139            // See comments in nonMutatedPs declaration
8140            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8141                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8142                if (foundPs != null) {
8143                    nonMutatedPs = new PackageSetting(foundPs);
8144                }
8145            }
8146
8147            // Just create the setting, don't add it yet. For already existing packages
8148            // the PkgSetting exists already and doesn't have to be created.
8149            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8150                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8151                    pkg.applicationInfo.primaryCpuAbi,
8152                    pkg.applicationInfo.secondaryCpuAbi,
8153                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8154                    user, false);
8155            if (pkgSetting == null) {
8156                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8157                        "Creating application package " + pkg.packageName + " failed");
8158            }
8159
8160            if (pkgSetting.origPackage != null) {
8161                // If we are first transitioning from an original package,
8162                // fix up the new package's name now.  We need to do this after
8163                // looking up the package under its new name, so getPackageLP
8164                // can take care of fiddling things correctly.
8165                pkg.setPackageName(origPackage.name);
8166
8167                // File a report about this.
8168                String msg = "New package " + pkgSetting.realName
8169                        + " renamed to replace old package " + pkgSetting.name;
8170                reportSettingsProblem(Log.WARN, msg);
8171
8172                // Make a note of it.
8173                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8174                    mTransferedPackages.add(origPackage.name);
8175                }
8176
8177                // No longer need to retain this.
8178                pkgSetting.origPackage = null;
8179            }
8180
8181            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8182                // Make a note of it.
8183                mTransferedPackages.add(pkg.packageName);
8184            }
8185
8186            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8187                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8188            }
8189
8190            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8191                // Check all shared libraries and map to their actual file path.
8192                // We only do this here for apps not on a system dir, because those
8193                // are the only ones that can fail an install due to this.  We
8194                // will take care of the system apps by updating all of their
8195                // library paths after the scan is done.
8196                updateSharedLibrariesLPw(pkg, null);
8197            }
8198
8199            if (mFoundPolicyFile) {
8200                SELinuxMMAC.assignSeinfoValue(pkg);
8201            }
8202
8203            pkg.applicationInfo.uid = pkgSetting.appId;
8204            pkg.mExtras = pkgSetting;
8205            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8206                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8207                    // We just determined the app is signed correctly, so bring
8208                    // over the latest parsed certs.
8209                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8210                } else {
8211                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8212                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8213                                "Package " + pkg.packageName + " upgrade keys do not match the "
8214                                + "previously installed version");
8215                    } else {
8216                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8217                        String msg = "System package " + pkg.packageName
8218                            + " signature changed; retaining data.";
8219                        reportSettingsProblem(Log.WARN, msg);
8220                    }
8221                }
8222            } else {
8223                try {
8224                    verifySignaturesLP(pkgSetting, pkg);
8225                    // We just determined the app is signed correctly, so bring
8226                    // over the latest parsed certs.
8227                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8228                } catch (PackageManagerException e) {
8229                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8230                        throw e;
8231                    }
8232                    // The signature has changed, but this package is in the system
8233                    // image...  let's recover!
8234                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8235                    // However...  if this package is part of a shared user, but it
8236                    // doesn't match the signature of the shared user, let's fail.
8237                    // What this means is that you can't change the signatures
8238                    // associated with an overall shared user, which doesn't seem all
8239                    // that unreasonable.
8240                    if (pkgSetting.sharedUser != null) {
8241                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8242                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8243                            throw new PackageManagerException(
8244                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8245                                            "Signature mismatch for shared user: "
8246                                            + pkgSetting.sharedUser);
8247                        }
8248                    }
8249                    // File a report about this.
8250                    String msg = "System package " + pkg.packageName
8251                        + " signature changed; retaining data.";
8252                    reportSettingsProblem(Log.WARN, msg);
8253                }
8254            }
8255            // Verify that this new package doesn't have any content providers
8256            // that conflict with existing packages.  Only do this if the
8257            // package isn't already installed, since we don't want to break
8258            // things that are installed.
8259            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8260                final int N = pkg.providers.size();
8261                int i;
8262                for (i=0; i<N; i++) {
8263                    PackageParser.Provider p = pkg.providers.get(i);
8264                    if (p.info.authority != null) {
8265                        String names[] = p.info.authority.split(";");
8266                        for (int j = 0; j < names.length; j++) {
8267                            if (mProvidersByAuthority.containsKey(names[j])) {
8268                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8269                                final String otherPackageName =
8270                                        ((other != null && other.getComponentName() != null) ?
8271                                                other.getComponentName().getPackageName() : "?");
8272                                throw new PackageManagerException(
8273                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8274                                                "Can't install because provider name " + names[j]
8275                                                + " (in package " + pkg.applicationInfo.packageName
8276                                                + ") is already used by " + otherPackageName);
8277                            }
8278                        }
8279                    }
8280                }
8281            }
8282
8283            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8284                // This package wants to adopt ownership of permissions from
8285                // another package.
8286                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8287                    final String origName = pkg.mAdoptPermissions.get(i);
8288                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8289                    if (orig != null) {
8290                        if (verifyPackageUpdateLPr(orig, pkg)) {
8291                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8292                                    + pkg.packageName);
8293                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8294                        }
8295                    }
8296                }
8297            }
8298        }
8299
8300        final String pkgName = pkg.packageName;
8301
8302        final long scanFileTime = scanFile.lastModified();
8303        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8304        pkg.applicationInfo.processName = fixProcessName(
8305                pkg.applicationInfo.packageName,
8306                pkg.applicationInfo.processName,
8307                pkg.applicationInfo.uid);
8308
8309        if (pkg != mPlatformPackage) {
8310            // Get all of our default paths setup
8311            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8312        }
8313
8314        final String path = scanFile.getPath();
8315        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8316
8317        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8318            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8319
8320            // Some system apps still use directory structure for native libraries
8321            // in which case we might end up not detecting abi solely based on apk
8322            // structure. Try to detect abi based on directory structure.
8323            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8324                    pkg.applicationInfo.primaryCpuAbi == null) {
8325                setBundledAppAbisAndRoots(pkg, pkgSetting);
8326                setNativeLibraryPaths(pkg);
8327            }
8328
8329        } else {
8330            if ((scanFlags & SCAN_MOVE) != 0) {
8331                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8332                // but we already have this packages package info in the PackageSetting. We just
8333                // use that and derive the native library path based on the new codepath.
8334                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8335                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8336            }
8337
8338            // Set native library paths again. For moves, the path will be updated based on the
8339            // ABIs we've determined above. For non-moves, the path will be updated based on the
8340            // ABIs we determined during compilation, but the path will depend on the final
8341            // package path (after the rename away from the stage path).
8342            setNativeLibraryPaths(pkg);
8343        }
8344
8345        // This is a special case for the "system" package, where the ABI is
8346        // dictated by the zygote configuration (and init.rc). We should keep track
8347        // of this ABI so that we can deal with "normal" applications that run under
8348        // the same UID correctly.
8349        if (mPlatformPackage == pkg) {
8350            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8351                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8352        }
8353
8354        // If there's a mismatch between the abi-override in the package setting
8355        // and the abiOverride specified for the install. Warn about this because we
8356        // would've already compiled the app without taking the package setting into
8357        // account.
8358        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8359            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8360                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8361                        " for package " + pkg.packageName);
8362            }
8363        }
8364
8365        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8366        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8367        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8368
8369        // Copy the derived override back to the parsed package, so that we can
8370        // update the package settings accordingly.
8371        pkg.cpuAbiOverride = cpuAbiOverride;
8372
8373        if (DEBUG_ABI_SELECTION) {
8374            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8375                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8376                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8377        }
8378
8379        // Push the derived path down into PackageSettings so we know what to
8380        // clean up at uninstall time.
8381        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8382
8383        if (DEBUG_ABI_SELECTION) {
8384            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8385                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8386                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8387        }
8388
8389        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8390            // We don't do this here during boot because we can do it all
8391            // at once after scanning all existing packages.
8392            //
8393            // We also do this *before* we perform dexopt on this package, so that
8394            // we can avoid redundant dexopts, and also to make sure we've got the
8395            // code and package path correct.
8396            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8397                    pkg, true /* boot complete */);
8398        }
8399
8400        if (mFactoryTest && pkg.requestedPermissions.contains(
8401                android.Manifest.permission.FACTORY_TEST)) {
8402            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8403        }
8404
8405        ArrayList<PackageParser.Package> clientLibPkgs = null;
8406
8407        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8408            if (nonMutatedPs != null) {
8409                synchronized (mPackages) {
8410                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8411                }
8412            }
8413            return pkg;
8414        }
8415
8416        // Only privileged apps and updated privileged apps can add child packages.
8417        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8418            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8419                throw new PackageManagerException("Only privileged apps and updated "
8420                        + "privileged apps can add child packages. Ignoring package "
8421                        + pkg.packageName);
8422            }
8423            final int childCount = pkg.childPackages.size();
8424            for (int i = 0; i < childCount; i++) {
8425                PackageParser.Package childPkg = pkg.childPackages.get(i);
8426                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8427                        childPkg.packageName)) {
8428                    throw new PackageManagerException("Cannot override a child package of "
8429                            + "another disabled system app. Ignoring package " + pkg.packageName);
8430                }
8431            }
8432        }
8433
8434        // writer
8435        synchronized (mPackages) {
8436            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8437                // Only system apps can add new shared libraries.
8438                if (pkg.libraryNames != null) {
8439                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8440                        String name = pkg.libraryNames.get(i);
8441                        boolean allowed = false;
8442                        if (pkg.isUpdatedSystemApp()) {
8443                            // New library entries can only be added through the
8444                            // system image.  This is important to get rid of a lot
8445                            // of nasty edge cases: for example if we allowed a non-
8446                            // system update of the app to add a library, then uninstalling
8447                            // the update would make the library go away, and assumptions
8448                            // we made such as through app install filtering would now
8449                            // have allowed apps on the device which aren't compatible
8450                            // with it.  Better to just have the restriction here, be
8451                            // conservative, and create many fewer cases that can negatively
8452                            // impact the user experience.
8453                            final PackageSetting sysPs = mSettings
8454                                    .getDisabledSystemPkgLPr(pkg.packageName);
8455                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8456                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8457                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8458                                        allowed = true;
8459                                        break;
8460                                    }
8461                                }
8462                            }
8463                        } else {
8464                            allowed = true;
8465                        }
8466                        if (allowed) {
8467                            if (!mSharedLibraries.containsKey(name)) {
8468                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8469                            } else if (!name.equals(pkg.packageName)) {
8470                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8471                                        + name + " already exists; skipping");
8472                            }
8473                        } else {
8474                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8475                                    + name + " that is not declared on system image; skipping");
8476                        }
8477                    }
8478                    if ((scanFlags & SCAN_BOOTING) == 0) {
8479                        // If we are not booting, we need to update any applications
8480                        // that are clients of our shared library.  If we are booting,
8481                        // this will all be done once the scan is complete.
8482                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8483                    }
8484                }
8485            }
8486        }
8487
8488        if ((scanFlags & SCAN_BOOTING) != 0) {
8489            // No apps can run during boot scan, so they don't need to be frozen
8490        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8491            // Caller asked to not kill app, so it's probably not frozen
8492        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8493            // Caller asked us to ignore frozen check for some reason; they
8494            // probably didn't know the package name
8495        } else {
8496            // We're doing major surgery on this package, so it better be frozen
8497            // right now to keep it from launching
8498            checkPackageFrozen(pkgName);
8499        }
8500
8501        // Also need to kill any apps that are dependent on the library.
8502        if (clientLibPkgs != null) {
8503            for (int i=0; i<clientLibPkgs.size(); i++) {
8504                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8505                killApplication(clientPkg.applicationInfo.packageName,
8506                        clientPkg.applicationInfo.uid, "update lib");
8507            }
8508        }
8509
8510        // Make sure we're not adding any bogus keyset info
8511        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8512        ksms.assertScannedPackageValid(pkg);
8513
8514        // writer
8515        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8516
8517        boolean createIdmapFailed = false;
8518        synchronized (mPackages) {
8519            // We don't expect installation to fail beyond this point
8520
8521            // Add the new setting to mSettings
8522            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8523            // Add the new setting to mPackages
8524            mPackages.put(pkg.applicationInfo.packageName, pkg);
8525            // Make sure we don't accidentally delete its data.
8526            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8527            while (iter.hasNext()) {
8528                PackageCleanItem item = iter.next();
8529                if (pkgName.equals(item.packageName)) {
8530                    iter.remove();
8531                }
8532            }
8533
8534            // Take care of first install / last update times.
8535            if (currentTime != 0) {
8536                if (pkgSetting.firstInstallTime == 0) {
8537                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8538                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8539                    pkgSetting.lastUpdateTime = currentTime;
8540                }
8541            } else if (pkgSetting.firstInstallTime == 0) {
8542                // We need *something*.  Take time time stamp of the file.
8543                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8544            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8545                if (scanFileTime != pkgSetting.timeStamp) {
8546                    // A package on the system image has changed; consider this
8547                    // to be an update.
8548                    pkgSetting.lastUpdateTime = scanFileTime;
8549                }
8550            }
8551
8552            // Add the package's KeySets to the global KeySetManagerService
8553            ksms.addScannedPackageLPw(pkg);
8554
8555            int N = pkg.providers.size();
8556            StringBuilder r = null;
8557            int i;
8558            for (i=0; i<N; i++) {
8559                PackageParser.Provider p = pkg.providers.get(i);
8560                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8561                        p.info.processName, pkg.applicationInfo.uid);
8562                mProviders.addProvider(p);
8563                p.syncable = p.info.isSyncable;
8564                if (p.info.authority != null) {
8565                    String names[] = p.info.authority.split(";");
8566                    p.info.authority = null;
8567                    for (int j = 0; j < names.length; j++) {
8568                        if (j == 1 && p.syncable) {
8569                            // We only want the first authority for a provider to possibly be
8570                            // syncable, so if we already added this provider using a different
8571                            // authority clear the syncable flag. We copy the provider before
8572                            // changing it because the mProviders object contains a reference
8573                            // to a provider that we don't want to change.
8574                            // Only do this for the second authority since the resulting provider
8575                            // object can be the same for all future authorities for this provider.
8576                            p = new PackageParser.Provider(p);
8577                            p.syncable = false;
8578                        }
8579                        if (!mProvidersByAuthority.containsKey(names[j])) {
8580                            mProvidersByAuthority.put(names[j], p);
8581                            if (p.info.authority == null) {
8582                                p.info.authority = names[j];
8583                            } else {
8584                                p.info.authority = p.info.authority + ";" + names[j];
8585                            }
8586                            if (DEBUG_PACKAGE_SCANNING) {
8587                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8588                                    Log.d(TAG, "Registered content provider: " + names[j]
8589                                            + ", className = " + p.info.name + ", isSyncable = "
8590                                            + p.info.isSyncable);
8591                            }
8592                        } else {
8593                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8594                            Slog.w(TAG, "Skipping provider name " + names[j] +
8595                                    " (in package " + pkg.applicationInfo.packageName +
8596                                    "): name already used by "
8597                                    + ((other != null && other.getComponentName() != null)
8598                                            ? other.getComponentName().getPackageName() : "?"));
8599                        }
8600                    }
8601                }
8602                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8603                    if (r == null) {
8604                        r = new StringBuilder(256);
8605                    } else {
8606                        r.append(' ');
8607                    }
8608                    r.append(p.info.name);
8609                }
8610            }
8611            if (r != null) {
8612                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8613            }
8614
8615            N = pkg.services.size();
8616            r = null;
8617            for (i=0; i<N; i++) {
8618                PackageParser.Service s = pkg.services.get(i);
8619                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8620                        s.info.processName, pkg.applicationInfo.uid);
8621                mServices.addService(s);
8622                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8623                    if (r == null) {
8624                        r = new StringBuilder(256);
8625                    } else {
8626                        r.append(' ');
8627                    }
8628                    r.append(s.info.name);
8629                }
8630            }
8631            if (r != null) {
8632                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8633            }
8634
8635            N = pkg.receivers.size();
8636            r = null;
8637            for (i=0; i<N; i++) {
8638                PackageParser.Activity a = pkg.receivers.get(i);
8639                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8640                        a.info.processName, pkg.applicationInfo.uid);
8641                mReceivers.addActivity(a, "receiver");
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(a.info.name);
8649                }
8650            }
8651            if (r != null) {
8652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8653            }
8654
8655            N = pkg.activities.size();
8656            r = null;
8657            for (i=0; i<N; i++) {
8658                PackageParser.Activity a = pkg.activities.get(i);
8659                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8660                        a.info.processName, pkg.applicationInfo.uid);
8661                mActivities.addActivity(a, "activity");
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(a.info.name);
8669                }
8670            }
8671            if (r != null) {
8672                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8673            }
8674
8675            N = pkg.permissionGroups.size();
8676            r = null;
8677            for (i=0; i<N; i++) {
8678                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8679                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8680                if (cur == null) {
8681                    mPermissionGroups.put(pg.info.name, pg);
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(pg.info.name);
8689                    }
8690                } else {
8691                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8692                            + pg.info.packageName + " ignored: original from "
8693                            + cur.info.packageName);
8694                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8695                        if (r == null) {
8696                            r = new StringBuilder(256);
8697                        } else {
8698                            r.append(' ');
8699                        }
8700                        r.append("DUP:");
8701                        r.append(pg.info.name);
8702                    }
8703                }
8704            }
8705            if (r != null) {
8706                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8707            }
8708
8709            N = pkg.permissions.size();
8710            r = null;
8711            for (i=0; i<N; i++) {
8712                PackageParser.Permission p = pkg.permissions.get(i);
8713
8714                // Assume by default that we did not install this permission into the system.
8715                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8716
8717                // Now that permission groups have a special meaning, we ignore permission
8718                // groups for legacy apps to prevent unexpected behavior. In particular,
8719                // permissions for one app being granted to someone just becase they happen
8720                // to be in a group defined by another app (before this had no implications).
8721                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8722                    p.group = mPermissionGroups.get(p.info.group);
8723                    // Warn for a permission in an unknown group.
8724                    if (p.info.group != null && p.group == null) {
8725                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8726                                + p.info.packageName + " in an unknown group " + p.info.group);
8727                    }
8728                }
8729
8730                ArrayMap<String, BasePermission> permissionMap =
8731                        p.tree ? mSettings.mPermissionTrees
8732                                : mSettings.mPermissions;
8733                BasePermission bp = permissionMap.get(p.info.name);
8734
8735                // Allow system apps to redefine non-system permissions
8736                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8737                    final boolean currentOwnerIsSystem = (bp.perm != null
8738                            && isSystemApp(bp.perm.owner));
8739                    if (isSystemApp(p.owner)) {
8740                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8741                            // It's a built-in permission and no owner, take ownership now
8742                            bp.packageSetting = pkgSetting;
8743                            bp.perm = p;
8744                            bp.uid = pkg.applicationInfo.uid;
8745                            bp.sourcePackage = p.info.packageName;
8746                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8747                        } else if (!currentOwnerIsSystem) {
8748                            String msg = "New decl " + p.owner + " of permission  "
8749                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8750                            reportSettingsProblem(Log.WARN, msg);
8751                            bp = null;
8752                        }
8753                    }
8754                }
8755
8756                if (bp == null) {
8757                    bp = new BasePermission(p.info.name, p.info.packageName,
8758                            BasePermission.TYPE_NORMAL);
8759                    permissionMap.put(p.info.name, bp);
8760                }
8761
8762                if (bp.perm == null) {
8763                    if (bp.sourcePackage == null
8764                            || bp.sourcePackage.equals(p.info.packageName)) {
8765                        BasePermission tree = findPermissionTreeLP(p.info.name);
8766                        if (tree == null
8767                                || tree.sourcePackage.equals(p.info.packageName)) {
8768                            bp.packageSetting = pkgSetting;
8769                            bp.perm = p;
8770                            bp.uid = pkg.applicationInfo.uid;
8771                            bp.sourcePackage = p.info.packageName;
8772                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8773                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8774                                if (r == null) {
8775                                    r = new StringBuilder(256);
8776                                } else {
8777                                    r.append(' ');
8778                                }
8779                                r.append(p.info.name);
8780                            }
8781                        } else {
8782                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8783                                    + p.info.packageName + " ignored: base tree "
8784                                    + tree.name + " is from package "
8785                                    + tree.sourcePackage);
8786                        }
8787                    } else {
8788                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8789                                + p.info.packageName + " ignored: original from "
8790                                + bp.sourcePackage);
8791                    }
8792                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8793                    if (r == null) {
8794                        r = new StringBuilder(256);
8795                    } else {
8796                        r.append(' ');
8797                    }
8798                    r.append("DUP:");
8799                    r.append(p.info.name);
8800                }
8801                if (bp.perm == p) {
8802                    bp.protectionLevel = p.info.protectionLevel;
8803                }
8804            }
8805
8806            if (r != null) {
8807                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8808            }
8809
8810            N = pkg.instrumentation.size();
8811            r = null;
8812            for (i=0; i<N; i++) {
8813                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8814                a.info.packageName = pkg.applicationInfo.packageName;
8815                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8816                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8817                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8818                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8819                a.info.dataDir = pkg.applicationInfo.dataDir;
8820                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8821                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8822
8823                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8824                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8825                mInstrumentation.put(a.getComponentName(), a);
8826                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8827                    if (r == null) {
8828                        r = new StringBuilder(256);
8829                    } else {
8830                        r.append(' ');
8831                    }
8832                    r.append(a.info.name);
8833                }
8834            }
8835            if (r != null) {
8836                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8837            }
8838
8839            if (pkg.protectedBroadcasts != null) {
8840                N = pkg.protectedBroadcasts.size();
8841                for (i=0; i<N; i++) {
8842                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8843                }
8844            }
8845
8846            pkgSetting.setTimeStamp(scanFileTime);
8847
8848            // Create idmap files for pairs of (packages, overlay packages).
8849            // Note: "android", ie framework-res.apk, is handled by native layers.
8850            if (pkg.mOverlayTarget != null) {
8851                // This is an overlay package.
8852                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8853                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8854                        mOverlays.put(pkg.mOverlayTarget,
8855                                new ArrayMap<String, PackageParser.Package>());
8856                    }
8857                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8858                    map.put(pkg.packageName, pkg);
8859                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8860                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8861                        createIdmapFailed = true;
8862                    }
8863                }
8864            } else if (mOverlays.containsKey(pkg.packageName) &&
8865                    !pkg.packageName.equals("android")) {
8866                // This is a regular package, with one or more known overlay packages.
8867                createIdmapsForPackageLI(pkg);
8868            }
8869        }
8870
8871        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8872
8873        if (createIdmapFailed) {
8874            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8875                    "scanPackageLI failed to createIdmap");
8876        }
8877        return pkg;
8878    }
8879
8880    /**
8881     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8882     * is derived purely on the basis of the contents of {@code scanFile} and
8883     * {@code cpuAbiOverride}.
8884     *
8885     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8886     */
8887    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8888                                 String cpuAbiOverride, boolean extractLibs)
8889            throws PackageManagerException {
8890        // TODO: We can probably be smarter about this stuff. For installed apps,
8891        // we can calculate this information at install time once and for all. For
8892        // system apps, we can probably assume that this information doesn't change
8893        // after the first boot scan. As things stand, we do lots of unnecessary work.
8894
8895        // Give ourselves some initial paths; we'll come back for another
8896        // pass once we've determined ABI below.
8897        setNativeLibraryPaths(pkg);
8898
8899        // We would never need to extract libs for forward-locked and external packages,
8900        // since the container service will do it for us. We shouldn't attempt to
8901        // extract libs from system app when it was not updated.
8902        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8903                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8904            extractLibs = false;
8905        }
8906
8907        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8908        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8909
8910        NativeLibraryHelper.Handle handle = null;
8911        try {
8912            handle = NativeLibraryHelper.Handle.create(pkg);
8913            // TODO(multiArch): This can be null for apps that didn't go through the
8914            // usual installation process. We can calculate it again, like we
8915            // do during install time.
8916            //
8917            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8918            // unnecessary.
8919            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8920
8921            // Null out the abis so that they can be recalculated.
8922            pkg.applicationInfo.primaryCpuAbi = null;
8923            pkg.applicationInfo.secondaryCpuAbi = null;
8924            if (isMultiArch(pkg.applicationInfo)) {
8925                // Warn if we've set an abiOverride for multi-lib packages..
8926                // By definition, we need to copy both 32 and 64 bit libraries for
8927                // such packages.
8928                if (pkg.cpuAbiOverride != null
8929                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8930                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8931                }
8932
8933                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8934                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8935                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8936                    if (extractLibs) {
8937                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8938                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8939                                useIsaSpecificSubdirs);
8940                    } else {
8941                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8942                    }
8943                }
8944
8945                maybeThrowExceptionForMultiArchCopy(
8946                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8947
8948                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8949                    if (extractLibs) {
8950                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8951                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8952                                useIsaSpecificSubdirs);
8953                    } else {
8954                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8955                    }
8956                }
8957
8958                maybeThrowExceptionForMultiArchCopy(
8959                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8960
8961                if (abi64 >= 0) {
8962                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8963                }
8964
8965                if (abi32 >= 0) {
8966                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8967                    if (abi64 >= 0) {
8968                        if (pkg.use32bitAbi) {
8969                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8970                            pkg.applicationInfo.primaryCpuAbi = abi;
8971                        } else {
8972                            pkg.applicationInfo.secondaryCpuAbi = abi;
8973                        }
8974                    } else {
8975                        pkg.applicationInfo.primaryCpuAbi = abi;
8976                    }
8977                }
8978
8979            } else {
8980                String[] abiList = (cpuAbiOverride != null) ?
8981                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8982
8983                // Enable gross and lame hacks for apps that are built with old
8984                // SDK tools. We must scan their APKs for renderscript bitcode and
8985                // not launch them if it's present. Don't bother checking on devices
8986                // that don't have 64 bit support.
8987                boolean needsRenderScriptOverride = false;
8988                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8989                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8990                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8991                    needsRenderScriptOverride = true;
8992                }
8993
8994                final int copyRet;
8995                if (extractLibs) {
8996                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8997                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8998                } else {
8999                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9000                }
9001
9002                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9003                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9004                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9005                }
9006
9007                if (copyRet >= 0) {
9008                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9009                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9010                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9011                } else if (needsRenderScriptOverride) {
9012                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9013                }
9014            }
9015        } catch (IOException ioe) {
9016            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9017        } finally {
9018            IoUtils.closeQuietly(handle);
9019        }
9020
9021        // Now that we've calculated the ABIs and determined if it's an internal app,
9022        // we will go ahead and populate the nativeLibraryPath.
9023        setNativeLibraryPaths(pkg);
9024    }
9025
9026    /**
9027     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9028     * i.e, so that all packages can be run inside a single process if required.
9029     *
9030     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9031     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9032     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9033     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9034     * updating a package that belongs to a shared user.
9035     *
9036     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9037     * adds unnecessary complexity.
9038     */
9039    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9040            PackageParser.Package scannedPackage, boolean bootComplete) {
9041        String requiredInstructionSet = null;
9042        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9043            requiredInstructionSet = VMRuntime.getInstructionSet(
9044                     scannedPackage.applicationInfo.primaryCpuAbi);
9045        }
9046
9047        PackageSetting requirer = null;
9048        for (PackageSetting ps : packagesForUser) {
9049            // If packagesForUser contains scannedPackage, we skip it. This will happen
9050            // when scannedPackage is an update of an existing package. Without this check,
9051            // we will never be able to change the ABI of any package belonging to a shared
9052            // user, even if it's compatible with other packages.
9053            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9054                if (ps.primaryCpuAbiString == null) {
9055                    continue;
9056                }
9057
9058                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9059                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9060                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9061                    // this but there's not much we can do.
9062                    String errorMessage = "Instruction set mismatch, "
9063                            + ((requirer == null) ? "[caller]" : requirer)
9064                            + " requires " + requiredInstructionSet + " whereas " + ps
9065                            + " requires " + instructionSet;
9066                    Slog.w(TAG, errorMessage);
9067                }
9068
9069                if (requiredInstructionSet == null) {
9070                    requiredInstructionSet = instructionSet;
9071                    requirer = ps;
9072                }
9073            }
9074        }
9075
9076        if (requiredInstructionSet != null) {
9077            String adjustedAbi;
9078            if (requirer != null) {
9079                // requirer != null implies that either scannedPackage was null or that scannedPackage
9080                // did not require an ABI, in which case we have to adjust scannedPackage to match
9081                // the ABI of the set (which is the same as requirer's ABI)
9082                adjustedAbi = requirer.primaryCpuAbiString;
9083                if (scannedPackage != null) {
9084                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9085                }
9086            } else {
9087                // requirer == null implies that we're updating all ABIs in the set to
9088                // match scannedPackage.
9089                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9090            }
9091
9092            for (PackageSetting ps : packagesForUser) {
9093                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9094                    if (ps.primaryCpuAbiString != null) {
9095                        continue;
9096                    }
9097
9098                    ps.primaryCpuAbiString = adjustedAbi;
9099                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9100                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9101                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9102                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9103                                + " (requirer="
9104                                + (requirer == null ? "null" : requirer.pkg.packageName)
9105                                + ", scannedPackage="
9106                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9107                                + ")");
9108                        try {
9109                            mInstaller.rmdex(ps.codePathString,
9110                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9111                        } catch (InstallerException ignored) {
9112                        }
9113                    }
9114                }
9115            }
9116        }
9117    }
9118
9119    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9120        synchronized (mPackages) {
9121            mResolverReplaced = true;
9122            // Set up information for custom user intent resolution activity.
9123            mResolveActivity.applicationInfo = pkg.applicationInfo;
9124            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9125            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9126            mResolveActivity.processName = pkg.applicationInfo.packageName;
9127            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9128            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9129                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9130            mResolveActivity.theme = 0;
9131            mResolveActivity.exported = true;
9132            mResolveActivity.enabled = true;
9133            mResolveInfo.activityInfo = mResolveActivity;
9134            mResolveInfo.priority = 0;
9135            mResolveInfo.preferredOrder = 0;
9136            mResolveInfo.match = 0;
9137            mResolveComponentName = mCustomResolverComponentName;
9138            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9139                    mResolveComponentName);
9140        }
9141    }
9142
9143    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9144        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9145
9146        // Set up information for ephemeral installer activity
9147        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9148        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9149        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9150        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9151        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9152        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9153                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9154        mEphemeralInstallerActivity.theme = 0;
9155        mEphemeralInstallerActivity.exported = true;
9156        mEphemeralInstallerActivity.enabled = true;
9157        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9158        mEphemeralInstallerInfo.priority = 0;
9159        mEphemeralInstallerInfo.preferredOrder = 0;
9160        mEphemeralInstallerInfo.match = 0;
9161
9162        if (DEBUG_EPHEMERAL) {
9163            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9164        }
9165    }
9166
9167    private static String calculateBundledApkRoot(final String codePathString) {
9168        final File codePath = new File(codePathString);
9169        final File codeRoot;
9170        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9171            codeRoot = Environment.getRootDirectory();
9172        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9173            codeRoot = Environment.getOemDirectory();
9174        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9175            codeRoot = Environment.getVendorDirectory();
9176        } else {
9177            // Unrecognized code path; take its top real segment as the apk root:
9178            // e.g. /something/app/blah.apk => /something
9179            try {
9180                File f = codePath.getCanonicalFile();
9181                File parent = f.getParentFile();    // non-null because codePath is a file
9182                File tmp;
9183                while ((tmp = parent.getParentFile()) != null) {
9184                    f = parent;
9185                    parent = tmp;
9186                }
9187                codeRoot = f;
9188                Slog.w(TAG, "Unrecognized code path "
9189                        + codePath + " - using " + codeRoot);
9190            } catch (IOException e) {
9191                // Can't canonicalize the code path -- shenanigans?
9192                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9193                return Environment.getRootDirectory().getPath();
9194            }
9195        }
9196        return codeRoot.getPath();
9197    }
9198
9199    /**
9200     * Derive and set the location of native libraries for the given package,
9201     * which varies depending on where and how the package was installed.
9202     */
9203    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9204        final ApplicationInfo info = pkg.applicationInfo;
9205        final String codePath = pkg.codePath;
9206        final File codeFile = new File(codePath);
9207        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9208        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9209
9210        info.nativeLibraryRootDir = null;
9211        info.nativeLibraryRootRequiresIsa = false;
9212        info.nativeLibraryDir = null;
9213        info.secondaryNativeLibraryDir = null;
9214
9215        if (isApkFile(codeFile)) {
9216            // Monolithic install
9217            if (bundledApp) {
9218                // If "/system/lib64/apkname" exists, assume that is the per-package
9219                // native library directory to use; otherwise use "/system/lib/apkname".
9220                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9221                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9222                        getPrimaryInstructionSet(info));
9223
9224                // This is a bundled system app so choose the path based on the ABI.
9225                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9226                // is just the default path.
9227                final String apkName = deriveCodePathName(codePath);
9228                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9229                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9230                        apkName).getAbsolutePath();
9231
9232                if (info.secondaryCpuAbi != null) {
9233                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9234                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9235                            secondaryLibDir, apkName).getAbsolutePath();
9236                }
9237            } else if (asecApp) {
9238                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9239                        .getAbsolutePath();
9240            } else {
9241                final String apkName = deriveCodePathName(codePath);
9242                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9243                        .getAbsolutePath();
9244            }
9245
9246            info.nativeLibraryRootRequiresIsa = false;
9247            info.nativeLibraryDir = info.nativeLibraryRootDir;
9248        } else {
9249            // Cluster install
9250            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9251            info.nativeLibraryRootRequiresIsa = true;
9252
9253            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9254                    getPrimaryInstructionSet(info)).getAbsolutePath();
9255
9256            if (info.secondaryCpuAbi != null) {
9257                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9258                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9259            }
9260        }
9261    }
9262
9263    /**
9264     * Calculate the abis and roots for a bundled app. These can uniquely
9265     * be determined from the contents of the system partition, i.e whether
9266     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9267     * of this information, and instead assume that the system was built
9268     * sensibly.
9269     */
9270    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9271                                           PackageSetting pkgSetting) {
9272        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9273
9274        // If "/system/lib64/apkname" exists, assume that is the per-package
9275        // native library directory to use; otherwise use "/system/lib/apkname".
9276        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9277        setBundledAppAbi(pkg, apkRoot, apkName);
9278        // pkgSetting might be null during rescan following uninstall of updates
9279        // to a bundled app, so accommodate that possibility.  The settings in
9280        // that case will be established later from the parsed package.
9281        //
9282        // If the settings aren't null, sync them up with what we've just derived.
9283        // note that apkRoot isn't stored in the package settings.
9284        if (pkgSetting != null) {
9285            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9286            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9287        }
9288    }
9289
9290    /**
9291     * Deduces the ABI of a bundled app and sets the relevant fields on the
9292     * parsed pkg object.
9293     *
9294     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9295     *        under which system libraries are installed.
9296     * @param apkName the name of the installed package.
9297     */
9298    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9299        final File codeFile = new File(pkg.codePath);
9300
9301        final boolean has64BitLibs;
9302        final boolean has32BitLibs;
9303        if (isApkFile(codeFile)) {
9304            // Monolithic install
9305            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9306            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9307        } else {
9308            // Cluster install
9309            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9310            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9311                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9312                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9313                has64BitLibs = (new File(rootDir, isa)).exists();
9314            } else {
9315                has64BitLibs = false;
9316            }
9317            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9318                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9319                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9320                has32BitLibs = (new File(rootDir, isa)).exists();
9321            } else {
9322                has32BitLibs = false;
9323            }
9324        }
9325
9326        if (has64BitLibs && !has32BitLibs) {
9327            // The package has 64 bit libs, but not 32 bit libs. Its primary
9328            // ABI should be 64 bit. We can safely assume here that the bundled
9329            // native libraries correspond to the most preferred ABI in the list.
9330
9331            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9332            pkg.applicationInfo.secondaryCpuAbi = null;
9333        } else if (has32BitLibs && !has64BitLibs) {
9334            // The package has 32 bit libs but not 64 bit libs. Its primary
9335            // ABI should be 32 bit.
9336
9337            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9338            pkg.applicationInfo.secondaryCpuAbi = null;
9339        } else if (has32BitLibs && has64BitLibs) {
9340            // The application has both 64 and 32 bit bundled libraries. We check
9341            // here that the app declares multiArch support, and warn if it doesn't.
9342            //
9343            // We will be lenient here and record both ABIs. The primary will be the
9344            // ABI that's higher on the list, i.e, a device that's configured to prefer
9345            // 64 bit apps will see a 64 bit primary ABI,
9346
9347            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9348                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9349            }
9350
9351            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9352                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9353                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9354            } else {
9355                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9356                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9357            }
9358        } else {
9359            pkg.applicationInfo.primaryCpuAbi = null;
9360            pkg.applicationInfo.secondaryCpuAbi = null;
9361        }
9362    }
9363
9364    private void killApplication(String pkgName, int appId, String reason) {
9365        // Request the ActivityManager to kill the process(only for existing packages)
9366        // so that we do not end up in a confused state while the user is still using the older
9367        // version of the application while the new one gets installed.
9368        final long token = Binder.clearCallingIdentity();
9369        try {
9370            IActivityManager am = ActivityManagerNative.getDefault();
9371            if (am != null) {
9372                try {
9373                    am.killApplicationWithAppId(pkgName, appId, reason);
9374                } catch (RemoteException e) {
9375                }
9376            }
9377        } finally {
9378            Binder.restoreCallingIdentity(token);
9379        }
9380    }
9381
9382    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9383        // Remove the parent package setting
9384        PackageSetting ps = (PackageSetting) pkg.mExtras;
9385        if (ps != null) {
9386            removePackageLI(ps, chatty);
9387        }
9388        // Remove the child package setting
9389        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9390        for (int i = 0; i < childCount; i++) {
9391            PackageParser.Package childPkg = pkg.childPackages.get(i);
9392            ps = (PackageSetting) childPkg.mExtras;
9393            if (ps != null) {
9394                removePackageLI(ps, chatty);
9395            }
9396        }
9397    }
9398
9399    void removePackageLI(PackageSetting ps, boolean chatty) {
9400        if (DEBUG_INSTALL) {
9401            if (chatty)
9402                Log.d(TAG, "Removing package " + ps.name);
9403        }
9404
9405        // writer
9406        synchronized (mPackages) {
9407            mPackages.remove(ps.name);
9408            final PackageParser.Package pkg = ps.pkg;
9409            if (pkg != null) {
9410                cleanPackageDataStructuresLILPw(pkg, chatty);
9411            }
9412        }
9413    }
9414
9415    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9416        if (DEBUG_INSTALL) {
9417            if (chatty)
9418                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9419        }
9420
9421        // writer
9422        synchronized (mPackages) {
9423            // Remove the parent package
9424            mPackages.remove(pkg.applicationInfo.packageName);
9425            cleanPackageDataStructuresLILPw(pkg, chatty);
9426
9427            // Remove the child packages
9428            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9429            for (int i = 0; i < childCount; i++) {
9430                PackageParser.Package childPkg = pkg.childPackages.get(i);
9431                mPackages.remove(childPkg.applicationInfo.packageName);
9432                cleanPackageDataStructuresLILPw(childPkg, chatty);
9433            }
9434        }
9435    }
9436
9437    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9438        int N = pkg.providers.size();
9439        StringBuilder r = null;
9440        int i;
9441        for (i=0; i<N; i++) {
9442            PackageParser.Provider p = pkg.providers.get(i);
9443            mProviders.removeProvider(p);
9444            if (p.info.authority == null) {
9445
9446                /* There was another ContentProvider with this authority when
9447                 * this app was installed so this authority is null,
9448                 * Ignore it as we don't have to unregister the provider.
9449                 */
9450                continue;
9451            }
9452            String names[] = p.info.authority.split(";");
9453            for (int j = 0; j < names.length; j++) {
9454                if (mProvidersByAuthority.get(names[j]) == p) {
9455                    mProvidersByAuthority.remove(names[j]);
9456                    if (DEBUG_REMOVE) {
9457                        if (chatty)
9458                            Log.d(TAG, "Unregistered content provider: " + names[j]
9459                                    + ", className = " + p.info.name + ", isSyncable = "
9460                                    + p.info.isSyncable);
9461                    }
9462                }
9463            }
9464            if (DEBUG_REMOVE && chatty) {
9465                if (r == null) {
9466                    r = new StringBuilder(256);
9467                } else {
9468                    r.append(' ');
9469                }
9470                r.append(p.info.name);
9471            }
9472        }
9473        if (r != null) {
9474            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9475        }
9476
9477        N = pkg.services.size();
9478        r = null;
9479        for (i=0; i<N; i++) {
9480            PackageParser.Service s = pkg.services.get(i);
9481            mServices.removeService(s);
9482            if (chatty) {
9483                if (r == null) {
9484                    r = new StringBuilder(256);
9485                } else {
9486                    r.append(' ');
9487                }
9488                r.append(s.info.name);
9489            }
9490        }
9491        if (r != null) {
9492            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9493        }
9494
9495        N = pkg.receivers.size();
9496        r = null;
9497        for (i=0; i<N; i++) {
9498            PackageParser.Activity a = pkg.receivers.get(i);
9499            mReceivers.removeActivity(a, "receiver");
9500            if (DEBUG_REMOVE && chatty) {
9501                if (r == null) {
9502                    r = new StringBuilder(256);
9503                } else {
9504                    r.append(' ');
9505                }
9506                r.append(a.info.name);
9507            }
9508        }
9509        if (r != null) {
9510            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9511        }
9512
9513        N = pkg.activities.size();
9514        r = null;
9515        for (i=0; i<N; i++) {
9516            PackageParser.Activity a = pkg.activities.get(i);
9517            mActivities.removeActivity(a, "activity");
9518            if (DEBUG_REMOVE && chatty) {
9519                if (r == null) {
9520                    r = new StringBuilder(256);
9521                } else {
9522                    r.append(' ');
9523                }
9524                r.append(a.info.name);
9525            }
9526        }
9527        if (r != null) {
9528            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9529        }
9530
9531        N = pkg.permissions.size();
9532        r = null;
9533        for (i=0; i<N; i++) {
9534            PackageParser.Permission p = pkg.permissions.get(i);
9535            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9536            if (bp == null) {
9537                bp = mSettings.mPermissionTrees.get(p.info.name);
9538            }
9539            if (bp != null && bp.perm == p) {
9540                bp.perm = null;
9541                if (DEBUG_REMOVE && chatty) {
9542                    if (r == null) {
9543                        r = new StringBuilder(256);
9544                    } else {
9545                        r.append(' ');
9546                    }
9547                    r.append(p.info.name);
9548                }
9549            }
9550            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9551                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9552                if (appOpPkgs != null) {
9553                    appOpPkgs.remove(pkg.packageName);
9554                }
9555            }
9556        }
9557        if (r != null) {
9558            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9559        }
9560
9561        N = pkg.requestedPermissions.size();
9562        r = null;
9563        for (i=0; i<N; i++) {
9564            String perm = pkg.requestedPermissions.get(i);
9565            BasePermission bp = mSettings.mPermissions.get(perm);
9566            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9567                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9568                if (appOpPkgs != null) {
9569                    appOpPkgs.remove(pkg.packageName);
9570                    if (appOpPkgs.isEmpty()) {
9571                        mAppOpPermissionPackages.remove(perm);
9572                    }
9573                }
9574            }
9575        }
9576        if (r != null) {
9577            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9578        }
9579
9580        N = pkg.instrumentation.size();
9581        r = null;
9582        for (i=0; i<N; i++) {
9583            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9584            mInstrumentation.remove(a.getComponentName());
9585            if (DEBUG_REMOVE && chatty) {
9586                if (r == null) {
9587                    r = new StringBuilder(256);
9588                } else {
9589                    r.append(' ');
9590                }
9591                r.append(a.info.name);
9592            }
9593        }
9594        if (r != null) {
9595            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9596        }
9597
9598        r = null;
9599        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9600            // Only system apps can hold shared libraries.
9601            if (pkg.libraryNames != null) {
9602                for (i=0; i<pkg.libraryNames.size(); i++) {
9603                    String name = pkg.libraryNames.get(i);
9604                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9605                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9606                        mSharedLibraries.remove(name);
9607                        if (DEBUG_REMOVE && chatty) {
9608                            if (r == null) {
9609                                r = new StringBuilder(256);
9610                            } else {
9611                                r.append(' ');
9612                            }
9613                            r.append(name);
9614                        }
9615                    }
9616                }
9617            }
9618        }
9619        if (r != null) {
9620            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9621        }
9622    }
9623
9624    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9625        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9626            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9627                return true;
9628            }
9629        }
9630        return false;
9631    }
9632
9633    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9634    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9635    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9636
9637    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9638        // Update the parent permissions
9639        updatePermissionsLPw(pkg.packageName, pkg, flags);
9640        // Update the child permissions
9641        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9642        for (int i = 0; i < childCount; i++) {
9643            PackageParser.Package childPkg = pkg.childPackages.get(i);
9644            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9645        }
9646    }
9647
9648    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9649            int flags) {
9650        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9651        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9652    }
9653
9654    private void updatePermissionsLPw(String changingPkg,
9655            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9656        // Make sure there are no dangling permission trees.
9657        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9658        while (it.hasNext()) {
9659            final BasePermission bp = it.next();
9660            if (bp.packageSetting == null) {
9661                // We may not yet have parsed the package, so just see if
9662                // we still know about its settings.
9663                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9664            }
9665            if (bp.packageSetting == null) {
9666                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9667                        + " from package " + bp.sourcePackage);
9668                it.remove();
9669            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9670                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9671                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9672                            + " from package " + bp.sourcePackage);
9673                    flags |= UPDATE_PERMISSIONS_ALL;
9674                    it.remove();
9675                }
9676            }
9677        }
9678
9679        // Make sure all dynamic permissions have been assigned to a package,
9680        // and make sure there are no dangling permissions.
9681        it = mSettings.mPermissions.values().iterator();
9682        while (it.hasNext()) {
9683            final BasePermission bp = it.next();
9684            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9685                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9686                        + bp.name + " pkg=" + bp.sourcePackage
9687                        + " info=" + bp.pendingInfo);
9688                if (bp.packageSetting == null && bp.pendingInfo != null) {
9689                    final BasePermission tree = findPermissionTreeLP(bp.name);
9690                    if (tree != null && tree.perm != null) {
9691                        bp.packageSetting = tree.packageSetting;
9692                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9693                                new PermissionInfo(bp.pendingInfo));
9694                        bp.perm.info.packageName = tree.perm.info.packageName;
9695                        bp.perm.info.name = bp.name;
9696                        bp.uid = tree.uid;
9697                    }
9698                }
9699            }
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: " + 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: " + bp.name
9712                            + " from package " + bp.sourcePackage);
9713                    flags |= UPDATE_PERMISSIONS_ALL;
9714                    it.remove();
9715                }
9716            }
9717        }
9718
9719        // Now update the permissions for all packages, in particular
9720        // replace the granted permissions of the system packages.
9721        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9722            for (PackageParser.Package pkg : mPackages.values()) {
9723                if (pkg != pkgInfo) {
9724                    // Only replace for packages on requested volume
9725                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9726                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9727                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9728                    grantPermissionsLPw(pkg, replace, changingPkg);
9729                }
9730            }
9731        }
9732
9733        if (pkgInfo != null) {
9734            // Only replace for packages on requested volume
9735            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9736            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9737                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9738            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9739        }
9740    }
9741
9742    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9743            String packageOfInterest) {
9744        // IMPORTANT: There are two types of permissions: install and runtime.
9745        // Install time permissions are granted when the app is installed to
9746        // all device users and users added in the future. Runtime permissions
9747        // are granted at runtime explicitly to specific users. Normal and signature
9748        // protected permissions are install time permissions. Dangerous permissions
9749        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9750        // otherwise they are runtime permissions. This function does not manage
9751        // runtime permissions except for the case an app targeting Lollipop MR1
9752        // being upgraded to target a newer SDK, in which case dangerous permissions
9753        // are transformed from install time to runtime ones.
9754
9755        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9756        if (ps == null) {
9757            return;
9758        }
9759
9760        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9761
9762        PermissionsState permissionsState = ps.getPermissionsState();
9763        PermissionsState origPermissions = permissionsState;
9764
9765        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9766
9767        boolean runtimePermissionsRevoked = false;
9768        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9769
9770        boolean changedInstallPermission = false;
9771
9772        if (replace) {
9773            ps.installPermissionsFixed = false;
9774            if (!ps.isSharedUser()) {
9775                origPermissions = new PermissionsState(permissionsState);
9776                permissionsState.reset();
9777            } else {
9778                // We need to know only about runtime permission changes since the
9779                // calling code always writes the install permissions state but
9780                // the runtime ones are written only if changed. The only cases of
9781                // changed runtime permissions here are promotion of an install to
9782                // runtime and revocation of a runtime from a shared user.
9783                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9784                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9785                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9786                    runtimePermissionsRevoked = true;
9787                }
9788            }
9789        }
9790
9791        permissionsState.setGlobalGids(mGlobalGids);
9792
9793        final int N = pkg.requestedPermissions.size();
9794        for (int i=0; i<N; i++) {
9795            final String name = pkg.requestedPermissions.get(i);
9796            final BasePermission bp = mSettings.mPermissions.get(name);
9797
9798            if (DEBUG_INSTALL) {
9799                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9800            }
9801
9802            if (bp == null || bp.packageSetting == null) {
9803                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9804                    Slog.w(TAG, "Unknown permission " + name
9805                            + " in package " + pkg.packageName);
9806                }
9807                continue;
9808            }
9809
9810            final String perm = bp.name;
9811            boolean allowedSig = false;
9812            int grant = GRANT_DENIED;
9813
9814            // Keep track of app op permissions.
9815            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9816                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9817                if (pkgs == null) {
9818                    pkgs = new ArraySet<>();
9819                    mAppOpPermissionPackages.put(bp.name, pkgs);
9820                }
9821                pkgs.add(pkg.packageName);
9822            }
9823
9824            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9825            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9826                    >= Build.VERSION_CODES.M;
9827            switch (level) {
9828                case PermissionInfo.PROTECTION_NORMAL: {
9829                    // For all apps normal permissions are install time ones.
9830                    grant = GRANT_INSTALL;
9831                } break;
9832
9833                case PermissionInfo.PROTECTION_DANGEROUS: {
9834                    // If a permission review is required for legacy apps we represent
9835                    // their permissions as always granted runtime ones since we need
9836                    // to keep the review required permission flag per user while an
9837                    // install permission's state is shared across all users.
9838                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9839                        // For legacy apps dangerous permissions are install time ones.
9840                        grant = GRANT_INSTALL;
9841                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9842                        // For legacy apps that became modern, install becomes runtime.
9843                        grant = GRANT_UPGRADE;
9844                    } else if (mPromoteSystemApps
9845                            && isSystemApp(ps)
9846                            && mExistingSystemPackages.contains(ps.name)) {
9847                        // For legacy system apps, install becomes runtime.
9848                        // We cannot check hasInstallPermission() for system apps since those
9849                        // permissions were granted implicitly and not persisted pre-M.
9850                        grant = GRANT_UPGRADE;
9851                    } else {
9852                        // For modern apps keep runtime permissions unchanged.
9853                        grant = GRANT_RUNTIME;
9854                    }
9855                } break;
9856
9857                case PermissionInfo.PROTECTION_SIGNATURE: {
9858                    // For all apps signature permissions are install time ones.
9859                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9860                    if (allowedSig) {
9861                        grant = GRANT_INSTALL;
9862                    }
9863                } break;
9864            }
9865
9866            if (DEBUG_INSTALL) {
9867                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9868            }
9869
9870            if (grant != GRANT_DENIED) {
9871                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9872                    // If this is an existing, non-system package, then
9873                    // we can't add any new permissions to it.
9874                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9875                        // Except...  if this is a permission that was added
9876                        // to the platform (note: need to only do this when
9877                        // updating the platform).
9878                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9879                            grant = GRANT_DENIED;
9880                        }
9881                    }
9882                }
9883
9884                switch (grant) {
9885                    case GRANT_INSTALL: {
9886                        // Revoke this as runtime permission to handle the case of
9887                        // a runtime permission being downgraded to an install one.
9888                        // Also in permission review mode we keep dangerous permissions
9889                        // for legacy apps
9890                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9891                            if (origPermissions.getRuntimePermissionState(
9892                                    bp.name, userId) != null) {
9893                                // Revoke the runtime permission and clear the flags.
9894                                origPermissions.revokeRuntimePermission(bp, userId);
9895                                origPermissions.updatePermissionFlags(bp, userId,
9896                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9897                                // If we revoked a permission permission, we have to write.
9898                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9899                                        changedRuntimePermissionUserIds, userId);
9900                            }
9901                        }
9902                        // Grant an install permission.
9903                        if (permissionsState.grantInstallPermission(bp) !=
9904                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9905                            changedInstallPermission = true;
9906                        }
9907                    } break;
9908
9909                    case GRANT_RUNTIME: {
9910                        // Grant previously granted runtime permissions.
9911                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9912                            PermissionState permissionState = origPermissions
9913                                    .getRuntimePermissionState(bp.name, userId);
9914                            int flags = permissionState != null
9915                                    ? permissionState.getFlags() : 0;
9916                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9917                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9918                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9919                                    // If we cannot put the permission as it was, we have to write.
9920                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9921                                            changedRuntimePermissionUserIds, userId);
9922                                }
9923                                // If the app supports runtime permissions no need for a review.
9924                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9925                                        && appSupportsRuntimePermissions
9926                                        && (flags & PackageManager
9927                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9928                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9929                                    // Since we changed the flags, we have to write.
9930                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9931                                            changedRuntimePermissionUserIds, userId);
9932                                }
9933                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9934                                    && !appSupportsRuntimePermissions) {
9935                                // For legacy apps that need a permission review, every new
9936                                // runtime permission is granted but it is pending a review.
9937                                // We also need to review only platform defined runtime
9938                                // permissions as these are the only ones the platform knows
9939                                // how to disable the API to simulate revocation as legacy
9940                                // apps don't expect to run with revoked permissions.
9941                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9942                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9943                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9944                                        // We changed the flags, hence have to write.
9945                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9946                                                changedRuntimePermissionUserIds, userId);
9947                                    }
9948                                }
9949                                if (permissionsState.grantRuntimePermission(bp, userId)
9950                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9951                                    // We changed the permission, hence have to write.
9952                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9953                                            changedRuntimePermissionUserIds, userId);
9954                                }
9955                            }
9956                            // Propagate the permission flags.
9957                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9958                        }
9959                    } break;
9960
9961                    case GRANT_UPGRADE: {
9962                        // Grant runtime permissions for a previously held install permission.
9963                        PermissionState permissionState = origPermissions
9964                                .getInstallPermissionState(bp.name);
9965                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9966
9967                        if (origPermissions.revokeInstallPermission(bp)
9968                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9969                            // We will be transferring the permission flags, so clear them.
9970                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9971                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9972                            changedInstallPermission = true;
9973                        }
9974
9975                        // If the permission is not to be promoted to runtime we ignore it and
9976                        // also its other flags as they are not applicable to install permissions.
9977                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9978                            for (int userId : currentUserIds) {
9979                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9980                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9981                                    // Transfer the permission flags.
9982                                    permissionsState.updatePermissionFlags(bp, userId,
9983                                            flags, flags);
9984                                    // If we granted the permission, we have to write.
9985                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9986                                            changedRuntimePermissionUserIds, userId);
9987                                }
9988                            }
9989                        }
9990                    } break;
9991
9992                    default: {
9993                        if (packageOfInterest == null
9994                                || packageOfInterest.equals(pkg.packageName)) {
9995                            Slog.w(TAG, "Not granting permission " + perm
9996                                    + " to package " + pkg.packageName
9997                                    + " because it was previously installed without");
9998                        }
9999                    } break;
10000                }
10001            } else {
10002                if (permissionsState.revokeInstallPermission(bp) !=
10003                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10004                    // Also drop the permission flags.
10005                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10006                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10007                    changedInstallPermission = true;
10008                    Slog.i(TAG, "Un-granting permission " + perm
10009                            + " from package " + pkg.packageName
10010                            + " (protectionLevel=" + bp.protectionLevel
10011                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10012                            + ")");
10013                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10014                    // Don't print warning for app op permissions, since it is fine for them
10015                    // not to be granted, there is a UI for the user to decide.
10016                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10017                        Slog.w(TAG, "Not granting permission " + perm
10018                                + " to package " + pkg.packageName
10019                                + " (protectionLevel=" + bp.protectionLevel
10020                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10021                                + ")");
10022                    }
10023                }
10024            }
10025        }
10026
10027        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10028                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10029            // This is the first that we have heard about this package, so the
10030            // permissions we have now selected are fixed until explicitly
10031            // changed.
10032            ps.installPermissionsFixed = true;
10033        }
10034
10035        // Persist the runtime permissions state for users with changes. If permissions
10036        // were revoked because no app in the shared user declares them we have to
10037        // write synchronously to avoid losing runtime permissions state.
10038        for (int userId : changedRuntimePermissionUserIds) {
10039            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10040        }
10041
10042        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10043    }
10044
10045    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10046        boolean allowed = false;
10047        final int NP = PackageParser.NEW_PERMISSIONS.length;
10048        for (int ip=0; ip<NP; ip++) {
10049            final PackageParser.NewPermissionInfo npi
10050                    = PackageParser.NEW_PERMISSIONS[ip];
10051            if (npi.name.equals(perm)
10052                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10053                allowed = true;
10054                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10055                        + pkg.packageName);
10056                break;
10057            }
10058        }
10059        return allowed;
10060    }
10061
10062    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10063            BasePermission bp, PermissionsState origPermissions) {
10064        boolean allowed;
10065        allowed = (compareSignatures(
10066                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10067                        == PackageManager.SIGNATURE_MATCH)
10068                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10069                        == PackageManager.SIGNATURE_MATCH);
10070        if (!allowed && (bp.protectionLevel
10071                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10072            if (isSystemApp(pkg)) {
10073                // For updated system applications, a system permission
10074                // is granted only if it had been defined by the original application.
10075                if (pkg.isUpdatedSystemApp()) {
10076                    final PackageSetting sysPs = mSettings
10077                            .getDisabledSystemPkgLPr(pkg.packageName);
10078                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10079                        // If the original was granted this permission, we take
10080                        // that grant decision as read and propagate it to the
10081                        // update.
10082                        if (sysPs.isPrivileged()) {
10083                            allowed = true;
10084                        }
10085                    } else {
10086                        // The system apk may have been updated with an older
10087                        // version of the one on the data partition, but which
10088                        // granted a new system permission that it didn't have
10089                        // before.  In this case we do want to allow the app to
10090                        // now get the new permission if the ancestral apk is
10091                        // privileged to get it.
10092                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10093                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10094                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10095                                    allowed = true;
10096                                    break;
10097                                }
10098                            }
10099                        }
10100                        // Also if a privileged parent package on the system image or any of
10101                        // its children requested a privileged permission, the updated child
10102                        // packages can also get the permission.
10103                        if (pkg.parentPackage != null) {
10104                            final PackageSetting disabledSysParentPs = mSettings
10105                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10106                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10107                                    && disabledSysParentPs.isPrivileged()) {
10108                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10109                                    allowed = true;
10110                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10111                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10112                                    for (int i = 0; i < count; i++) {
10113                                        PackageParser.Package disabledSysChildPkg =
10114                                                disabledSysParentPs.pkg.childPackages.get(i);
10115                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10116                                                perm)) {
10117                                            allowed = true;
10118                                            break;
10119                                        }
10120                                    }
10121                                }
10122                            }
10123                        }
10124                    }
10125                } else {
10126                    allowed = isPrivilegedApp(pkg);
10127                }
10128            }
10129        }
10130        if (!allowed) {
10131            if (!allowed && (bp.protectionLevel
10132                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10133                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10134                // If this was a previously normal/dangerous permission that got moved
10135                // to a system permission as part of the runtime permission redesign, then
10136                // we still want to blindly grant it to old apps.
10137                allowed = true;
10138            }
10139            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10140                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10141                // If this permission is to be granted to the system installer and
10142                // this app is an installer, then it gets the permission.
10143                allowed = true;
10144            }
10145            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10146                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10147                // If this permission is to be granted to the system verifier and
10148                // this app is a verifier, then it gets the permission.
10149                allowed = true;
10150            }
10151            if (!allowed && (bp.protectionLevel
10152                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10153                    && isSystemApp(pkg)) {
10154                // Any pre-installed system app is allowed to get this permission.
10155                allowed = true;
10156            }
10157            if (!allowed && (bp.protectionLevel
10158                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10159                // For development permissions, a development permission
10160                // is granted only if it was already granted.
10161                allowed = origPermissions.hasInstallPermission(perm);
10162            }
10163            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10164                    && pkg.packageName.equals(mSetupWizardPackage)) {
10165                // If this permission is to be granted to the system setup wizard and
10166                // this app is a setup wizard, then it gets the permission.
10167                allowed = true;
10168            }
10169        }
10170        return allowed;
10171    }
10172
10173    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10174        final int permCount = pkg.requestedPermissions.size();
10175        for (int j = 0; j < permCount; j++) {
10176            String requestedPermission = pkg.requestedPermissions.get(j);
10177            if (permission.equals(requestedPermission)) {
10178                return true;
10179            }
10180        }
10181        return false;
10182    }
10183
10184    final class ActivityIntentResolver
10185            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10186        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10187                boolean defaultOnly, int userId) {
10188            if (!sUserManager.exists(userId)) return null;
10189            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10190            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10191        }
10192
10193        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10194                int userId) {
10195            if (!sUserManager.exists(userId)) return null;
10196            mFlags = flags;
10197            return super.queryIntent(intent, resolvedType,
10198                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10199        }
10200
10201        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10202                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10203            if (!sUserManager.exists(userId)) return null;
10204            if (packageActivities == null) {
10205                return null;
10206            }
10207            mFlags = flags;
10208            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10209            final int N = packageActivities.size();
10210            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10211                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10212
10213            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10214            for (int i = 0; i < N; ++i) {
10215                intentFilters = packageActivities.get(i).intents;
10216                if (intentFilters != null && intentFilters.size() > 0) {
10217                    PackageParser.ActivityIntentInfo[] array =
10218                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10219                    intentFilters.toArray(array);
10220                    listCut.add(array);
10221                }
10222            }
10223            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10224        }
10225
10226        /**
10227         * Finds a privileged activity that matches the specified activity names.
10228         */
10229        private PackageParser.Activity findMatchingActivity(
10230                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10231            for (PackageParser.Activity sysActivity : activityList) {
10232                if (sysActivity.info.name.equals(activityInfo.name)) {
10233                    return sysActivity;
10234                }
10235                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10236                    return sysActivity;
10237                }
10238                if (sysActivity.info.targetActivity != null) {
10239                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10240                        return sysActivity;
10241                    }
10242                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10243                        return sysActivity;
10244                    }
10245                }
10246            }
10247            return null;
10248        }
10249
10250        public class IterGenerator<E> {
10251            public Iterator<E> generate(ActivityIntentInfo info) {
10252                return null;
10253            }
10254        }
10255
10256        public class ActionIterGenerator extends IterGenerator<String> {
10257            @Override
10258            public Iterator<String> generate(ActivityIntentInfo info) {
10259                return info.actionsIterator();
10260            }
10261        }
10262
10263        public class CategoriesIterGenerator extends IterGenerator<String> {
10264            @Override
10265            public Iterator<String> generate(ActivityIntentInfo info) {
10266                return info.categoriesIterator();
10267            }
10268        }
10269
10270        public class SchemesIterGenerator extends IterGenerator<String> {
10271            @Override
10272            public Iterator<String> generate(ActivityIntentInfo info) {
10273                return info.schemesIterator();
10274            }
10275        }
10276
10277        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10278            @Override
10279            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10280                return info.authoritiesIterator();
10281            }
10282        }
10283
10284        /**
10285         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10286         * MODIFIED. Do not pass in a list that should not be changed.
10287         */
10288        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10289                IterGenerator<T> generator, Iterator<T> searchIterator) {
10290            // loop through the set of actions; every one must be found in the intent filter
10291            while (searchIterator.hasNext()) {
10292                // we must have at least one filter in the list to consider a match
10293                if (intentList.size() == 0) {
10294                    break;
10295                }
10296
10297                final T searchAction = searchIterator.next();
10298
10299                // loop through the set of intent filters
10300                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10301                while (intentIter.hasNext()) {
10302                    final ActivityIntentInfo intentInfo = intentIter.next();
10303                    boolean selectionFound = false;
10304
10305                    // loop through the intent filter's selection criteria; at least one
10306                    // of them must match the searched criteria
10307                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10308                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10309                        final T intentSelection = intentSelectionIter.next();
10310                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10311                            selectionFound = true;
10312                            break;
10313                        }
10314                    }
10315
10316                    // the selection criteria wasn't found in this filter's set; this filter
10317                    // is not a potential match
10318                    if (!selectionFound) {
10319                        intentIter.remove();
10320                    }
10321                }
10322            }
10323        }
10324
10325        private boolean isProtectedAction(ActivityIntentInfo filter) {
10326            final Iterator<String> actionsIter = filter.actionsIterator();
10327            while (actionsIter != null && actionsIter.hasNext()) {
10328                final String filterAction = actionsIter.next();
10329                if (PROTECTED_ACTIONS.contains(filterAction)) {
10330                    return true;
10331                }
10332            }
10333            return false;
10334        }
10335
10336        /**
10337         * Adjusts the priority of the given intent filter according to policy.
10338         * <p>
10339         * <ul>
10340         * <li>The priority for non privileged applications is capped to '0'</li>
10341         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10342         * <li>The priority for unbundled updates to privileged applications is capped to the
10343         *      priority defined on the system partition</li>
10344         * </ul>
10345         * <p>
10346         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10347         * allowed to obtain any priority on any action.
10348         */
10349        private void adjustPriority(
10350                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10351            // nothing to do; priority is fine as-is
10352            if (intent.getPriority() <= 0) {
10353                return;
10354            }
10355
10356            final ActivityInfo activityInfo = intent.activity.info;
10357            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10358
10359            final boolean privilegedApp =
10360                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10361            if (!privilegedApp) {
10362                // non-privileged applications can never define a priority >0
10363                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10364                        + " package: " + applicationInfo.packageName
10365                        + " activity: " + intent.activity.className
10366                        + " origPrio: " + intent.getPriority());
10367                intent.setPriority(0);
10368                return;
10369            }
10370
10371            if (systemActivities == null) {
10372                // the system package is not disabled; we're parsing the system partition
10373                if (isProtectedAction(intent)) {
10374                    if (mDeferProtectedFilters) {
10375                        // We can't deal with these just yet. No component should ever obtain a
10376                        // >0 priority for a protected actions, with ONE exception -- the setup
10377                        // wizard. The setup wizard, however, cannot be known until we're able to
10378                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10379                        // until all intent filters have been processed. Chicken, meet egg.
10380                        // Let the filter temporarily have a high priority and rectify the
10381                        // priorities after all system packages have been scanned.
10382                        mProtectedFilters.add(intent);
10383                        if (DEBUG_FILTERS) {
10384                            Slog.i(TAG, "Protected action; save for later;"
10385                                    + " package: " + applicationInfo.packageName
10386                                    + " activity: " + intent.activity.className
10387                                    + " origPrio: " + intent.getPriority());
10388                        }
10389                        return;
10390                    } else {
10391                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10392                            Slog.i(TAG, "No setup wizard;"
10393                                + " All protected intents capped to priority 0");
10394                        }
10395                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10396                            if (DEBUG_FILTERS) {
10397                                Slog.i(TAG, "Found setup wizard;"
10398                                    + " allow priority " + intent.getPriority() + ";"
10399                                    + " package: " + intent.activity.info.packageName
10400                                    + " activity: " + intent.activity.className
10401                                    + " priority: " + intent.getPriority());
10402                            }
10403                            // setup wizard gets whatever it wants
10404                            return;
10405                        }
10406                        Slog.w(TAG, "Protected action; cap priority to 0;"
10407                                + " package: " + intent.activity.info.packageName
10408                                + " activity: " + intent.activity.className
10409                                + " origPrio: " + intent.getPriority());
10410                        intent.setPriority(0);
10411                        return;
10412                    }
10413                }
10414                // privileged apps on the system image get whatever priority they request
10415                return;
10416            }
10417
10418            // privileged app unbundled update ... try to find the same activity
10419            final PackageParser.Activity foundActivity =
10420                    findMatchingActivity(systemActivities, activityInfo);
10421            if (foundActivity == null) {
10422                // this is a new activity; it cannot obtain >0 priority
10423                if (DEBUG_FILTERS) {
10424                    Slog.i(TAG, "New activity; cap priority to 0;"
10425                            + " package: " + applicationInfo.packageName
10426                            + " activity: " + intent.activity.className
10427                            + " origPrio: " + intent.getPriority());
10428                }
10429                intent.setPriority(0);
10430                return;
10431            }
10432
10433            // found activity, now check for filter equivalence
10434
10435            // a shallow copy is enough; we modify the list, not its contents
10436            final List<ActivityIntentInfo> intentListCopy =
10437                    new ArrayList<>(foundActivity.intents);
10438            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10439
10440            // find matching action subsets
10441            final Iterator<String> actionsIterator = intent.actionsIterator();
10442            if (actionsIterator != null) {
10443                getIntentListSubset(
10444                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10445                if (intentListCopy.size() == 0) {
10446                    // no more intents to match; we're not equivalent
10447                    if (DEBUG_FILTERS) {
10448                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10449                                + " package: " + applicationInfo.packageName
10450                                + " activity: " + intent.activity.className
10451                                + " origPrio: " + intent.getPriority());
10452                    }
10453                    intent.setPriority(0);
10454                    return;
10455                }
10456            }
10457
10458            // find matching category subsets
10459            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10460            if (categoriesIterator != null) {
10461                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10462                        categoriesIterator);
10463                if (intentListCopy.size() == 0) {
10464                    // no more intents to match; we're not equivalent
10465                    if (DEBUG_FILTERS) {
10466                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10467                                + " package: " + applicationInfo.packageName
10468                                + " activity: " + intent.activity.className
10469                                + " origPrio: " + intent.getPriority());
10470                    }
10471                    intent.setPriority(0);
10472                    return;
10473                }
10474            }
10475
10476            // find matching schemes subsets
10477            final Iterator<String> schemesIterator = intent.schemesIterator();
10478            if (schemesIterator != null) {
10479                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10480                        schemesIterator);
10481                if (intentListCopy.size() == 0) {
10482                    // no more intents to match; we're not equivalent
10483                    if (DEBUG_FILTERS) {
10484                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10485                                + " package: " + applicationInfo.packageName
10486                                + " activity: " + intent.activity.className
10487                                + " origPrio: " + intent.getPriority());
10488                    }
10489                    intent.setPriority(0);
10490                    return;
10491                }
10492            }
10493
10494            // find matching authorities subsets
10495            final Iterator<IntentFilter.AuthorityEntry>
10496                    authoritiesIterator = intent.authoritiesIterator();
10497            if (authoritiesIterator != null) {
10498                getIntentListSubset(intentListCopy,
10499                        new AuthoritiesIterGenerator(),
10500                        authoritiesIterator);
10501                if (intentListCopy.size() == 0) {
10502                    // no more intents to match; we're not equivalent
10503                    if (DEBUG_FILTERS) {
10504                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10505                                + " package: " + applicationInfo.packageName
10506                                + " activity: " + intent.activity.className
10507                                + " origPrio: " + intent.getPriority());
10508                    }
10509                    intent.setPriority(0);
10510                    return;
10511                }
10512            }
10513
10514            // we found matching filter(s); app gets the max priority of all intents
10515            int cappedPriority = 0;
10516            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10517                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10518            }
10519            if (intent.getPriority() > cappedPriority) {
10520                if (DEBUG_FILTERS) {
10521                    Slog.i(TAG, "Found matching filter(s);"
10522                            + " cap priority to " + cappedPriority + ";"
10523                            + " package: " + applicationInfo.packageName
10524                            + " activity: " + intent.activity.className
10525                            + " origPrio: " + intent.getPriority());
10526                }
10527                intent.setPriority(cappedPriority);
10528                return;
10529            }
10530            // all this for nothing; the requested priority was <= what was on the system
10531        }
10532
10533        public final void addActivity(PackageParser.Activity a, String type) {
10534            mActivities.put(a.getComponentName(), a);
10535            if (DEBUG_SHOW_INFO)
10536                Log.v(
10537                TAG, "  " + type + " " +
10538                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10539            if (DEBUG_SHOW_INFO)
10540                Log.v(TAG, "    Class=" + a.info.name);
10541            final int NI = a.intents.size();
10542            for (int j=0; j<NI; j++) {
10543                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10544                if ("activity".equals(type)) {
10545                    final PackageSetting ps =
10546                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10547                    final List<PackageParser.Activity> systemActivities =
10548                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10549                    adjustPriority(systemActivities, intent);
10550                }
10551                if (DEBUG_SHOW_INFO) {
10552                    Log.v(TAG, "    IntentFilter:");
10553                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10554                }
10555                if (!intent.debugCheck()) {
10556                    Log.w(TAG, "==> For Activity " + a.info.name);
10557                }
10558                addFilter(intent);
10559            }
10560        }
10561
10562        public final void removeActivity(PackageParser.Activity a, String type) {
10563            mActivities.remove(a.getComponentName());
10564            if (DEBUG_SHOW_INFO) {
10565                Log.v(TAG, "  " + type + " "
10566                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10567                                : a.info.name) + ":");
10568                Log.v(TAG, "    Class=" + a.info.name);
10569            }
10570            final int NI = a.intents.size();
10571            for (int j=0; j<NI; j++) {
10572                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10573                if (DEBUG_SHOW_INFO) {
10574                    Log.v(TAG, "    IntentFilter:");
10575                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10576                }
10577                removeFilter(intent);
10578            }
10579        }
10580
10581        @Override
10582        protected boolean allowFilterResult(
10583                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10584            ActivityInfo filterAi = filter.activity.info;
10585            for (int i=dest.size()-1; i>=0; i--) {
10586                ActivityInfo destAi = dest.get(i).activityInfo;
10587                if (destAi.name == filterAi.name
10588                        && destAi.packageName == filterAi.packageName) {
10589                    return false;
10590                }
10591            }
10592            return true;
10593        }
10594
10595        @Override
10596        protected ActivityIntentInfo[] newArray(int size) {
10597            return new ActivityIntentInfo[size];
10598        }
10599
10600        @Override
10601        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10602            if (!sUserManager.exists(userId)) return true;
10603            PackageParser.Package p = filter.activity.owner;
10604            if (p != null) {
10605                PackageSetting ps = (PackageSetting)p.mExtras;
10606                if (ps != null) {
10607                    // System apps are never considered stopped for purposes of
10608                    // filtering, because there may be no way for the user to
10609                    // actually re-launch them.
10610                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10611                            && ps.getStopped(userId);
10612                }
10613            }
10614            return false;
10615        }
10616
10617        @Override
10618        protected boolean isPackageForFilter(String packageName,
10619                PackageParser.ActivityIntentInfo info) {
10620            return packageName.equals(info.activity.owner.packageName);
10621        }
10622
10623        @Override
10624        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10625                int match, int userId) {
10626            if (!sUserManager.exists(userId)) return null;
10627            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10628                return null;
10629            }
10630            final PackageParser.Activity activity = info.activity;
10631            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10632            if (ps == null) {
10633                return null;
10634            }
10635            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10636                    ps.readUserState(userId), userId);
10637            if (ai == null) {
10638                return null;
10639            }
10640            final ResolveInfo res = new ResolveInfo();
10641            res.activityInfo = ai;
10642            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10643                res.filter = info;
10644            }
10645            if (info != null) {
10646                res.handleAllWebDataURI = info.handleAllWebDataURI();
10647            }
10648            res.priority = info.getPriority();
10649            res.preferredOrder = activity.owner.mPreferredOrder;
10650            //System.out.println("Result: " + res.activityInfo.className +
10651            //                   " = " + res.priority);
10652            res.match = match;
10653            res.isDefault = info.hasDefault;
10654            res.labelRes = info.labelRes;
10655            res.nonLocalizedLabel = info.nonLocalizedLabel;
10656            if (userNeedsBadging(userId)) {
10657                res.noResourceId = true;
10658            } else {
10659                res.icon = info.icon;
10660            }
10661            res.iconResourceId = info.icon;
10662            res.system = res.activityInfo.applicationInfo.isSystemApp();
10663            return res;
10664        }
10665
10666        @Override
10667        protected void sortResults(List<ResolveInfo> results) {
10668            Collections.sort(results, mResolvePrioritySorter);
10669        }
10670
10671        @Override
10672        protected void dumpFilter(PrintWriter out, String prefix,
10673                PackageParser.ActivityIntentInfo filter) {
10674            out.print(prefix); out.print(
10675                    Integer.toHexString(System.identityHashCode(filter.activity)));
10676                    out.print(' ');
10677                    filter.activity.printComponentShortName(out);
10678                    out.print(" filter ");
10679                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10680        }
10681
10682        @Override
10683        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10684            return filter.activity;
10685        }
10686
10687        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10688            PackageParser.Activity activity = (PackageParser.Activity)label;
10689            out.print(prefix); out.print(
10690                    Integer.toHexString(System.identityHashCode(activity)));
10691                    out.print(' ');
10692                    activity.printComponentShortName(out);
10693            if (count > 1) {
10694                out.print(" ("); out.print(count); out.print(" filters)");
10695            }
10696            out.println();
10697        }
10698
10699        // Keys are String (activity class name), values are Activity.
10700        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10701                = new ArrayMap<ComponentName, PackageParser.Activity>();
10702        private int mFlags;
10703    }
10704
10705    private final class ServiceIntentResolver
10706            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10707        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10708                boolean defaultOnly, int userId) {
10709            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10710            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10711        }
10712
10713        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10714                int userId) {
10715            if (!sUserManager.exists(userId)) return null;
10716            mFlags = flags;
10717            return super.queryIntent(intent, resolvedType,
10718                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10719        }
10720
10721        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10722                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10723            if (!sUserManager.exists(userId)) return null;
10724            if (packageServices == null) {
10725                return null;
10726            }
10727            mFlags = flags;
10728            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10729            final int N = packageServices.size();
10730            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10731                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10732
10733            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10734            for (int i = 0; i < N; ++i) {
10735                intentFilters = packageServices.get(i).intents;
10736                if (intentFilters != null && intentFilters.size() > 0) {
10737                    PackageParser.ServiceIntentInfo[] array =
10738                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10739                    intentFilters.toArray(array);
10740                    listCut.add(array);
10741                }
10742            }
10743            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10744        }
10745
10746        public final void addService(PackageParser.Service s) {
10747            mServices.put(s.getComponentName(), s);
10748            if (DEBUG_SHOW_INFO) {
10749                Log.v(TAG, "  "
10750                        + (s.info.nonLocalizedLabel != null
10751                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10752                Log.v(TAG, "    Class=" + s.info.name);
10753            }
10754            final int NI = s.intents.size();
10755            int j;
10756            for (j=0; j<NI; j++) {
10757                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10758                if (DEBUG_SHOW_INFO) {
10759                    Log.v(TAG, "    IntentFilter:");
10760                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10761                }
10762                if (!intent.debugCheck()) {
10763                    Log.w(TAG, "==> For Service " + s.info.name);
10764                }
10765                addFilter(intent);
10766            }
10767        }
10768
10769        public final void removeService(PackageParser.Service s) {
10770            mServices.remove(s.getComponentName());
10771            if (DEBUG_SHOW_INFO) {
10772                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10773                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10774                Log.v(TAG, "    Class=" + s.info.name);
10775            }
10776            final int NI = s.intents.size();
10777            int j;
10778            for (j=0; j<NI; j++) {
10779                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10780                if (DEBUG_SHOW_INFO) {
10781                    Log.v(TAG, "    IntentFilter:");
10782                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10783                }
10784                removeFilter(intent);
10785            }
10786        }
10787
10788        @Override
10789        protected boolean allowFilterResult(
10790                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10791            ServiceInfo filterSi = filter.service.info;
10792            for (int i=dest.size()-1; i>=0; i--) {
10793                ServiceInfo destAi = dest.get(i).serviceInfo;
10794                if (destAi.name == filterSi.name
10795                        && destAi.packageName == filterSi.packageName) {
10796                    return false;
10797                }
10798            }
10799            return true;
10800        }
10801
10802        @Override
10803        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10804            return new PackageParser.ServiceIntentInfo[size];
10805        }
10806
10807        @Override
10808        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10809            if (!sUserManager.exists(userId)) return true;
10810            PackageParser.Package p = filter.service.owner;
10811            if (p != null) {
10812                PackageSetting ps = (PackageSetting)p.mExtras;
10813                if (ps != null) {
10814                    // System apps are never considered stopped for purposes of
10815                    // filtering, because there may be no way for the user to
10816                    // actually re-launch them.
10817                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10818                            && ps.getStopped(userId);
10819                }
10820            }
10821            return false;
10822        }
10823
10824        @Override
10825        protected boolean isPackageForFilter(String packageName,
10826                PackageParser.ServiceIntentInfo info) {
10827            return packageName.equals(info.service.owner.packageName);
10828        }
10829
10830        @Override
10831        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10832                int match, int userId) {
10833            if (!sUserManager.exists(userId)) return null;
10834            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10835            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10836                return null;
10837            }
10838            final PackageParser.Service service = info.service;
10839            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10840            if (ps == null) {
10841                return null;
10842            }
10843            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10844                    ps.readUserState(userId), userId);
10845            if (si == null) {
10846                return null;
10847            }
10848            final ResolveInfo res = new ResolveInfo();
10849            res.serviceInfo = si;
10850            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10851                res.filter = filter;
10852            }
10853            res.priority = info.getPriority();
10854            res.preferredOrder = service.owner.mPreferredOrder;
10855            res.match = match;
10856            res.isDefault = info.hasDefault;
10857            res.labelRes = info.labelRes;
10858            res.nonLocalizedLabel = info.nonLocalizedLabel;
10859            res.icon = info.icon;
10860            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10861            return res;
10862        }
10863
10864        @Override
10865        protected void sortResults(List<ResolveInfo> results) {
10866            Collections.sort(results, mResolvePrioritySorter);
10867        }
10868
10869        @Override
10870        protected void dumpFilter(PrintWriter out, String prefix,
10871                PackageParser.ServiceIntentInfo filter) {
10872            out.print(prefix); out.print(
10873                    Integer.toHexString(System.identityHashCode(filter.service)));
10874                    out.print(' ');
10875                    filter.service.printComponentShortName(out);
10876                    out.print(" filter ");
10877                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10878        }
10879
10880        @Override
10881        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10882            return filter.service;
10883        }
10884
10885        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10886            PackageParser.Service service = (PackageParser.Service)label;
10887            out.print(prefix); out.print(
10888                    Integer.toHexString(System.identityHashCode(service)));
10889                    out.print(' ');
10890                    service.printComponentShortName(out);
10891            if (count > 1) {
10892                out.print(" ("); out.print(count); out.print(" filters)");
10893            }
10894            out.println();
10895        }
10896
10897//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10898//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10899//            final List<ResolveInfo> retList = Lists.newArrayList();
10900//            while (i.hasNext()) {
10901//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10902//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10903//                    retList.add(resolveInfo);
10904//                }
10905//            }
10906//            return retList;
10907//        }
10908
10909        // Keys are String (activity class name), values are Activity.
10910        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10911                = new ArrayMap<ComponentName, PackageParser.Service>();
10912        private int mFlags;
10913    };
10914
10915    private final class ProviderIntentResolver
10916            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10917        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10918                boolean defaultOnly, int userId) {
10919            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10920            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10921        }
10922
10923        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10924                int userId) {
10925            if (!sUserManager.exists(userId))
10926                return null;
10927            mFlags = flags;
10928            return super.queryIntent(intent, resolvedType,
10929                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10930        }
10931
10932        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10933                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10934            if (!sUserManager.exists(userId))
10935                return null;
10936            if (packageProviders == null) {
10937                return null;
10938            }
10939            mFlags = flags;
10940            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10941            final int N = packageProviders.size();
10942            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10943                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10944
10945            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10946            for (int i = 0; i < N; ++i) {
10947                intentFilters = packageProviders.get(i).intents;
10948                if (intentFilters != null && intentFilters.size() > 0) {
10949                    PackageParser.ProviderIntentInfo[] array =
10950                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10951                    intentFilters.toArray(array);
10952                    listCut.add(array);
10953                }
10954            }
10955            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10956        }
10957
10958        public final void addProvider(PackageParser.Provider p) {
10959            if (mProviders.containsKey(p.getComponentName())) {
10960                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10961                return;
10962            }
10963
10964            mProviders.put(p.getComponentName(), p);
10965            if (DEBUG_SHOW_INFO) {
10966                Log.v(TAG, "  "
10967                        + (p.info.nonLocalizedLabel != null
10968                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10969                Log.v(TAG, "    Class=" + p.info.name);
10970            }
10971            final int NI = p.intents.size();
10972            int j;
10973            for (j = 0; j < NI; j++) {
10974                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10975                if (DEBUG_SHOW_INFO) {
10976                    Log.v(TAG, "    IntentFilter:");
10977                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10978                }
10979                if (!intent.debugCheck()) {
10980                    Log.w(TAG, "==> For Provider " + p.info.name);
10981                }
10982                addFilter(intent);
10983            }
10984        }
10985
10986        public final void removeProvider(PackageParser.Provider p) {
10987            mProviders.remove(p.getComponentName());
10988            if (DEBUG_SHOW_INFO) {
10989                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10990                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10991                Log.v(TAG, "    Class=" + p.info.name);
10992            }
10993            final int NI = p.intents.size();
10994            int j;
10995            for (j = 0; j < NI; j++) {
10996                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10997                if (DEBUG_SHOW_INFO) {
10998                    Log.v(TAG, "    IntentFilter:");
10999                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11000                }
11001                removeFilter(intent);
11002            }
11003        }
11004
11005        @Override
11006        protected boolean allowFilterResult(
11007                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11008            ProviderInfo filterPi = filter.provider.info;
11009            for (int i = dest.size() - 1; i >= 0; i--) {
11010                ProviderInfo destPi = dest.get(i).providerInfo;
11011                if (destPi.name == filterPi.name
11012                        && destPi.packageName == filterPi.packageName) {
11013                    return false;
11014                }
11015            }
11016            return true;
11017        }
11018
11019        @Override
11020        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11021            return new PackageParser.ProviderIntentInfo[size];
11022        }
11023
11024        @Override
11025        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11026            if (!sUserManager.exists(userId))
11027                return true;
11028            PackageParser.Package p = filter.provider.owner;
11029            if (p != null) {
11030                PackageSetting ps = (PackageSetting) p.mExtras;
11031                if (ps != null) {
11032                    // System apps are never considered stopped for purposes of
11033                    // filtering, because there may be no way for the user to
11034                    // actually re-launch them.
11035                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11036                            && ps.getStopped(userId);
11037                }
11038            }
11039            return false;
11040        }
11041
11042        @Override
11043        protected boolean isPackageForFilter(String packageName,
11044                PackageParser.ProviderIntentInfo info) {
11045            return packageName.equals(info.provider.owner.packageName);
11046        }
11047
11048        @Override
11049        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11050                int match, int userId) {
11051            if (!sUserManager.exists(userId))
11052                return null;
11053            final PackageParser.ProviderIntentInfo info = filter;
11054            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11055                return null;
11056            }
11057            final PackageParser.Provider provider = info.provider;
11058            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11059            if (ps == null) {
11060                return null;
11061            }
11062            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11063                    ps.readUserState(userId), userId);
11064            if (pi == null) {
11065                return null;
11066            }
11067            final ResolveInfo res = new ResolveInfo();
11068            res.providerInfo = pi;
11069            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11070                res.filter = filter;
11071            }
11072            res.priority = info.getPriority();
11073            res.preferredOrder = provider.owner.mPreferredOrder;
11074            res.match = match;
11075            res.isDefault = info.hasDefault;
11076            res.labelRes = info.labelRes;
11077            res.nonLocalizedLabel = info.nonLocalizedLabel;
11078            res.icon = info.icon;
11079            res.system = res.providerInfo.applicationInfo.isSystemApp();
11080            return res;
11081        }
11082
11083        @Override
11084        protected void sortResults(List<ResolveInfo> results) {
11085            Collections.sort(results, mResolvePrioritySorter);
11086        }
11087
11088        @Override
11089        protected void dumpFilter(PrintWriter out, String prefix,
11090                PackageParser.ProviderIntentInfo filter) {
11091            out.print(prefix);
11092            out.print(
11093                    Integer.toHexString(System.identityHashCode(filter.provider)));
11094            out.print(' ');
11095            filter.provider.printComponentShortName(out);
11096            out.print(" filter ");
11097            out.println(Integer.toHexString(System.identityHashCode(filter)));
11098        }
11099
11100        @Override
11101        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11102            return filter.provider;
11103        }
11104
11105        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11106            PackageParser.Provider provider = (PackageParser.Provider)label;
11107            out.print(prefix); out.print(
11108                    Integer.toHexString(System.identityHashCode(provider)));
11109                    out.print(' ');
11110                    provider.printComponentShortName(out);
11111            if (count > 1) {
11112                out.print(" ("); out.print(count); out.print(" filters)");
11113            }
11114            out.println();
11115        }
11116
11117        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11118                = new ArrayMap<ComponentName, PackageParser.Provider>();
11119        private int mFlags;
11120    }
11121
11122    private static final class EphemeralIntentResolver
11123            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11124        @Override
11125        protected EphemeralResolveIntentInfo[] newArray(int size) {
11126            return new EphemeralResolveIntentInfo[size];
11127        }
11128
11129        @Override
11130        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11131            return true;
11132        }
11133
11134        @Override
11135        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11136                int userId) {
11137            if (!sUserManager.exists(userId)) {
11138                return null;
11139            }
11140            return info.getEphemeralResolveInfo();
11141        }
11142    }
11143
11144    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11145            new Comparator<ResolveInfo>() {
11146        public int compare(ResolveInfo r1, ResolveInfo r2) {
11147            int v1 = r1.priority;
11148            int v2 = r2.priority;
11149            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11150            if (v1 != v2) {
11151                return (v1 > v2) ? -1 : 1;
11152            }
11153            v1 = r1.preferredOrder;
11154            v2 = r2.preferredOrder;
11155            if (v1 != v2) {
11156                return (v1 > v2) ? -1 : 1;
11157            }
11158            if (r1.isDefault != r2.isDefault) {
11159                return r1.isDefault ? -1 : 1;
11160            }
11161            v1 = r1.match;
11162            v2 = r2.match;
11163            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11164            if (v1 != v2) {
11165                return (v1 > v2) ? -1 : 1;
11166            }
11167            if (r1.system != r2.system) {
11168                return r1.system ? -1 : 1;
11169            }
11170            if (r1.activityInfo != null) {
11171                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11172            }
11173            if (r1.serviceInfo != null) {
11174                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11175            }
11176            if (r1.providerInfo != null) {
11177                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11178            }
11179            return 0;
11180        }
11181    };
11182
11183    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11184            new Comparator<ProviderInfo>() {
11185        public int compare(ProviderInfo p1, ProviderInfo p2) {
11186            final int v1 = p1.initOrder;
11187            final int v2 = p2.initOrder;
11188            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11189        }
11190    };
11191
11192    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11193            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11194            final int[] userIds) {
11195        mHandler.post(new Runnable() {
11196            @Override
11197            public void run() {
11198                try {
11199                    final IActivityManager am = ActivityManagerNative.getDefault();
11200                    if (am == null) return;
11201                    final int[] resolvedUserIds;
11202                    if (userIds == null) {
11203                        resolvedUserIds = am.getRunningUserIds();
11204                    } else {
11205                        resolvedUserIds = userIds;
11206                    }
11207                    for (int id : resolvedUserIds) {
11208                        final Intent intent = new Intent(action,
11209                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11210                        if (extras != null) {
11211                            intent.putExtras(extras);
11212                        }
11213                        if (targetPkg != null) {
11214                            intent.setPackage(targetPkg);
11215                        }
11216                        // Modify the UID when posting to other users
11217                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11218                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11219                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11220                            intent.putExtra(Intent.EXTRA_UID, uid);
11221                        }
11222                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11223                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11224                        if (DEBUG_BROADCASTS) {
11225                            RuntimeException here = new RuntimeException("here");
11226                            here.fillInStackTrace();
11227                            Slog.d(TAG, "Sending to user " + id + ": "
11228                                    + intent.toShortString(false, true, false, false)
11229                                    + " " + intent.getExtras(), here);
11230                        }
11231                        am.broadcastIntent(null, intent, null, finishedReceiver,
11232                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11233                                null, finishedReceiver != null, false, id);
11234                    }
11235                } catch (RemoteException ex) {
11236                }
11237            }
11238        });
11239    }
11240
11241    /**
11242     * Check if the external storage media is available. This is true if there
11243     * is a mounted external storage medium or if the external storage is
11244     * emulated.
11245     */
11246    private boolean isExternalMediaAvailable() {
11247        return mMediaMounted || Environment.isExternalStorageEmulated();
11248    }
11249
11250    @Override
11251    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11252        // writer
11253        synchronized (mPackages) {
11254            if (!isExternalMediaAvailable()) {
11255                // If the external storage is no longer mounted at this point,
11256                // the caller may not have been able to delete all of this
11257                // packages files and can not delete any more.  Bail.
11258                return null;
11259            }
11260            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11261            if (lastPackage != null) {
11262                pkgs.remove(lastPackage);
11263            }
11264            if (pkgs.size() > 0) {
11265                return pkgs.get(0);
11266            }
11267        }
11268        return null;
11269    }
11270
11271    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11272        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11273                userId, andCode ? 1 : 0, packageName);
11274        if (mSystemReady) {
11275            msg.sendToTarget();
11276        } else {
11277            if (mPostSystemReadyMessages == null) {
11278                mPostSystemReadyMessages = new ArrayList<>();
11279            }
11280            mPostSystemReadyMessages.add(msg);
11281        }
11282    }
11283
11284    void startCleaningPackages() {
11285        // reader
11286        if (!isExternalMediaAvailable()) {
11287            return;
11288        }
11289        synchronized (mPackages) {
11290            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11291                return;
11292            }
11293        }
11294        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11295        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11296        IActivityManager am = ActivityManagerNative.getDefault();
11297        if (am != null) {
11298            try {
11299                am.startService(null, intent, null, mContext.getOpPackageName(),
11300                        UserHandle.USER_SYSTEM);
11301            } catch (RemoteException e) {
11302            }
11303        }
11304    }
11305
11306    @Override
11307    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11308            int installFlags, String installerPackageName, int userId) {
11309        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11310
11311        final int callingUid = Binder.getCallingUid();
11312        enforceCrossUserPermission(callingUid, userId,
11313                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11314
11315        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11316            try {
11317                if (observer != null) {
11318                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11319                }
11320            } catch (RemoteException re) {
11321            }
11322            return;
11323        }
11324
11325        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11326            installFlags |= PackageManager.INSTALL_FROM_ADB;
11327
11328        } else {
11329            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11330            // about installerPackageName.
11331
11332            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11333            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11334        }
11335
11336        UserHandle user;
11337        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11338            user = UserHandle.ALL;
11339        } else {
11340            user = new UserHandle(userId);
11341        }
11342
11343        // Only system components can circumvent runtime permissions when installing.
11344        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11345                && mContext.checkCallingOrSelfPermission(Manifest.permission
11346                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11347            throw new SecurityException("You need the "
11348                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11349                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11350        }
11351
11352        final File originFile = new File(originPath);
11353        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11354
11355        final Message msg = mHandler.obtainMessage(INIT_COPY);
11356        final VerificationInfo verificationInfo = new VerificationInfo(
11357                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11358        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11359                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11360                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11361                null /*certificates*/);
11362        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11363        msg.obj = params;
11364
11365        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11366                System.identityHashCode(msg.obj));
11367        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11368                System.identityHashCode(msg.obj));
11369
11370        mHandler.sendMessage(msg);
11371    }
11372
11373    void installStage(String packageName, File stagedDir, String stagedCid,
11374            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11375            String installerPackageName, int installerUid, UserHandle user,
11376            Certificate[][] certificates) {
11377        if (DEBUG_EPHEMERAL) {
11378            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11379                Slog.d(TAG, "Ephemeral install of " + packageName);
11380            }
11381        }
11382        final VerificationInfo verificationInfo = new VerificationInfo(
11383                sessionParams.originatingUri, sessionParams.referrerUri,
11384                sessionParams.originatingUid, installerUid);
11385
11386        final OriginInfo origin;
11387        if (stagedDir != null) {
11388            origin = OriginInfo.fromStagedFile(stagedDir);
11389        } else {
11390            origin = OriginInfo.fromStagedContainer(stagedCid);
11391        }
11392
11393        final Message msg = mHandler.obtainMessage(INIT_COPY);
11394        final InstallParams params = new InstallParams(origin, null, observer,
11395                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11396                verificationInfo, user, sessionParams.abiOverride,
11397                sessionParams.grantedRuntimePermissions, certificates);
11398        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11399        msg.obj = params;
11400
11401        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11402                System.identityHashCode(msg.obj));
11403        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11404                System.identityHashCode(msg.obj));
11405
11406        mHandler.sendMessage(msg);
11407    }
11408
11409    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11410            int userId) {
11411        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11412        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11413    }
11414
11415    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11416            int appId, int userId) {
11417        Bundle extras = new Bundle(1);
11418        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11419
11420        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11421                packageName, extras, 0, null, null, new int[] {userId});
11422        try {
11423            IActivityManager am = ActivityManagerNative.getDefault();
11424            if (isSystem && am.isUserRunning(userId, 0)) {
11425                // The just-installed/enabled app is bundled on the system, so presumed
11426                // to be able to run automatically without needing an explicit launch.
11427                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11428                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11429                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11430                        .setPackage(packageName);
11431                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11432                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11433            }
11434        } catch (RemoteException e) {
11435            // shouldn't happen
11436            Slog.w(TAG, "Unable to bootstrap installed package", e);
11437        }
11438    }
11439
11440    @Override
11441    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11442            int userId) {
11443        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11444        PackageSetting pkgSetting;
11445        final int uid = Binder.getCallingUid();
11446        enforceCrossUserPermission(uid, userId,
11447                true /* requireFullPermission */, true /* checkShell */,
11448                "setApplicationHiddenSetting for user " + userId);
11449
11450        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11451            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11452            return false;
11453        }
11454
11455        long callingId = Binder.clearCallingIdentity();
11456        try {
11457            boolean sendAdded = false;
11458            boolean sendRemoved = false;
11459            // writer
11460            synchronized (mPackages) {
11461                pkgSetting = mSettings.mPackages.get(packageName);
11462                if (pkgSetting == null) {
11463                    return false;
11464                }
11465                if (pkgSetting.getHidden(userId) != hidden) {
11466                    pkgSetting.setHidden(hidden, userId);
11467                    mSettings.writePackageRestrictionsLPr(userId);
11468                    if (hidden) {
11469                        sendRemoved = true;
11470                    } else {
11471                        sendAdded = true;
11472                    }
11473                }
11474            }
11475            if (sendAdded) {
11476                sendPackageAddedForUser(packageName, pkgSetting, userId);
11477                return true;
11478            }
11479            if (sendRemoved) {
11480                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11481                        "hiding pkg");
11482                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11483                return true;
11484            }
11485        } finally {
11486            Binder.restoreCallingIdentity(callingId);
11487        }
11488        return false;
11489    }
11490
11491    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11492            int userId) {
11493        final PackageRemovedInfo info = new PackageRemovedInfo();
11494        info.removedPackage = packageName;
11495        info.removedUsers = new int[] {userId};
11496        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11497        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11498    }
11499
11500    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11501        if (pkgList.length > 0) {
11502            Bundle extras = new Bundle(1);
11503            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11504
11505            sendPackageBroadcast(
11506                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11507                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11508                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11509                    new int[] {userId});
11510        }
11511    }
11512
11513    /**
11514     * Returns true if application is not found or there was an error. Otherwise it returns
11515     * the hidden state of the package for the given user.
11516     */
11517    @Override
11518    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11519        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11520        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11521                true /* requireFullPermission */, false /* checkShell */,
11522                "getApplicationHidden for user " + userId);
11523        PackageSetting pkgSetting;
11524        long callingId = Binder.clearCallingIdentity();
11525        try {
11526            // writer
11527            synchronized (mPackages) {
11528                pkgSetting = mSettings.mPackages.get(packageName);
11529                if (pkgSetting == null) {
11530                    return true;
11531                }
11532                return pkgSetting.getHidden(userId);
11533            }
11534        } finally {
11535            Binder.restoreCallingIdentity(callingId);
11536        }
11537    }
11538
11539    /**
11540     * @hide
11541     */
11542    @Override
11543    public int installExistingPackageAsUser(String packageName, int userId) {
11544        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11545                null);
11546        PackageSetting pkgSetting;
11547        final int uid = Binder.getCallingUid();
11548        enforceCrossUserPermission(uid, userId,
11549                true /* requireFullPermission */, true /* checkShell */,
11550                "installExistingPackage for user " + userId);
11551        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11552            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11553        }
11554
11555        long callingId = Binder.clearCallingIdentity();
11556        try {
11557            boolean installed = false;
11558
11559            // writer
11560            synchronized (mPackages) {
11561                pkgSetting = mSettings.mPackages.get(packageName);
11562                if (pkgSetting == null) {
11563                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11564                }
11565                if (!pkgSetting.getInstalled(userId)) {
11566                    pkgSetting.setInstalled(true, userId);
11567                    pkgSetting.setHidden(false, userId);
11568                    mSettings.writePackageRestrictionsLPr(userId);
11569                    installed = true;
11570                }
11571            }
11572
11573            if (installed) {
11574                if (pkgSetting.pkg != null) {
11575                    synchronized (mInstallLock) {
11576                        // We don't need to freeze for a brand new install
11577                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11578                    }
11579                }
11580                sendPackageAddedForUser(packageName, pkgSetting, userId);
11581            }
11582        } finally {
11583            Binder.restoreCallingIdentity(callingId);
11584        }
11585
11586        return PackageManager.INSTALL_SUCCEEDED;
11587    }
11588
11589    boolean isUserRestricted(int userId, String restrictionKey) {
11590        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11591        if (restrictions.getBoolean(restrictionKey, false)) {
11592            Log.w(TAG, "User is restricted: " + restrictionKey);
11593            return true;
11594        }
11595        return false;
11596    }
11597
11598    @Override
11599    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11600            int userId) {
11601        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11602        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11603                true /* requireFullPermission */, true /* checkShell */,
11604                "setPackagesSuspended for user " + userId);
11605
11606        if (ArrayUtils.isEmpty(packageNames)) {
11607            return packageNames;
11608        }
11609
11610        // List of package names for whom the suspended state has changed.
11611        List<String> changedPackages = new ArrayList<>(packageNames.length);
11612        // List of package names for whom the suspended state is not set as requested in this
11613        // method.
11614        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11615        long callingId = Binder.clearCallingIdentity();
11616        try {
11617            for (int i = 0; i < packageNames.length; i++) {
11618                String packageName = packageNames[i];
11619                boolean changed = false;
11620                final int appId;
11621                synchronized (mPackages) {
11622                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11623                    if (pkgSetting == null) {
11624                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11625                                + "\". Skipping suspending/un-suspending.");
11626                        unactionedPackages.add(packageName);
11627                        continue;
11628                    }
11629                    appId = pkgSetting.appId;
11630                    if (pkgSetting.getSuspended(userId) != suspended) {
11631                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11632                            unactionedPackages.add(packageName);
11633                            continue;
11634                        }
11635                        pkgSetting.setSuspended(suspended, userId);
11636                        mSettings.writePackageRestrictionsLPr(userId);
11637                        changed = true;
11638                        changedPackages.add(packageName);
11639                    }
11640                }
11641
11642                if (changed && suspended) {
11643                    killApplication(packageName, UserHandle.getUid(userId, appId),
11644                            "suspending package");
11645                }
11646            }
11647        } finally {
11648            Binder.restoreCallingIdentity(callingId);
11649        }
11650
11651        if (!changedPackages.isEmpty()) {
11652            sendPackagesSuspendedForUser(changedPackages.toArray(
11653                    new String[changedPackages.size()]), userId, suspended);
11654        }
11655
11656        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11657    }
11658
11659    @Override
11660    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11661        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11662                true /* requireFullPermission */, false /* checkShell */,
11663                "isPackageSuspendedForUser for user " + userId);
11664        synchronized (mPackages) {
11665            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11666            if (pkgSetting == null) {
11667                throw new IllegalArgumentException("Unknown target package: " + packageName);
11668            }
11669            return pkgSetting.getSuspended(userId);
11670        }
11671    }
11672
11673    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11674        if (isPackageDeviceAdmin(packageName, userId)) {
11675            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11676                    + "\": has an active device admin");
11677            return false;
11678        }
11679
11680        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11681        if (packageName.equals(activeLauncherPackageName)) {
11682            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11683                    + "\": contains the active launcher");
11684            return false;
11685        }
11686
11687        if (packageName.equals(mRequiredInstallerPackage)) {
11688            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11689                    + "\": required for package installation");
11690            return false;
11691        }
11692
11693        if (packageName.equals(mRequiredVerifierPackage)) {
11694            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11695                    + "\": required for package verification");
11696            return false;
11697        }
11698
11699        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11700            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11701                    + "\": is the default dialer");
11702            return false;
11703        }
11704
11705        return true;
11706    }
11707
11708    private String getActiveLauncherPackageName(int userId) {
11709        Intent intent = new Intent(Intent.ACTION_MAIN);
11710        intent.addCategory(Intent.CATEGORY_HOME);
11711        ResolveInfo resolveInfo = resolveIntent(
11712                intent,
11713                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11714                PackageManager.MATCH_DEFAULT_ONLY,
11715                userId);
11716
11717        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11718    }
11719
11720    private String getDefaultDialerPackageName(int userId) {
11721        synchronized (mPackages) {
11722            return mSettings.getDefaultDialerPackageNameLPw(userId);
11723        }
11724    }
11725
11726    @Override
11727    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11728        mContext.enforceCallingOrSelfPermission(
11729                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11730                "Only package verification agents can verify applications");
11731
11732        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11733        final PackageVerificationResponse response = new PackageVerificationResponse(
11734                verificationCode, Binder.getCallingUid());
11735        msg.arg1 = id;
11736        msg.obj = response;
11737        mHandler.sendMessage(msg);
11738    }
11739
11740    @Override
11741    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11742            long millisecondsToDelay) {
11743        mContext.enforceCallingOrSelfPermission(
11744                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11745                "Only package verification agents can extend verification timeouts");
11746
11747        final PackageVerificationState state = mPendingVerification.get(id);
11748        final PackageVerificationResponse response = new PackageVerificationResponse(
11749                verificationCodeAtTimeout, Binder.getCallingUid());
11750
11751        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11752            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11753        }
11754        if (millisecondsToDelay < 0) {
11755            millisecondsToDelay = 0;
11756        }
11757        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11758                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11759            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11760        }
11761
11762        if ((state != null) && !state.timeoutExtended()) {
11763            state.extendTimeout();
11764
11765            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11766            msg.arg1 = id;
11767            msg.obj = response;
11768            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11769        }
11770    }
11771
11772    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11773            int verificationCode, UserHandle user) {
11774        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11775        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11776        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11777        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11778        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11779
11780        mContext.sendBroadcastAsUser(intent, user,
11781                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11782    }
11783
11784    private ComponentName matchComponentForVerifier(String packageName,
11785            List<ResolveInfo> receivers) {
11786        ActivityInfo targetReceiver = null;
11787
11788        final int NR = receivers.size();
11789        for (int i = 0; i < NR; i++) {
11790            final ResolveInfo info = receivers.get(i);
11791            if (info.activityInfo == null) {
11792                continue;
11793            }
11794
11795            if (packageName.equals(info.activityInfo.packageName)) {
11796                targetReceiver = info.activityInfo;
11797                break;
11798            }
11799        }
11800
11801        if (targetReceiver == null) {
11802            return null;
11803        }
11804
11805        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11806    }
11807
11808    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11809            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11810        if (pkgInfo.verifiers.length == 0) {
11811            return null;
11812        }
11813
11814        final int N = pkgInfo.verifiers.length;
11815        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11816        for (int i = 0; i < N; i++) {
11817            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11818
11819            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11820                    receivers);
11821            if (comp == null) {
11822                continue;
11823            }
11824
11825            final int verifierUid = getUidForVerifier(verifierInfo);
11826            if (verifierUid == -1) {
11827                continue;
11828            }
11829
11830            if (DEBUG_VERIFY) {
11831                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11832                        + " with the correct signature");
11833            }
11834            sufficientVerifiers.add(comp);
11835            verificationState.addSufficientVerifier(verifierUid);
11836        }
11837
11838        return sufficientVerifiers;
11839    }
11840
11841    private int getUidForVerifier(VerifierInfo verifierInfo) {
11842        synchronized (mPackages) {
11843            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11844            if (pkg == null) {
11845                return -1;
11846            } else if (pkg.mSignatures.length != 1) {
11847                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11848                        + " has more than one signature; ignoring");
11849                return -1;
11850            }
11851
11852            /*
11853             * If the public key of the package's signature does not match
11854             * our expected public key, then this is a different package and
11855             * we should skip.
11856             */
11857
11858            final byte[] expectedPublicKey;
11859            try {
11860                final Signature verifierSig = pkg.mSignatures[0];
11861                final PublicKey publicKey = verifierSig.getPublicKey();
11862                expectedPublicKey = publicKey.getEncoded();
11863            } catch (CertificateException e) {
11864                return -1;
11865            }
11866
11867            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11868
11869            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11870                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11871                        + " does not have the expected public key; ignoring");
11872                return -1;
11873            }
11874
11875            return pkg.applicationInfo.uid;
11876        }
11877    }
11878
11879    @Override
11880    public void finishPackageInstall(int token, boolean didLaunch) {
11881        enforceSystemOrRoot("Only the system is allowed to finish installs");
11882
11883        if (DEBUG_INSTALL) {
11884            Slog.v(TAG, "BM finishing package install for " + token);
11885        }
11886        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11887
11888        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11889        mHandler.sendMessage(msg);
11890    }
11891
11892    /**
11893     * Get the verification agent timeout.
11894     *
11895     * @return verification timeout in milliseconds
11896     */
11897    private long getVerificationTimeout() {
11898        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11899                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11900                DEFAULT_VERIFICATION_TIMEOUT);
11901    }
11902
11903    /**
11904     * Get the default verification agent response code.
11905     *
11906     * @return default verification response code
11907     */
11908    private int getDefaultVerificationResponse() {
11909        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11910                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11911                DEFAULT_VERIFICATION_RESPONSE);
11912    }
11913
11914    /**
11915     * Check whether or not package verification has been enabled.
11916     *
11917     * @return true if verification should be performed
11918     */
11919    private boolean isVerificationEnabled(int userId, int installFlags) {
11920        if (!DEFAULT_VERIFY_ENABLE) {
11921            return false;
11922        }
11923        // Ephemeral apps don't get the full verification treatment
11924        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11925            if (DEBUG_EPHEMERAL) {
11926                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11927            }
11928            return false;
11929        }
11930
11931        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11932
11933        // Check if installing from ADB
11934        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11935            // Do not run verification in a test harness environment
11936            if (ActivityManager.isRunningInTestHarness()) {
11937                return false;
11938            }
11939            if (ensureVerifyAppsEnabled) {
11940                return true;
11941            }
11942            // Check if the developer does not want package verification for ADB installs
11943            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11944                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11945                return false;
11946            }
11947        }
11948
11949        if (ensureVerifyAppsEnabled) {
11950            return true;
11951        }
11952
11953        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11954                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11955    }
11956
11957    @Override
11958    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11959            throws RemoteException {
11960        mContext.enforceCallingOrSelfPermission(
11961                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11962                "Only intentfilter verification agents can verify applications");
11963
11964        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11965        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11966                Binder.getCallingUid(), verificationCode, failedDomains);
11967        msg.arg1 = id;
11968        msg.obj = response;
11969        mHandler.sendMessage(msg);
11970    }
11971
11972    @Override
11973    public int getIntentVerificationStatus(String packageName, int userId) {
11974        synchronized (mPackages) {
11975            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11976        }
11977    }
11978
11979    @Override
11980    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11981        mContext.enforceCallingOrSelfPermission(
11982                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11983
11984        boolean result = false;
11985        synchronized (mPackages) {
11986            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11987        }
11988        if (result) {
11989            scheduleWritePackageRestrictionsLocked(userId);
11990        }
11991        return result;
11992    }
11993
11994    @Override
11995    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11996            String packageName) {
11997        synchronized (mPackages) {
11998            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11999        }
12000    }
12001
12002    @Override
12003    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12004        if (TextUtils.isEmpty(packageName)) {
12005            return ParceledListSlice.emptyList();
12006        }
12007        synchronized (mPackages) {
12008            PackageParser.Package pkg = mPackages.get(packageName);
12009            if (pkg == null || pkg.activities == null) {
12010                return ParceledListSlice.emptyList();
12011            }
12012            final int count = pkg.activities.size();
12013            ArrayList<IntentFilter> result = new ArrayList<>();
12014            for (int n=0; n<count; n++) {
12015                PackageParser.Activity activity = pkg.activities.get(n);
12016                if (activity.intents != null && activity.intents.size() > 0) {
12017                    result.addAll(activity.intents);
12018                }
12019            }
12020            return new ParceledListSlice<>(result);
12021        }
12022    }
12023
12024    @Override
12025    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12026        mContext.enforceCallingOrSelfPermission(
12027                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12028
12029        synchronized (mPackages) {
12030            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12031            if (packageName != null) {
12032                result |= updateIntentVerificationStatus(packageName,
12033                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12034                        userId);
12035                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12036                        packageName, userId);
12037            }
12038            return result;
12039        }
12040    }
12041
12042    @Override
12043    public String getDefaultBrowserPackageName(int userId) {
12044        synchronized (mPackages) {
12045            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12046        }
12047    }
12048
12049    /**
12050     * Get the "allow unknown sources" setting.
12051     *
12052     * @return the current "allow unknown sources" setting
12053     */
12054    private int getUnknownSourcesSettings() {
12055        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12056                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12057                -1);
12058    }
12059
12060    @Override
12061    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12062        final int uid = Binder.getCallingUid();
12063        // writer
12064        synchronized (mPackages) {
12065            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12066            if (targetPackageSetting == null) {
12067                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12068            }
12069
12070            PackageSetting installerPackageSetting;
12071            if (installerPackageName != null) {
12072                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12073                if (installerPackageSetting == null) {
12074                    throw new IllegalArgumentException("Unknown installer package: "
12075                            + installerPackageName);
12076                }
12077            } else {
12078                installerPackageSetting = null;
12079            }
12080
12081            Signature[] callerSignature;
12082            Object obj = mSettings.getUserIdLPr(uid);
12083            if (obj != null) {
12084                if (obj instanceof SharedUserSetting) {
12085                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12086                } else if (obj instanceof PackageSetting) {
12087                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12088                } else {
12089                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12090                }
12091            } else {
12092                throw new SecurityException("Unknown calling UID: " + uid);
12093            }
12094
12095            // Verify: can't set installerPackageName to a package that is
12096            // not signed with the same cert as the caller.
12097            if (installerPackageSetting != null) {
12098                if (compareSignatures(callerSignature,
12099                        installerPackageSetting.signatures.mSignatures)
12100                        != PackageManager.SIGNATURE_MATCH) {
12101                    throw new SecurityException(
12102                            "Caller does not have same cert as new installer package "
12103                            + installerPackageName);
12104                }
12105            }
12106
12107            // Verify: if target already has an installer package, it must
12108            // be signed with the same cert as the caller.
12109            if (targetPackageSetting.installerPackageName != null) {
12110                PackageSetting setting = mSettings.mPackages.get(
12111                        targetPackageSetting.installerPackageName);
12112                // If the currently set package isn't valid, then it's always
12113                // okay to change it.
12114                if (setting != null) {
12115                    if (compareSignatures(callerSignature,
12116                            setting.signatures.mSignatures)
12117                            != PackageManager.SIGNATURE_MATCH) {
12118                        throw new SecurityException(
12119                                "Caller does not have same cert as old installer package "
12120                                + targetPackageSetting.installerPackageName);
12121                    }
12122                }
12123            }
12124
12125            // Okay!
12126            targetPackageSetting.installerPackageName = installerPackageName;
12127            if (installerPackageName != null) {
12128                mSettings.mInstallerPackages.add(installerPackageName);
12129            }
12130            scheduleWriteSettingsLocked();
12131        }
12132    }
12133
12134    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12135        // Queue up an async operation since the package installation may take a little while.
12136        mHandler.post(new Runnable() {
12137            public void run() {
12138                mHandler.removeCallbacks(this);
12139                 // Result object to be returned
12140                PackageInstalledInfo res = new PackageInstalledInfo();
12141                res.setReturnCode(currentStatus);
12142                res.uid = -1;
12143                res.pkg = null;
12144                res.removedInfo = null;
12145                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12146                    args.doPreInstall(res.returnCode);
12147                    synchronized (mInstallLock) {
12148                        installPackageTracedLI(args, res);
12149                    }
12150                    args.doPostInstall(res.returnCode, res.uid);
12151                }
12152
12153                // A restore should be performed at this point if (a) the install
12154                // succeeded, (b) the operation is not an update, and (c) the new
12155                // package has not opted out of backup participation.
12156                final boolean update = res.removedInfo != null
12157                        && res.removedInfo.removedPackage != null;
12158                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12159                boolean doRestore = !update
12160                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12161
12162                // Set up the post-install work request bookkeeping.  This will be used
12163                // and cleaned up by the post-install event handling regardless of whether
12164                // there's a restore pass performed.  Token values are >= 1.
12165                int token;
12166                if (mNextInstallToken < 0) mNextInstallToken = 1;
12167                token = mNextInstallToken++;
12168
12169                PostInstallData data = new PostInstallData(args, res);
12170                mRunningInstalls.put(token, data);
12171                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12172
12173                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12174                    // Pass responsibility to the Backup Manager.  It will perform a
12175                    // restore if appropriate, then pass responsibility back to the
12176                    // Package Manager to run the post-install observer callbacks
12177                    // and broadcasts.
12178                    IBackupManager bm = IBackupManager.Stub.asInterface(
12179                            ServiceManager.getService(Context.BACKUP_SERVICE));
12180                    if (bm != null) {
12181                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12182                                + " to BM for possible restore");
12183                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12184                        try {
12185                            // TODO: http://b/22388012
12186                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12187                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12188                            } else {
12189                                doRestore = false;
12190                            }
12191                        } catch (RemoteException e) {
12192                            // can't happen; the backup manager is local
12193                        } catch (Exception e) {
12194                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12195                            doRestore = false;
12196                        }
12197                    } else {
12198                        Slog.e(TAG, "Backup Manager not found!");
12199                        doRestore = false;
12200                    }
12201                }
12202
12203                if (!doRestore) {
12204                    // No restore possible, or the Backup Manager was mysteriously not
12205                    // available -- just fire the post-install work request directly.
12206                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12207
12208                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12209
12210                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12211                    mHandler.sendMessage(msg);
12212                }
12213            }
12214        });
12215    }
12216
12217    /**
12218     * Callback from PackageSettings whenever an app is first transitioned out of the
12219     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12220     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12221     * here whether the app is the target of an ongoing install, and only send the
12222     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12223     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12224     * handling.
12225     */
12226    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12227        // Serialize this with the rest of the install-process message chain.  In the
12228        // restore-at-install case, this Runnable will necessarily run before the
12229        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12230        // are coherent.  In the non-restore case, the app has already completed install
12231        // and been launched through some other means, so it is not in a problematic
12232        // state for observers to see the FIRST_LAUNCH signal.
12233        mHandler.post(new Runnable() {
12234            @Override
12235            public void run() {
12236                for (int i = 0; i < mRunningInstalls.size(); i++) {
12237                    final PostInstallData data = mRunningInstalls.valueAt(i);
12238                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12239                        // right package; but is it for the right user?
12240                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12241                            if (userId == data.res.newUsers[uIndex]) {
12242                                if (DEBUG_BACKUP) {
12243                                    Slog.i(TAG, "Package " + pkgName
12244                                            + " being restored so deferring FIRST_LAUNCH");
12245                                }
12246                                return;
12247                            }
12248                        }
12249                    }
12250                }
12251                // didn't find it, so not being restored
12252                if (DEBUG_BACKUP) {
12253                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12254                }
12255                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12256            }
12257        });
12258    }
12259
12260    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12261        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12262                installerPkg, null, userIds);
12263    }
12264
12265    private abstract class HandlerParams {
12266        private static final int MAX_RETRIES = 4;
12267
12268        /**
12269         * Number of times startCopy() has been attempted and had a non-fatal
12270         * error.
12271         */
12272        private int mRetries = 0;
12273
12274        /** User handle for the user requesting the information or installation. */
12275        private final UserHandle mUser;
12276        String traceMethod;
12277        int traceCookie;
12278
12279        HandlerParams(UserHandle user) {
12280            mUser = user;
12281        }
12282
12283        UserHandle getUser() {
12284            return mUser;
12285        }
12286
12287        HandlerParams setTraceMethod(String traceMethod) {
12288            this.traceMethod = traceMethod;
12289            return this;
12290        }
12291
12292        HandlerParams setTraceCookie(int traceCookie) {
12293            this.traceCookie = traceCookie;
12294            return this;
12295        }
12296
12297        final boolean startCopy() {
12298            boolean res;
12299            try {
12300                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12301
12302                if (++mRetries > MAX_RETRIES) {
12303                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12304                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12305                    handleServiceError();
12306                    return false;
12307                } else {
12308                    handleStartCopy();
12309                    res = true;
12310                }
12311            } catch (RemoteException e) {
12312                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12313                mHandler.sendEmptyMessage(MCS_RECONNECT);
12314                res = false;
12315            }
12316            handleReturnCode();
12317            return res;
12318        }
12319
12320        final void serviceError() {
12321            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12322            handleServiceError();
12323            handleReturnCode();
12324        }
12325
12326        abstract void handleStartCopy() throws RemoteException;
12327        abstract void handleServiceError();
12328        abstract void handleReturnCode();
12329    }
12330
12331    class MeasureParams extends HandlerParams {
12332        private final PackageStats mStats;
12333        private boolean mSuccess;
12334
12335        private final IPackageStatsObserver mObserver;
12336
12337        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12338            super(new UserHandle(stats.userHandle));
12339            mObserver = observer;
12340            mStats = stats;
12341        }
12342
12343        @Override
12344        public String toString() {
12345            return "MeasureParams{"
12346                + Integer.toHexString(System.identityHashCode(this))
12347                + " " + mStats.packageName + "}";
12348        }
12349
12350        @Override
12351        void handleStartCopy() throws RemoteException {
12352            synchronized (mInstallLock) {
12353                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12354            }
12355
12356            if (mSuccess) {
12357                final boolean mounted;
12358                if (Environment.isExternalStorageEmulated()) {
12359                    mounted = true;
12360                } else {
12361                    final String status = Environment.getExternalStorageState();
12362                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12363                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12364                }
12365
12366                if (mounted) {
12367                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12368
12369                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12370                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12371
12372                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12373                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12374
12375                    // Always subtract cache size, since it's a subdirectory
12376                    mStats.externalDataSize -= mStats.externalCacheSize;
12377
12378                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12379                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12380
12381                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12382                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12383                }
12384            }
12385        }
12386
12387        @Override
12388        void handleReturnCode() {
12389            if (mObserver != null) {
12390                try {
12391                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12392                } catch (RemoteException e) {
12393                    Slog.i(TAG, "Observer no longer exists.");
12394                }
12395            }
12396        }
12397
12398        @Override
12399        void handleServiceError() {
12400            Slog.e(TAG, "Could not measure application " + mStats.packageName
12401                            + " external storage");
12402        }
12403    }
12404
12405    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12406            throws RemoteException {
12407        long result = 0;
12408        for (File path : paths) {
12409            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12410        }
12411        return result;
12412    }
12413
12414    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12415        for (File path : paths) {
12416            try {
12417                mcs.clearDirectory(path.getAbsolutePath());
12418            } catch (RemoteException e) {
12419            }
12420        }
12421    }
12422
12423    static class OriginInfo {
12424        /**
12425         * Location where install is coming from, before it has been
12426         * copied/renamed into place. This could be a single monolithic APK
12427         * file, or a cluster directory. This location may be untrusted.
12428         */
12429        final File file;
12430        final String cid;
12431
12432        /**
12433         * Flag indicating that {@link #file} or {@link #cid} has already been
12434         * staged, meaning downstream users don't need to defensively copy the
12435         * contents.
12436         */
12437        final boolean staged;
12438
12439        /**
12440         * Flag indicating that {@link #file} or {@link #cid} is an already
12441         * installed app that is being moved.
12442         */
12443        final boolean existing;
12444
12445        final String resolvedPath;
12446        final File resolvedFile;
12447
12448        static OriginInfo fromNothing() {
12449            return new OriginInfo(null, null, false, false);
12450        }
12451
12452        static OriginInfo fromUntrustedFile(File file) {
12453            return new OriginInfo(file, null, false, false);
12454        }
12455
12456        static OriginInfo fromExistingFile(File file) {
12457            return new OriginInfo(file, null, false, true);
12458        }
12459
12460        static OriginInfo fromStagedFile(File file) {
12461            return new OriginInfo(file, null, true, false);
12462        }
12463
12464        static OriginInfo fromStagedContainer(String cid) {
12465            return new OriginInfo(null, cid, true, false);
12466        }
12467
12468        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12469            this.file = file;
12470            this.cid = cid;
12471            this.staged = staged;
12472            this.existing = existing;
12473
12474            if (cid != null) {
12475                resolvedPath = PackageHelper.getSdDir(cid);
12476                resolvedFile = new File(resolvedPath);
12477            } else if (file != null) {
12478                resolvedPath = file.getAbsolutePath();
12479                resolvedFile = file;
12480            } else {
12481                resolvedPath = null;
12482                resolvedFile = null;
12483            }
12484        }
12485    }
12486
12487    static class MoveInfo {
12488        final int moveId;
12489        final String fromUuid;
12490        final String toUuid;
12491        final String packageName;
12492        final String dataAppName;
12493        final int appId;
12494        final String seinfo;
12495        final int targetSdkVersion;
12496
12497        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12498                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12499            this.moveId = moveId;
12500            this.fromUuid = fromUuid;
12501            this.toUuid = toUuid;
12502            this.packageName = packageName;
12503            this.dataAppName = dataAppName;
12504            this.appId = appId;
12505            this.seinfo = seinfo;
12506            this.targetSdkVersion = targetSdkVersion;
12507        }
12508    }
12509
12510    static class VerificationInfo {
12511        /** A constant used to indicate that a uid value is not present. */
12512        public static final int NO_UID = -1;
12513
12514        /** URI referencing where the package was downloaded from. */
12515        final Uri originatingUri;
12516
12517        /** HTTP referrer URI associated with the originatingURI. */
12518        final Uri referrer;
12519
12520        /** UID of the application that the install request originated from. */
12521        final int originatingUid;
12522
12523        /** UID of application requesting the install */
12524        final int installerUid;
12525
12526        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12527            this.originatingUri = originatingUri;
12528            this.referrer = referrer;
12529            this.originatingUid = originatingUid;
12530            this.installerUid = installerUid;
12531        }
12532    }
12533
12534    class InstallParams extends HandlerParams {
12535        final OriginInfo origin;
12536        final MoveInfo move;
12537        final IPackageInstallObserver2 observer;
12538        int installFlags;
12539        final String installerPackageName;
12540        final String volumeUuid;
12541        private InstallArgs mArgs;
12542        private int mRet;
12543        final String packageAbiOverride;
12544        final String[] grantedRuntimePermissions;
12545        final VerificationInfo verificationInfo;
12546        final Certificate[][] certificates;
12547
12548        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12549                int installFlags, String installerPackageName, String volumeUuid,
12550                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12551                String[] grantedPermissions, Certificate[][] certificates) {
12552            super(user);
12553            this.origin = origin;
12554            this.move = move;
12555            this.observer = observer;
12556            this.installFlags = installFlags;
12557            this.installerPackageName = installerPackageName;
12558            this.volumeUuid = volumeUuid;
12559            this.verificationInfo = verificationInfo;
12560            this.packageAbiOverride = packageAbiOverride;
12561            this.grantedRuntimePermissions = grantedPermissions;
12562            this.certificates = certificates;
12563        }
12564
12565        @Override
12566        public String toString() {
12567            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12568                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12569        }
12570
12571        private int installLocationPolicy(PackageInfoLite pkgLite) {
12572            String packageName = pkgLite.packageName;
12573            int installLocation = pkgLite.installLocation;
12574            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12575            // reader
12576            synchronized (mPackages) {
12577                // Currently installed package which the new package is attempting to replace or
12578                // null if no such package is installed.
12579                PackageParser.Package installedPkg = mPackages.get(packageName);
12580                // Package which currently owns the data which the new package will own if installed.
12581                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12582                // will be null whereas dataOwnerPkg will contain information about the package
12583                // which was uninstalled while keeping its data.
12584                PackageParser.Package dataOwnerPkg = installedPkg;
12585                if (dataOwnerPkg  == null) {
12586                    PackageSetting ps = mSettings.mPackages.get(packageName);
12587                    if (ps != null) {
12588                        dataOwnerPkg = ps.pkg;
12589                    }
12590                }
12591
12592                if (dataOwnerPkg != null) {
12593                    // If installed, the package will get access to data left on the device by its
12594                    // predecessor. As a security measure, this is permited only if this is not a
12595                    // version downgrade or if the predecessor package is marked as debuggable and
12596                    // a downgrade is explicitly requested.
12597                    //
12598                    // On debuggable platform builds, downgrades are permitted even for
12599                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12600                    // not offer security guarantees and thus it's OK to disable some security
12601                    // mechanisms to make debugging/testing easier on those builds. However, even on
12602                    // debuggable builds downgrades of packages are permitted only if requested via
12603                    // installFlags. This is because we aim to keep the behavior of debuggable
12604                    // platform builds as close as possible to the behavior of non-debuggable
12605                    // platform builds.
12606                    final boolean downgradeRequested =
12607                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12608                    final boolean packageDebuggable =
12609                                (dataOwnerPkg.applicationInfo.flags
12610                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12611                    final boolean downgradePermitted =
12612                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12613                    if (!downgradePermitted) {
12614                        try {
12615                            checkDowngrade(dataOwnerPkg, pkgLite);
12616                        } catch (PackageManagerException e) {
12617                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12618                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12619                        }
12620                    }
12621                }
12622
12623                if (installedPkg != null) {
12624                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12625                        // Check for updated system application.
12626                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12627                            if (onSd) {
12628                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12629                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12630                            }
12631                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12632                        } else {
12633                            if (onSd) {
12634                                // Install flag overrides everything.
12635                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12636                            }
12637                            // If current upgrade specifies particular preference
12638                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12639                                // Application explicitly specified internal.
12640                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12641                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12642                                // App explictly prefers external. Let policy decide
12643                            } else {
12644                                // Prefer previous location
12645                                if (isExternal(installedPkg)) {
12646                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12647                                }
12648                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12649                            }
12650                        }
12651                    } else {
12652                        // Invalid install. Return error code
12653                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12654                    }
12655                }
12656            }
12657            // All the special cases have been taken care of.
12658            // Return result based on recommended install location.
12659            if (onSd) {
12660                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12661            }
12662            return pkgLite.recommendedInstallLocation;
12663        }
12664
12665        /*
12666         * Invoke remote method to get package information and install
12667         * location values. Override install location based on default
12668         * policy if needed and then create install arguments based
12669         * on the install location.
12670         */
12671        public void handleStartCopy() throws RemoteException {
12672            int ret = PackageManager.INSTALL_SUCCEEDED;
12673
12674            // If we're already staged, we've firmly committed to an install location
12675            if (origin.staged) {
12676                if (origin.file != null) {
12677                    installFlags |= PackageManager.INSTALL_INTERNAL;
12678                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12679                } else if (origin.cid != null) {
12680                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12681                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12682                } else {
12683                    throw new IllegalStateException("Invalid stage location");
12684                }
12685            }
12686
12687            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12688            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12689            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12690            PackageInfoLite pkgLite = null;
12691
12692            if (onInt && onSd) {
12693                // Check if both bits are set.
12694                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12695                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12696            } else if (onSd && ephemeral) {
12697                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12698                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12699            } else {
12700                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12701                        packageAbiOverride);
12702
12703                if (DEBUG_EPHEMERAL && ephemeral) {
12704                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12705                }
12706
12707                /*
12708                 * If we have too little free space, try to free cache
12709                 * before giving up.
12710                 */
12711                if (!origin.staged && pkgLite.recommendedInstallLocation
12712                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12713                    // TODO: focus freeing disk space on the target device
12714                    final StorageManager storage = StorageManager.from(mContext);
12715                    final long lowThreshold = storage.getStorageLowBytes(
12716                            Environment.getDataDirectory());
12717
12718                    final long sizeBytes = mContainerService.calculateInstalledSize(
12719                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12720
12721                    try {
12722                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12723                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12724                                installFlags, packageAbiOverride);
12725                    } catch (InstallerException e) {
12726                        Slog.w(TAG, "Failed to free cache", e);
12727                    }
12728
12729                    /*
12730                     * The cache free must have deleted the file we
12731                     * downloaded to install.
12732                     *
12733                     * TODO: fix the "freeCache" call to not delete
12734                     *       the file we care about.
12735                     */
12736                    if (pkgLite.recommendedInstallLocation
12737                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12738                        pkgLite.recommendedInstallLocation
12739                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12740                    }
12741                }
12742            }
12743
12744            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12745                int loc = pkgLite.recommendedInstallLocation;
12746                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12747                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12748                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12749                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12750                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12751                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12752                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12753                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12754                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12755                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12756                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12757                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12758                } else {
12759                    // Override with defaults if needed.
12760                    loc = installLocationPolicy(pkgLite);
12761                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12762                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12763                    } else if (!onSd && !onInt) {
12764                        // Override install location with flags
12765                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12766                            // Set the flag to install on external media.
12767                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12768                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12769                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12770                            if (DEBUG_EPHEMERAL) {
12771                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12772                            }
12773                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12774                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12775                                    |PackageManager.INSTALL_INTERNAL);
12776                        } else {
12777                            // Make sure the flag for installing on external
12778                            // media is unset
12779                            installFlags |= PackageManager.INSTALL_INTERNAL;
12780                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12781                        }
12782                    }
12783                }
12784            }
12785
12786            final InstallArgs args = createInstallArgs(this);
12787            mArgs = args;
12788
12789            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12790                // TODO: http://b/22976637
12791                // Apps installed for "all" users use the device owner to verify the app
12792                UserHandle verifierUser = getUser();
12793                if (verifierUser == UserHandle.ALL) {
12794                    verifierUser = UserHandle.SYSTEM;
12795                }
12796
12797                /*
12798                 * Determine if we have any installed package verifiers. If we
12799                 * do, then we'll defer to them to verify the packages.
12800                 */
12801                final int requiredUid = mRequiredVerifierPackage == null ? -1
12802                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12803                                verifierUser.getIdentifier());
12804                if (!origin.existing && requiredUid != -1
12805                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12806                    final Intent verification = new Intent(
12807                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12808                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12809                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12810                            PACKAGE_MIME_TYPE);
12811                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12812
12813                    // Query all live verifiers based on current user state
12814                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12815                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12816
12817                    if (DEBUG_VERIFY) {
12818                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12819                                + verification.toString() + " with " + pkgLite.verifiers.length
12820                                + " optional verifiers");
12821                    }
12822
12823                    final int verificationId = mPendingVerificationToken++;
12824
12825                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12826
12827                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12828                            installerPackageName);
12829
12830                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12831                            installFlags);
12832
12833                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12834                            pkgLite.packageName);
12835
12836                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12837                            pkgLite.versionCode);
12838
12839                    if (verificationInfo != null) {
12840                        if (verificationInfo.originatingUri != null) {
12841                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12842                                    verificationInfo.originatingUri);
12843                        }
12844                        if (verificationInfo.referrer != null) {
12845                            verification.putExtra(Intent.EXTRA_REFERRER,
12846                                    verificationInfo.referrer);
12847                        }
12848                        if (verificationInfo.originatingUid >= 0) {
12849                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12850                                    verificationInfo.originatingUid);
12851                        }
12852                        if (verificationInfo.installerUid >= 0) {
12853                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12854                                    verificationInfo.installerUid);
12855                        }
12856                    }
12857
12858                    final PackageVerificationState verificationState = new PackageVerificationState(
12859                            requiredUid, args);
12860
12861                    mPendingVerification.append(verificationId, verificationState);
12862
12863                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12864                            receivers, verificationState);
12865
12866                    /*
12867                     * If any sufficient verifiers were listed in the package
12868                     * manifest, attempt to ask them.
12869                     */
12870                    if (sufficientVerifiers != null) {
12871                        final int N = sufficientVerifiers.size();
12872                        if (N == 0) {
12873                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12874                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12875                        } else {
12876                            for (int i = 0; i < N; i++) {
12877                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12878
12879                                final Intent sufficientIntent = new Intent(verification);
12880                                sufficientIntent.setComponent(verifierComponent);
12881                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12882                            }
12883                        }
12884                    }
12885
12886                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12887                            mRequiredVerifierPackage, receivers);
12888                    if (ret == PackageManager.INSTALL_SUCCEEDED
12889                            && mRequiredVerifierPackage != null) {
12890                        Trace.asyncTraceBegin(
12891                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12892                        /*
12893                         * Send the intent to the required verification agent,
12894                         * but only start the verification timeout after the
12895                         * target BroadcastReceivers have run.
12896                         */
12897                        verification.setComponent(requiredVerifierComponent);
12898                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12899                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12900                                new BroadcastReceiver() {
12901                                    @Override
12902                                    public void onReceive(Context context, Intent intent) {
12903                                        final Message msg = mHandler
12904                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12905                                        msg.arg1 = verificationId;
12906                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12907                                    }
12908                                }, null, 0, null, null);
12909
12910                        /*
12911                         * We don't want the copy to proceed until verification
12912                         * succeeds, so null out this field.
12913                         */
12914                        mArgs = null;
12915                    }
12916                } else {
12917                    /*
12918                     * No package verification is enabled, so immediately start
12919                     * the remote call to initiate copy using temporary file.
12920                     */
12921                    ret = args.copyApk(mContainerService, true);
12922                }
12923            }
12924
12925            mRet = ret;
12926        }
12927
12928        @Override
12929        void handleReturnCode() {
12930            // If mArgs is null, then MCS couldn't be reached. When it
12931            // reconnects, it will try again to install. At that point, this
12932            // will succeed.
12933            if (mArgs != null) {
12934                processPendingInstall(mArgs, mRet);
12935            }
12936        }
12937
12938        @Override
12939        void handleServiceError() {
12940            mArgs = createInstallArgs(this);
12941            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12942        }
12943
12944        public boolean isForwardLocked() {
12945            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12946        }
12947    }
12948
12949    /**
12950     * Used during creation of InstallArgs
12951     *
12952     * @param installFlags package installation flags
12953     * @return true if should be installed on external storage
12954     */
12955    private static boolean installOnExternalAsec(int installFlags) {
12956        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12957            return false;
12958        }
12959        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12960            return true;
12961        }
12962        return false;
12963    }
12964
12965    /**
12966     * Used during creation of InstallArgs
12967     *
12968     * @param installFlags package installation flags
12969     * @return true if should be installed as forward locked
12970     */
12971    private static boolean installForwardLocked(int installFlags) {
12972        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12973    }
12974
12975    private InstallArgs createInstallArgs(InstallParams params) {
12976        if (params.move != null) {
12977            return new MoveInstallArgs(params);
12978        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12979            return new AsecInstallArgs(params);
12980        } else {
12981            return new FileInstallArgs(params);
12982        }
12983    }
12984
12985    /**
12986     * Create args that describe an existing installed package. Typically used
12987     * when cleaning up old installs, or used as a move source.
12988     */
12989    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12990            String resourcePath, String[] instructionSets) {
12991        final boolean isInAsec;
12992        if (installOnExternalAsec(installFlags)) {
12993            /* Apps on SD card are always in ASEC containers. */
12994            isInAsec = true;
12995        } else if (installForwardLocked(installFlags)
12996                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12997            /*
12998             * Forward-locked apps are only in ASEC containers if they're the
12999             * new style
13000             */
13001            isInAsec = true;
13002        } else {
13003            isInAsec = false;
13004        }
13005
13006        if (isInAsec) {
13007            return new AsecInstallArgs(codePath, instructionSets,
13008                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13009        } else {
13010            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13011        }
13012    }
13013
13014    static abstract class InstallArgs {
13015        /** @see InstallParams#origin */
13016        final OriginInfo origin;
13017        /** @see InstallParams#move */
13018        final MoveInfo move;
13019
13020        final IPackageInstallObserver2 observer;
13021        // Always refers to PackageManager flags only
13022        final int installFlags;
13023        final String installerPackageName;
13024        final String volumeUuid;
13025        final UserHandle user;
13026        final String abiOverride;
13027        final String[] installGrantPermissions;
13028        /** If non-null, drop an async trace when the install completes */
13029        final String traceMethod;
13030        final int traceCookie;
13031        final Certificate[][] certificates;
13032
13033        // The list of instruction sets supported by this app. This is currently
13034        // only used during the rmdex() phase to clean up resources. We can get rid of this
13035        // if we move dex files under the common app path.
13036        /* nullable */ String[] instructionSets;
13037
13038        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13039                int installFlags, String installerPackageName, String volumeUuid,
13040                UserHandle user, String[] instructionSets,
13041                String abiOverride, String[] installGrantPermissions,
13042                String traceMethod, int traceCookie, Certificate[][] certificates) {
13043            this.origin = origin;
13044            this.move = move;
13045            this.installFlags = installFlags;
13046            this.observer = observer;
13047            this.installerPackageName = installerPackageName;
13048            this.volumeUuid = volumeUuid;
13049            this.user = user;
13050            this.instructionSets = instructionSets;
13051            this.abiOverride = abiOverride;
13052            this.installGrantPermissions = installGrantPermissions;
13053            this.traceMethod = traceMethod;
13054            this.traceCookie = traceCookie;
13055            this.certificates = certificates;
13056        }
13057
13058        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13059        abstract int doPreInstall(int status);
13060
13061        /**
13062         * Rename package into final resting place. All paths on the given
13063         * scanned package should be updated to reflect the rename.
13064         */
13065        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13066        abstract int doPostInstall(int status, int uid);
13067
13068        /** @see PackageSettingBase#codePathString */
13069        abstract String getCodePath();
13070        /** @see PackageSettingBase#resourcePathString */
13071        abstract String getResourcePath();
13072
13073        // Need installer lock especially for dex file removal.
13074        abstract void cleanUpResourcesLI();
13075        abstract boolean doPostDeleteLI(boolean delete);
13076
13077        /**
13078         * Called before the source arguments are copied. This is used mostly
13079         * for MoveParams when it needs to read the source file to put it in the
13080         * destination.
13081         */
13082        int doPreCopy() {
13083            return PackageManager.INSTALL_SUCCEEDED;
13084        }
13085
13086        /**
13087         * Called after the source arguments are copied. This is used mostly for
13088         * MoveParams when it needs to read the source file to put it in the
13089         * destination.
13090         */
13091        int doPostCopy(int uid) {
13092            return PackageManager.INSTALL_SUCCEEDED;
13093        }
13094
13095        protected boolean isFwdLocked() {
13096            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13097        }
13098
13099        protected boolean isExternalAsec() {
13100            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13101        }
13102
13103        protected boolean isEphemeral() {
13104            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13105        }
13106
13107        UserHandle getUser() {
13108            return user;
13109        }
13110    }
13111
13112    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13113        if (!allCodePaths.isEmpty()) {
13114            if (instructionSets == null) {
13115                throw new IllegalStateException("instructionSet == null");
13116            }
13117            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13118            for (String codePath : allCodePaths) {
13119                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13120                    try {
13121                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13122                    } catch (InstallerException ignored) {
13123                    }
13124                }
13125            }
13126        }
13127    }
13128
13129    /**
13130     * Logic to handle installation of non-ASEC applications, including copying
13131     * and renaming logic.
13132     */
13133    class FileInstallArgs extends InstallArgs {
13134        private File codeFile;
13135        private File resourceFile;
13136
13137        // Example topology:
13138        // /data/app/com.example/base.apk
13139        // /data/app/com.example/split_foo.apk
13140        // /data/app/com.example/lib/arm/libfoo.so
13141        // /data/app/com.example/lib/arm64/libfoo.so
13142        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13143
13144        /** New install */
13145        FileInstallArgs(InstallParams params) {
13146            super(params.origin, params.move, params.observer, params.installFlags,
13147                    params.installerPackageName, params.volumeUuid,
13148                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13149                    params.grantedRuntimePermissions,
13150                    params.traceMethod, params.traceCookie, params.certificates);
13151            if (isFwdLocked()) {
13152                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13153            }
13154        }
13155
13156        /** Existing install */
13157        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13158            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13159                    null, null, null, 0, null /*certificates*/);
13160            this.codeFile = (codePath != null) ? new File(codePath) : null;
13161            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13162        }
13163
13164        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13165            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13166            try {
13167                return doCopyApk(imcs, temp);
13168            } finally {
13169                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13170            }
13171        }
13172
13173        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13174            if (origin.staged) {
13175                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13176                codeFile = origin.file;
13177                resourceFile = origin.file;
13178                return PackageManager.INSTALL_SUCCEEDED;
13179            }
13180
13181            try {
13182                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13183                final File tempDir =
13184                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13185                codeFile = tempDir;
13186                resourceFile = tempDir;
13187            } catch (IOException e) {
13188                Slog.w(TAG, "Failed to create copy file: " + e);
13189                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13190            }
13191
13192            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13193                @Override
13194                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13195                    if (!FileUtils.isValidExtFilename(name)) {
13196                        throw new IllegalArgumentException("Invalid filename: " + name);
13197                    }
13198                    try {
13199                        final File file = new File(codeFile, name);
13200                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13201                                O_RDWR | O_CREAT, 0644);
13202                        Os.chmod(file.getAbsolutePath(), 0644);
13203                        return new ParcelFileDescriptor(fd);
13204                    } catch (ErrnoException e) {
13205                        throw new RemoteException("Failed to open: " + e.getMessage());
13206                    }
13207                }
13208            };
13209
13210            int ret = PackageManager.INSTALL_SUCCEEDED;
13211            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13212            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13213                Slog.e(TAG, "Failed to copy package");
13214                return ret;
13215            }
13216
13217            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13218            NativeLibraryHelper.Handle handle = null;
13219            try {
13220                handle = NativeLibraryHelper.Handle.create(codeFile);
13221                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13222                        abiOverride);
13223            } catch (IOException e) {
13224                Slog.e(TAG, "Copying native libraries failed", e);
13225                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13226            } finally {
13227                IoUtils.closeQuietly(handle);
13228            }
13229
13230            return ret;
13231        }
13232
13233        int doPreInstall(int status) {
13234            if (status != PackageManager.INSTALL_SUCCEEDED) {
13235                cleanUp();
13236            }
13237            return status;
13238        }
13239
13240        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13241            if (status != PackageManager.INSTALL_SUCCEEDED) {
13242                cleanUp();
13243                return false;
13244            }
13245
13246            final File targetDir = codeFile.getParentFile();
13247            final File beforeCodeFile = codeFile;
13248            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13249
13250            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13251            try {
13252                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13253            } catch (ErrnoException e) {
13254                Slog.w(TAG, "Failed to rename", e);
13255                return false;
13256            }
13257
13258            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13259                Slog.w(TAG, "Failed to restorecon");
13260                return false;
13261            }
13262
13263            // Reflect the rename internally
13264            codeFile = afterCodeFile;
13265            resourceFile = afterCodeFile;
13266
13267            // Reflect the rename in scanned details
13268            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13269            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13270                    afterCodeFile, pkg.baseCodePath));
13271            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13272                    afterCodeFile, pkg.splitCodePaths));
13273
13274            // Reflect the rename in app info
13275            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13276            pkg.setApplicationInfoCodePath(pkg.codePath);
13277            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13278            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13279            pkg.setApplicationInfoResourcePath(pkg.codePath);
13280            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13281            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13282
13283            return true;
13284        }
13285
13286        int doPostInstall(int status, int uid) {
13287            if (status != PackageManager.INSTALL_SUCCEEDED) {
13288                cleanUp();
13289            }
13290            return status;
13291        }
13292
13293        @Override
13294        String getCodePath() {
13295            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13296        }
13297
13298        @Override
13299        String getResourcePath() {
13300            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13301        }
13302
13303        private boolean cleanUp() {
13304            if (codeFile == null || !codeFile.exists()) {
13305                return false;
13306            }
13307
13308            removeCodePathLI(codeFile);
13309
13310            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13311                resourceFile.delete();
13312            }
13313
13314            return true;
13315        }
13316
13317        void cleanUpResourcesLI() {
13318            // Try enumerating all code paths before deleting
13319            List<String> allCodePaths = Collections.EMPTY_LIST;
13320            if (codeFile != null && codeFile.exists()) {
13321                try {
13322                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13323                    allCodePaths = pkg.getAllCodePaths();
13324                } catch (PackageParserException e) {
13325                    // Ignored; we tried our best
13326                }
13327            }
13328
13329            cleanUp();
13330            removeDexFiles(allCodePaths, instructionSets);
13331        }
13332
13333        boolean doPostDeleteLI(boolean delete) {
13334            // XXX err, shouldn't we respect the delete flag?
13335            cleanUpResourcesLI();
13336            return true;
13337        }
13338    }
13339
13340    private boolean isAsecExternal(String cid) {
13341        final String asecPath = PackageHelper.getSdFilesystem(cid);
13342        return !asecPath.startsWith(mAsecInternalPath);
13343    }
13344
13345    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13346            PackageManagerException {
13347        if (copyRet < 0) {
13348            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13349                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13350                throw new PackageManagerException(copyRet, message);
13351            }
13352        }
13353    }
13354
13355    /**
13356     * Extract the MountService "container ID" from the full code path of an
13357     * .apk.
13358     */
13359    static String cidFromCodePath(String fullCodePath) {
13360        int eidx = fullCodePath.lastIndexOf("/");
13361        String subStr1 = fullCodePath.substring(0, eidx);
13362        int sidx = subStr1.lastIndexOf("/");
13363        return subStr1.substring(sidx+1, eidx);
13364    }
13365
13366    /**
13367     * Logic to handle installation of ASEC applications, including copying and
13368     * renaming logic.
13369     */
13370    class AsecInstallArgs extends InstallArgs {
13371        static final String RES_FILE_NAME = "pkg.apk";
13372        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13373
13374        String cid;
13375        String packagePath;
13376        String resourcePath;
13377
13378        /** New install */
13379        AsecInstallArgs(InstallParams params) {
13380            super(params.origin, params.move, params.observer, params.installFlags,
13381                    params.installerPackageName, params.volumeUuid,
13382                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13383                    params.grantedRuntimePermissions,
13384                    params.traceMethod, params.traceCookie, params.certificates);
13385        }
13386
13387        /** Existing install */
13388        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13389                        boolean isExternal, boolean isForwardLocked) {
13390            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13391              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13392                    instructionSets, null, null, null, 0, null /*certificates*/);
13393            // Hackily pretend we're still looking at a full code path
13394            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13395                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13396            }
13397
13398            // Extract cid from fullCodePath
13399            int eidx = fullCodePath.lastIndexOf("/");
13400            String subStr1 = fullCodePath.substring(0, eidx);
13401            int sidx = subStr1.lastIndexOf("/");
13402            cid = subStr1.substring(sidx+1, eidx);
13403            setMountPath(subStr1);
13404        }
13405
13406        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13407            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13408              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13409                    instructionSets, null, null, null, 0, null /*certificates*/);
13410            this.cid = cid;
13411            setMountPath(PackageHelper.getSdDir(cid));
13412        }
13413
13414        void createCopyFile() {
13415            cid = mInstallerService.allocateExternalStageCidLegacy();
13416        }
13417
13418        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13419            if (origin.staged && origin.cid != null) {
13420                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13421                cid = origin.cid;
13422                setMountPath(PackageHelper.getSdDir(cid));
13423                return PackageManager.INSTALL_SUCCEEDED;
13424            }
13425
13426            if (temp) {
13427                createCopyFile();
13428            } else {
13429                /*
13430                 * Pre-emptively destroy the container since it's destroyed if
13431                 * copying fails due to it existing anyway.
13432                 */
13433                PackageHelper.destroySdDir(cid);
13434            }
13435
13436            final String newMountPath = imcs.copyPackageToContainer(
13437                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13438                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13439
13440            if (newMountPath != null) {
13441                setMountPath(newMountPath);
13442                return PackageManager.INSTALL_SUCCEEDED;
13443            } else {
13444                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13445            }
13446        }
13447
13448        @Override
13449        String getCodePath() {
13450            return packagePath;
13451        }
13452
13453        @Override
13454        String getResourcePath() {
13455            return resourcePath;
13456        }
13457
13458        int doPreInstall(int status) {
13459            if (status != PackageManager.INSTALL_SUCCEEDED) {
13460                // Destroy container
13461                PackageHelper.destroySdDir(cid);
13462            } else {
13463                boolean mounted = PackageHelper.isContainerMounted(cid);
13464                if (!mounted) {
13465                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13466                            Process.SYSTEM_UID);
13467                    if (newMountPath != null) {
13468                        setMountPath(newMountPath);
13469                    } else {
13470                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13471                    }
13472                }
13473            }
13474            return status;
13475        }
13476
13477        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13478            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13479            String newMountPath = null;
13480            if (PackageHelper.isContainerMounted(cid)) {
13481                // Unmount the container
13482                if (!PackageHelper.unMountSdDir(cid)) {
13483                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13484                    return false;
13485                }
13486            }
13487            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13488                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13489                        " which might be stale. Will try to clean up.");
13490                // Clean up the stale container and proceed to recreate.
13491                if (!PackageHelper.destroySdDir(newCacheId)) {
13492                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13493                    return false;
13494                }
13495                // Successfully cleaned up stale container. Try to rename again.
13496                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13497                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13498                            + " inspite of cleaning it up.");
13499                    return false;
13500                }
13501            }
13502            if (!PackageHelper.isContainerMounted(newCacheId)) {
13503                Slog.w(TAG, "Mounting container " + newCacheId);
13504                newMountPath = PackageHelper.mountSdDir(newCacheId,
13505                        getEncryptKey(), Process.SYSTEM_UID);
13506            } else {
13507                newMountPath = PackageHelper.getSdDir(newCacheId);
13508            }
13509            if (newMountPath == null) {
13510                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13511                return false;
13512            }
13513            Log.i(TAG, "Succesfully renamed " + cid +
13514                    " to " + newCacheId +
13515                    " at new path: " + newMountPath);
13516            cid = newCacheId;
13517
13518            final File beforeCodeFile = new File(packagePath);
13519            setMountPath(newMountPath);
13520            final File afterCodeFile = new File(packagePath);
13521
13522            // Reflect the rename in scanned details
13523            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13524            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13525                    afterCodeFile, pkg.baseCodePath));
13526            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13527                    afterCodeFile, pkg.splitCodePaths));
13528
13529            // Reflect the rename in app info
13530            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13531            pkg.setApplicationInfoCodePath(pkg.codePath);
13532            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13533            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13534            pkg.setApplicationInfoResourcePath(pkg.codePath);
13535            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13536            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13537
13538            return true;
13539        }
13540
13541        private void setMountPath(String mountPath) {
13542            final File mountFile = new File(mountPath);
13543
13544            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13545            if (monolithicFile.exists()) {
13546                packagePath = monolithicFile.getAbsolutePath();
13547                if (isFwdLocked()) {
13548                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13549                } else {
13550                    resourcePath = packagePath;
13551                }
13552            } else {
13553                packagePath = mountFile.getAbsolutePath();
13554                resourcePath = packagePath;
13555            }
13556        }
13557
13558        int doPostInstall(int status, int uid) {
13559            if (status != PackageManager.INSTALL_SUCCEEDED) {
13560                cleanUp();
13561            } else {
13562                final int groupOwner;
13563                final String protectedFile;
13564                if (isFwdLocked()) {
13565                    groupOwner = UserHandle.getSharedAppGid(uid);
13566                    protectedFile = RES_FILE_NAME;
13567                } else {
13568                    groupOwner = -1;
13569                    protectedFile = null;
13570                }
13571
13572                if (uid < Process.FIRST_APPLICATION_UID
13573                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13574                    Slog.e(TAG, "Failed to finalize " + cid);
13575                    PackageHelper.destroySdDir(cid);
13576                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13577                }
13578
13579                boolean mounted = PackageHelper.isContainerMounted(cid);
13580                if (!mounted) {
13581                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13582                }
13583            }
13584            return status;
13585        }
13586
13587        private void cleanUp() {
13588            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13589
13590            // Destroy secure container
13591            PackageHelper.destroySdDir(cid);
13592        }
13593
13594        private List<String> getAllCodePaths() {
13595            final File codeFile = new File(getCodePath());
13596            if (codeFile != null && codeFile.exists()) {
13597                try {
13598                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13599                    return pkg.getAllCodePaths();
13600                } catch (PackageParserException e) {
13601                    // Ignored; we tried our best
13602                }
13603            }
13604            return Collections.EMPTY_LIST;
13605        }
13606
13607        void cleanUpResourcesLI() {
13608            // Enumerate all code paths before deleting
13609            cleanUpResourcesLI(getAllCodePaths());
13610        }
13611
13612        private void cleanUpResourcesLI(List<String> allCodePaths) {
13613            cleanUp();
13614            removeDexFiles(allCodePaths, instructionSets);
13615        }
13616
13617        String getPackageName() {
13618            return getAsecPackageName(cid);
13619        }
13620
13621        boolean doPostDeleteLI(boolean delete) {
13622            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13623            final List<String> allCodePaths = getAllCodePaths();
13624            boolean mounted = PackageHelper.isContainerMounted(cid);
13625            if (mounted) {
13626                // Unmount first
13627                if (PackageHelper.unMountSdDir(cid)) {
13628                    mounted = false;
13629                }
13630            }
13631            if (!mounted && delete) {
13632                cleanUpResourcesLI(allCodePaths);
13633            }
13634            return !mounted;
13635        }
13636
13637        @Override
13638        int doPreCopy() {
13639            if (isFwdLocked()) {
13640                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13641                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13642                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13643                }
13644            }
13645
13646            return PackageManager.INSTALL_SUCCEEDED;
13647        }
13648
13649        @Override
13650        int doPostCopy(int uid) {
13651            if (isFwdLocked()) {
13652                if (uid < Process.FIRST_APPLICATION_UID
13653                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13654                                RES_FILE_NAME)) {
13655                    Slog.e(TAG, "Failed to finalize " + cid);
13656                    PackageHelper.destroySdDir(cid);
13657                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13658                }
13659            }
13660
13661            return PackageManager.INSTALL_SUCCEEDED;
13662        }
13663    }
13664
13665    /**
13666     * Logic to handle movement of existing installed applications.
13667     */
13668    class MoveInstallArgs extends InstallArgs {
13669        private File codeFile;
13670        private File resourceFile;
13671
13672        /** New install */
13673        MoveInstallArgs(InstallParams params) {
13674            super(params.origin, params.move, params.observer, params.installFlags,
13675                    params.installerPackageName, params.volumeUuid,
13676                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13677                    params.grantedRuntimePermissions,
13678                    params.traceMethod, params.traceCookie, params.certificates);
13679        }
13680
13681        int copyApk(IMediaContainerService imcs, boolean temp) {
13682            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13683                    + move.fromUuid + " to " + move.toUuid);
13684            synchronized (mInstaller) {
13685                try {
13686                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13687                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13688                } catch (InstallerException e) {
13689                    Slog.w(TAG, "Failed to move app", e);
13690                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13691                }
13692            }
13693
13694            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13695            resourceFile = codeFile;
13696            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13697
13698            return PackageManager.INSTALL_SUCCEEDED;
13699        }
13700
13701        int doPreInstall(int status) {
13702            if (status != PackageManager.INSTALL_SUCCEEDED) {
13703                cleanUp(move.toUuid);
13704            }
13705            return status;
13706        }
13707
13708        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13709            if (status != PackageManager.INSTALL_SUCCEEDED) {
13710                cleanUp(move.toUuid);
13711                return false;
13712            }
13713
13714            // Reflect the move in app info
13715            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13716            pkg.setApplicationInfoCodePath(pkg.codePath);
13717            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13718            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13719            pkg.setApplicationInfoResourcePath(pkg.codePath);
13720            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13721            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13722
13723            return true;
13724        }
13725
13726        int doPostInstall(int status, int uid) {
13727            if (status == PackageManager.INSTALL_SUCCEEDED) {
13728                cleanUp(move.fromUuid);
13729            } else {
13730                cleanUp(move.toUuid);
13731            }
13732            return status;
13733        }
13734
13735        @Override
13736        String getCodePath() {
13737            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13738        }
13739
13740        @Override
13741        String getResourcePath() {
13742            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13743        }
13744
13745        private boolean cleanUp(String volumeUuid) {
13746            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13747                    move.dataAppName);
13748            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13749            final int[] userIds = sUserManager.getUserIds();
13750            synchronized (mInstallLock) {
13751                // Clean up both app data and code
13752                // All package moves are frozen until finished
13753                for (int userId : userIds) {
13754                    try {
13755                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13756                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13757                    } catch (InstallerException e) {
13758                        Slog.w(TAG, String.valueOf(e));
13759                    }
13760                }
13761                removeCodePathLI(codeFile);
13762            }
13763            return true;
13764        }
13765
13766        void cleanUpResourcesLI() {
13767            throw new UnsupportedOperationException();
13768        }
13769
13770        boolean doPostDeleteLI(boolean delete) {
13771            throw new UnsupportedOperationException();
13772        }
13773    }
13774
13775    static String getAsecPackageName(String packageCid) {
13776        int idx = packageCid.lastIndexOf("-");
13777        if (idx == -1) {
13778            return packageCid;
13779        }
13780        return packageCid.substring(0, idx);
13781    }
13782
13783    // Utility method used to create code paths based on package name and available index.
13784    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13785        String idxStr = "";
13786        int idx = 1;
13787        // Fall back to default value of idx=1 if prefix is not
13788        // part of oldCodePath
13789        if (oldCodePath != null) {
13790            String subStr = oldCodePath;
13791            // Drop the suffix right away
13792            if (suffix != null && subStr.endsWith(suffix)) {
13793                subStr = subStr.substring(0, subStr.length() - suffix.length());
13794            }
13795            // If oldCodePath already contains prefix find out the
13796            // ending index to either increment or decrement.
13797            int sidx = subStr.lastIndexOf(prefix);
13798            if (sidx != -1) {
13799                subStr = subStr.substring(sidx + prefix.length());
13800                if (subStr != null) {
13801                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13802                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13803                    }
13804                    try {
13805                        idx = Integer.parseInt(subStr);
13806                        if (idx <= 1) {
13807                            idx++;
13808                        } else {
13809                            idx--;
13810                        }
13811                    } catch(NumberFormatException e) {
13812                    }
13813                }
13814            }
13815        }
13816        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13817        return prefix + idxStr;
13818    }
13819
13820    private File getNextCodePath(File targetDir, String packageName) {
13821        int suffix = 1;
13822        File result;
13823        do {
13824            result = new File(targetDir, packageName + "-" + suffix);
13825            suffix++;
13826        } while (result.exists());
13827        return result;
13828    }
13829
13830    // Utility method that returns the relative package path with respect
13831    // to the installation directory. Like say for /data/data/com.test-1.apk
13832    // string com.test-1 is returned.
13833    static String deriveCodePathName(String codePath) {
13834        if (codePath == null) {
13835            return null;
13836        }
13837        final File codeFile = new File(codePath);
13838        final String name = codeFile.getName();
13839        if (codeFile.isDirectory()) {
13840            return name;
13841        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13842            final int lastDot = name.lastIndexOf('.');
13843            return name.substring(0, lastDot);
13844        } else {
13845            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13846            return null;
13847        }
13848    }
13849
13850    static class PackageInstalledInfo {
13851        String name;
13852        int uid;
13853        // The set of users that originally had this package installed.
13854        int[] origUsers;
13855        // The set of users that now have this package installed.
13856        int[] newUsers;
13857        PackageParser.Package pkg;
13858        int returnCode;
13859        String returnMsg;
13860        PackageRemovedInfo removedInfo;
13861        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13862
13863        public void setError(int code, String msg) {
13864            setReturnCode(code);
13865            setReturnMessage(msg);
13866            Slog.w(TAG, msg);
13867        }
13868
13869        public void setError(String msg, PackageParserException e) {
13870            setReturnCode(e.error);
13871            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13872            Slog.w(TAG, msg, e);
13873        }
13874
13875        public void setError(String msg, PackageManagerException e) {
13876            returnCode = e.error;
13877            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13878            Slog.w(TAG, msg, e);
13879        }
13880
13881        public void setReturnCode(int returnCode) {
13882            this.returnCode = returnCode;
13883            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13884            for (int i = 0; i < childCount; i++) {
13885                addedChildPackages.valueAt(i).returnCode = returnCode;
13886            }
13887        }
13888
13889        private void setReturnMessage(String returnMsg) {
13890            this.returnMsg = returnMsg;
13891            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13892            for (int i = 0; i < childCount; i++) {
13893                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13894            }
13895        }
13896
13897        // In some error cases we want to convey more info back to the observer
13898        String origPackage;
13899        String origPermission;
13900    }
13901
13902    /*
13903     * Install a non-existing package.
13904     */
13905    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13906            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13907            PackageInstalledInfo res) {
13908        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13909
13910        // Remember this for later, in case we need to rollback this install
13911        String pkgName = pkg.packageName;
13912
13913        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13914
13915        synchronized(mPackages) {
13916            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13917                // A package with the same name is already installed, though
13918                // it has been renamed to an older name.  The package we
13919                // are trying to install should be installed as an update to
13920                // the existing one, but that has not been requested, so bail.
13921                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13922                        + " without first uninstalling package running as "
13923                        + mSettings.mRenamedPackages.get(pkgName));
13924                return;
13925            }
13926            if (mPackages.containsKey(pkgName)) {
13927                // Don't allow installation over an existing package with the same name.
13928                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13929                        + " without first uninstalling.");
13930                return;
13931            }
13932        }
13933
13934        try {
13935            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13936                    System.currentTimeMillis(), user);
13937
13938            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13939
13940            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13941                prepareAppDataAfterInstallLIF(newPackage);
13942
13943            } else {
13944                // Remove package from internal structures, but keep around any
13945                // data that might have already existed
13946                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13947                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13948            }
13949        } catch (PackageManagerException e) {
13950            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13951        }
13952
13953        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13954    }
13955
13956    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13957        // Can't rotate keys during boot or if sharedUser.
13958        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13959                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13960            return false;
13961        }
13962        // app is using upgradeKeySets; make sure all are valid
13963        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13964        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13965        for (int i = 0; i < upgradeKeySets.length; i++) {
13966            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13967                Slog.wtf(TAG, "Package "
13968                         + (oldPs.name != null ? oldPs.name : "<null>")
13969                         + " contains upgrade-key-set reference to unknown key-set: "
13970                         + upgradeKeySets[i]
13971                         + " reverting to signatures check.");
13972                return false;
13973            }
13974        }
13975        return true;
13976    }
13977
13978    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13979        // Upgrade keysets are being used.  Determine if new package has a superset of the
13980        // required keys.
13981        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13982        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13983        for (int i = 0; i < upgradeKeySets.length; i++) {
13984            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13985            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13986                return true;
13987            }
13988        }
13989        return false;
13990    }
13991
13992    private static void updateDigest(MessageDigest digest, File file) throws IOException {
13993        try (DigestInputStream digestStream =
13994                new DigestInputStream(new FileInputStream(file), digest)) {
13995            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
13996        }
13997    }
13998
13999    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14000            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14001        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14002
14003        final PackageParser.Package oldPackage;
14004        final String pkgName = pkg.packageName;
14005        final int[] allUsers;
14006        final int[] installedUsers;
14007
14008        synchronized(mPackages) {
14009            oldPackage = mPackages.get(pkgName);
14010            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14011
14012            // don't allow upgrade to target a release SDK from a pre-release SDK
14013            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14014                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14015            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14016                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14017            if (oldTargetsPreRelease
14018                    && !newTargetsPreRelease
14019                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14020                Slog.w(TAG, "Can't install package targeting released sdk");
14021                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14022                return;
14023            }
14024
14025            // don't allow an upgrade from full to ephemeral
14026            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14027            if (isEphemeral && !oldIsEphemeral) {
14028                // can't downgrade from full to ephemeral
14029                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14030                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14031                return;
14032            }
14033
14034            // verify signatures are valid
14035            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14036            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14037                if (!checkUpgradeKeySetLP(ps, pkg)) {
14038                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14039                            "New package not signed by keys specified by upgrade-keysets: "
14040                                    + pkgName);
14041                    return;
14042                }
14043            } else {
14044                // default to original signature matching
14045                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14046                        != PackageManager.SIGNATURE_MATCH) {
14047                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14048                            "New package has a different signature: " + pkgName);
14049                    return;
14050                }
14051            }
14052
14053            // don't allow a system upgrade unless the upgrade hash matches
14054            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14055                byte[] digestBytes = null;
14056                try {
14057                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14058                    updateDigest(digest, new File(pkg.baseCodePath));
14059                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14060                        for (String path : pkg.splitCodePaths) {
14061                            updateDigest(digest, new File(path));
14062                        }
14063                    }
14064                    digestBytes = digest.digest();
14065                } catch (NoSuchAlgorithmException | IOException e) {
14066                    res.setError(INSTALL_FAILED_INVALID_APK,
14067                            "Could not compute hash: " + pkgName);
14068                    return;
14069                }
14070                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14071                    res.setError(INSTALL_FAILED_INVALID_APK,
14072                            "New package fails restrict-update check: " + pkgName);
14073                    return;
14074                }
14075                // retain upgrade restriction
14076                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14077            }
14078
14079            // Check for shared user id changes
14080            String invalidPackageName =
14081                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14082            if (invalidPackageName != null) {
14083                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14084                        "Package " + invalidPackageName + " tried to change user "
14085                                + oldPackage.mSharedUserId);
14086                return;
14087            }
14088
14089            // In case of rollback, remember per-user/profile install state
14090            allUsers = sUserManager.getUserIds();
14091            installedUsers = ps.queryInstalledUsers(allUsers, true);
14092        }
14093
14094        // Update what is removed
14095        res.removedInfo = new PackageRemovedInfo();
14096        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14097        res.removedInfo.removedPackage = oldPackage.packageName;
14098        res.removedInfo.isUpdate = true;
14099        res.removedInfo.origUsers = installedUsers;
14100        final int childCount = (oldPackage.childPackages != null)
14101                ? oldPackage.childPackages.size() : 0;
14102        for (int i = 0; i < childCount; i++) {
14103            boolean childPackageUpdated = false;
14104            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14105            if (res.addedChildPackages != null) {
14106                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14107                if (childRes != null) {
14108                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14109                    childRes.removedInfo.removedPackage = childPkg.packageName;
14110                    childRes.removedInfo.isUpdate = true;
14111                    childPackageUpdated = true;
14112                }
14113            }
14114            if (!childPackageUpdated) {
14115                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14116                childRemovedRes.removedPackage = childPkg.packageName;
14117                childRemovedRes.isUpdate = false;
14118                childRemovedRes.dataRemoved = true;
14119                synchronized (mPackages) {
14120                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14121                    if (childPs != null) {
14122                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14123                    }
14124                }
14125                if (res.removedInfo.removedChildPackages == null) {
14126                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14127                }
14128                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14129            }
14130        }
14131
14132        boolean sysPkg = (isSystemApp(oldPackage));
14133        if (sysPkg) {
14134            // Set the system/privileged flags as needed
14135            final boolean privileged =
14136                    (oldPackage.applicationInfo.privateFlags
14137                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14138            final int systemPolicyFlags = policyFlags
14139                    | PackageParser.PARSE_IS_SYSTEM
14140                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14141
14142            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14143                    user, allUsers, installerPackageName, res);
14144        } else {
14145            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14146                    user, allUsers, installerPackageName, res);
14147        }
14148    }
14149
14150    public List<String> getPreviousCodePaths(String packageName) {
14151        final PackageSetting ps = mSettings.mPackages.get(packageName);
14152        final List<String> result = new ArrayList<String>();
14153        if (ps != null && ps.oldCodePaths != null) {
14154            result.addAll(ps.oldCodePaths);
14155        }
14156        return result;
14157    }
14158
14159    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14160            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14161            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14162        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14163                + deletedPackage);
14164
14165        String pkgName = deletedPackage.packageName;
14166        boolean deletedPkg = true;
14167        boolean addedPkg = false;
14168        boolean updatedSettings = false;
14169        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14170        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14171                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14172
14173        final long origUpdateTime = (pkg.mExtras != null)
14174                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14175
14176        // First delete the existing package while retaining the data directory
14177        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14178                res.removedInfo, true, pkg)) {
14179            // If the existing package wasn't successfully deleted
14180            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14181            deletedPkg = false;
14182        } else {
14183            // Successfully deleted the old package; proceed with replace.
14184
14185            // If deleted package lived in a container, give users a chance to
14186            // relinquish resources before killing.
14187            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14188                if (DEBUG_INSTALL) {
14189                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14190                }
14191                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14192                final ArrayList<String> pkgList = new ArrayList<String>(1);
14193                pkgList.add(deletedPackage.applicationInfo.packageName);
14194                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14195            }
14196
14197            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14198                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14199            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14200
14201            try {
14202                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14203                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14204                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14205
14206                // Update the in-memory copy of the previous code paths.
14207                PackageSetting ps = mSettings.mPackages.get(pkgName);
14208                if (!killApp) {
14209                    if (ps.oldCodePaths == null) {
14210                        ps.oldCodePaths = new ArraySet<>();
14211                    }
14212                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14213                    if (deletedPackage.splitCodePaths != null) {
14214                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14215                    }
14216                } else {
14217                    ps.oldCodePaths = null;
14218                }
14219                if (ps.childPackageNames != null) {
14220                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14221                        final String childPkgName = ps.childPackageNames.get(i);
14222                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14223                        childPs.oldCodePaths = ps.oldCodePaths;
14224                    }
14225                }
14226                prepareAppDataAfterInstallLIF(newPackage);
14227                addedPkg = true;
14228            } catch (PackageManagerException e) {
14229                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14230            }
14231        }
14232
14233        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14234            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14235
14236            // Revert all internal state mutations and added folders for the failed install
14237            if (addedPkg) {
14238                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14239                        res.removedInfo, true, null);
14240            }
14241
14242            // Restore the old package
14243            if (deletedPkg) {
14244                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14245                File restoreFile = new File(deletedPackage.codePath);
14246                // Parse old package
14247                boolean oldExternal = isExternal(deletedPackage);
14248                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14249                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14250                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14251                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14252                try {
14253                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14254                            null);
14255                } catch (PackageManagerException e) {
14256                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14257                            + e.getMessage());
14258                    return;
14259                }
14260
14261                synchronized (mPackages) {
14262                    // Ensure the installer package name up to date
14263                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14264
14265                    // Update permissions for restored package
14266                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14267
14268                    mSettings.writeLPr();
14269                }
14270
14271                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14272            }
14273        } else {
14274            synchronized (mPackages) {
14275                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14276                if (ps != null) {
14277                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14278                    if (res.removedInfo.removedChildPackages != null) {
14279                        final int childCount = res.removedInfo.removedChildPackages.size();
14280                        // Iterate in reverse as we may modify the collection
14281                        for (int i = childCount - 1; i >= 0; i--) {
14282                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14283                            if (res.addedChildPackages.containsKey(childPackageName)) {
14284                                res.removedInfo.removedChildPackages.removeAt(i);
14285                            } else {
14286                                PackageRemovedInfo childInfo = res.removedInfo
14287                                        .removedChildPackages.valueAt(i);
14288                                childInfo.removedForAllUsers = mPackages.get(
14289                                        childInfo.removedPackage) == null;
14290                            }
14291                        }
14292                    }
14293                }
14294            }
14295        }
14296    }
14297
14298    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14299            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14300            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14301        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14302                + ", old=" + deletedPackage);
14303
14304        final boolean disabledSystem;
14305
14306        // Remove existing system package
14307        removePackageLI(deletedPackage, true);
14308
14309        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14310        if (!disabledSystem) {
14311            // We didn't need to disable the .apk as a current system package,
14312            // which means we are replacing another update that is already
14313            // installed.  We need to make sure to delete the older one's .apk.
14314            res.removedInfo.args = createInstallArgsForExisting(0,
14315                    deletedPackage.applicationInfo.getCodePath(),
14316                    deletedPackage.applicationInfo.getResourcePath(),
14317                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14318        } else {
14319            res.removedInfo.args = null;
14320        }
14321
14322        // Successfully disabled the old package. Now proceed with re-installation
14323        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14324                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14325        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14326
14327        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14328        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14329                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14330
14331        PackageParser.Package newPackage = null;
14332        try {
14333            // Add the package to the internal data structures
14334            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14335
14336            // Set the update and install times
14337            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14338            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14339                    System.currentTimeMillis());
14340
14341            // Update the package dynamic state if succeeded
14342            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14343                // Now that the install succeeded make sure we remove data
14344                // directories for any child package the update removed.
14345                final int deletedChildCount = (deletedPackage.childPackages != null)
14346                        ? deletedPackage.childPackages.size() : 0;
14347                final int newChildCount = (newPackage.childPackages != null)
14348                        ? newPackage.childPackages.size() : 0;
14349                for (int i = 0; i < deletedChildCount; i++) {
14350                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14351                    boolean childPackageDeleted = true;
14352                    for (int j = 0; j < newChildCount; j++) {
14353                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14354                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14355                            childPackageDeleted = false;
14356                            break;
14357                        }
14358                    }
14359                    if (childPackageDeleted) {
14360                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14361                                deletedChildPkg.packageName);
14362                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14363                            PackageRemovedInfo removedChildRes = res.removedInfo
14364                                    .removedChildPackages.get(deletedChildPkg.packageName);
14365                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14366                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14367                        }
14368                    }
14369                }
14370
14371                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14372                prepareAppDataAfterInstallLIF(newPackage);
14373            }
14374        } catch (PackageManagerException e) {
14375            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14376            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14377        }
14378
14379        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14380            // Re installation failed. Restore old information
14381            // Remove new pkg information
14382            if (newPackage != null) {
14383                removeInstalledPackageLI(newPackage, true);
14384            }
14385            // Add back the old system package
14386            try {
14387                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14388            } catch (PackageManagerException e) {
14389                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14390            }
14391
14392            synchronized (mPackages) {
14393                if (disabledSystem) {
14394                    enableSystemPackageLPw(deletedPackage);
14395                }
14396
14397                // Ensure the installer package name up to date
14398                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14399
14400                // Update permissions for restored package
14401                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14402
14403                mSettings.writeLPr();
14404            }
14405
14406            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14407                    + " after failed upgrade");
14408        }
14409    }
14410
14411    /**
14412     * Checks whether the parent or any of the child packages have a change shared
14413     * user. For a package to be a valid update the shred users of the parent and
14414     * the children should match. We may later support changing child shared users.
14415     * @param oldPkg The updated package.
14416     * @param newPkg The update package.
14417     * @return The shared user that change between the versions.
14418     */
14419    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14420            PackageParser.Package newPkg) {
14421        // Check parent shared user
14422        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14423            return newPkg.packageName;
14424        }
14425        // Check child shared users
14426        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14427        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14428        for (int i = 0; i < newChildCount; i++) {
14429            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14430            // If this child was present, did it have the same shared user?
14431            for (int j = 0; j < oldChildCount; j++) {
14432                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14433                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14434                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14435                    return newChildPkg.packageName;
14436                }
14437            }
14438        }
14439        return null;
14440    }
14441
14442    private void removeNativeBinariesLI(PackageSetting ps) {
14443        // Remove the lib path for the parent package
14444        if (ps != null) {
14445            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14446            // Remove the lib path for the child packages
14447            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14448            for (int i = 0; i < childCount; i++) {
14449                PackageSetting childPs = null;
14450                synchronized (mPackages) {
14451                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14452                }
14453                if (childPs != null) {
14454                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14455                            .legacyNativeLibraryPathString);
14456                }
14457            }
14458        }
14459    }
14460
14461    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14462        // Enable the parent package
14463        mSettings.enableSystemPackageLPw(pkg.packageName);
14464        // Enable the child packages
14465        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14466        for (int i = 0; i < childCount; i++) {
14467            PackageParser.Package childPkg = pkg.childPackages.get(i);
14468            mSettings.enableSystemPackageLPw(childPkg.packageName);
14469        }
14470    }
14471
14472    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14473            PackageParser.Package newPkg) {
14474        // Disable the parent package (parent always replaced)
14475        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14476        // Disable the child packages
14477        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14478        for (int i = 0; i < childCount; i++) {
14479            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14480            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14481            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14482        }
14483        return disabled;
14484    }
14485
14486    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14487            String installerPackageName) {
14488        // Enable the parent package
14489        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14490        // Enable the child packages
14491        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14492        for (int i = 0; i < childCount; i++) {
14493            PackageParser.Package childPkg = pkg.childPackages.get(i);
14494            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14495        }
14496    }
14497
14498    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14499        // Collect all used permissions in the UID
14500        ArraySet<String> usedPermissions = new ArraySet<>();
14501        final int packageCount = su.packages.size();
14502        for (int i = 0; i < packageCount; i++) {
14503            PackageSetting ps = su.packages.valueAt(i);
14504            if (ps.pkg == null) {
14505                continue;
14506            }
14507            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14508            for (int j = 0; j < requestedPermCount; j++) {
14509                String permission = ps.pkg.requestedPermissions.get(j);
14510                BasePermission bp = mSettings.mPermissions.get(permission);
14511                if (bp != null) {
14512                    usedPermissions.add(permission);
14513                }
14514            }
14515        }
14516
14517        PermissionsState permissionsState = su.getPermissionsState();
14518        // Prune install permissions
14519        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14520        final int installPermCount = installPermStates.size();
14521        for (int i = installPermCount - 1; i >= 0;  i--) {
14522            PermissionState permissionState = installPermStates.get(i);
14523            if (!usedPermissions.contains(permissionState.getName())) {
14524                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14525                if (bp != null) {
14526                    permissionsState.revokeInstallPermission(bp);
14527                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14528                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14529                }
14530            }
14531        }
14532
14533        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14534
14535        // Prune runtime permissions
14536        for (int userId : allUserIds) {
14537            List<PermissionState> runtimePermStates = permissionsState
14538                    .getRuntimePermissionStates(userId);
14539            final int runtimePermCount = runtimePermStates.size();
14540            for (int i = runtimePermCount - 1; i >= 0; i--) {
14541                PermissionState permissionState = runtimePermStates.get(i);
14542                if (!usedPermissions.contains(permissionState.getName())) {
14543                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14544                    if (bp != null) {
14545                        permissionsState.revokeRuntimePermission(bp, userId);
14546                        permissionsState.updatePermissionFlags(bp, userId,
14547                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14548                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14549                                runtimePermissionChangedUserIds, userId);
14550                    }
14551                }
14552            }
14553        }
14554
14555        return runtimePermissionChangedUserIds;
14556    }
14557
14558    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14559            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14560        // Update the parent package setting
14561        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14562                res, user);
14563        // Update the child packages setting
14564        final int childCount = (newPackage.childPackages != null)
14565                ? newPackage.childPackages.size() : 0;
14566        for (int i = 0; i < childCount; i++) {
14567            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14568            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14569            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14570                    childRes.origUsers, childRes, user);
14571        }
14572    }
14573
14574    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14575            String installerPackageName, int[] allUsers, int[] installedForUsers,
14576            PackageInstalledInfo res, UserHandle user) {
14577        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14578
14579        String pkgName = newPackage.packageName;
14580        synchronized (mPackages) {
14581            //write settings. the installStatus will be incomplete at this stage.
14582            //note that the new package setting would have already been
14583            //added to mPackages. It hasn't been persisted yet.
14584            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14585            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14586            mSettings.writeLPr();
14587            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14588        }
14589
14590        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14591        synchronized (mPackages) {
14592            updatePermissionsLPw(newPackage.packageName, newPackage,
14593                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14594                            ? UPDATE_PERMISSIONS_ALL : 0));
14595            // For system-bundled packages, we assume that installing an upgraded version
14596            // of the package implies that the user actually wants to run that new code,
14597            // so we enable the package.
14598            PackageSetting ps = mSettings.mPackages.get(pkgName);
14599            final int userId = user.getIdentifier();
14600            if (ps != null) {
14601                if (isSystemApp(newPackage)) {
14602                    if (DEBUG_INSTALL) {
14603                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14604                    }
14605                    // Enable system package for requested users
14606                    if (res.origUsers != null) {
14607                        for (int origUserId : res.origUsers) {
14608                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14609                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14610                                        origUserId, installerPackageName);
14611                            }
14612                        }
14613                    }
14614                    // Also convey the prior install/uninstall state
14615                    if (allUsers != null && installedForUsers != null) {
14616                        for (int currentUserId : allUsers) {
14617                            final boolean installed = ArrayUtils.contains(
14618                                    installedForUsers, currentUserId);
14619                            if (DEBUG_INSTALL) {
14620                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14621                            }
14622                            ps.setInstalled(installed, currentUserId);
14623                        }
14624                        // these install state changes will be persisted in the
14625                        // upcoming call to mSettings.writeLPr().
14626                    }
14627                }
14628                // It's implied that when a user requests installation, they want the app to be
14629                // installed and enabled.
14630                if (userId != UserHandle.USER_ALL) {
14631                    ps.setInstalled(true, userId);
14632                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14633                }
14634            }
14635            res.name = pkgName;
14636            res.uid = newPackage.applicationInfo.uid;
14637            res.pkg = newPackage;
14638            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14639            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14640            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14641            //to update install status
14642            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14643            mSettings.writeLPr();
14644            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14645        }
14646
14647        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14648    }
14649
14650    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14651        try {
14652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14653            installPackageLI(args, res);
14654        } finally {
14655            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14656        }
14657    }
14658
14659    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14660        final int installFlags = args.installFlags;
14661        final String installerPackageName = args.installerPackageName;
14662        final String volumeUuid = args.volumeUuid;
14663        final File tmpPackageFile = new File(args.getCodePath());
14664        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14665        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14666                || (args.volumeUuid != null));
14667        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14668        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14669        boolean replace = false;
14670        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14671        if (args.move != null) {
14672            // moving a complete application; perform an initial scan on the new install location
14673            scanFlags |= SCAN_INITIAL;
14674        }
14675        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14676            scanFlags |= SCAN_DONT_KILL_APP;
14677        }
14678
14679        // Result object to be returned
14680        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14681
14682        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14683
14684        // Sanity check
14685        if (ephemeral && (forwardLocked || onExternal)) {
14686            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14687                    + " external=" + onExternal);
14688            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14689            return;
14690        }
14691
14692        // Retrieve PackageSettings and parse package
14693        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14694                | PackageParser.PARSE_ENFORCE_CODE
14695                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14696                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14697                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14698                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14699        PackageParser pp = new PackageParser();
14700        pp.setSeparateProcesses(mSeparateProcesses);
14701        pp.setDisplayMetrics(mMetrics);
14702
14703        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14704        final PackageParser.Package pkg;
14705        try {
14706            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14707        } catch (PackageParserException e) {
14708            res.setError("Failed parse during installPackageLI", e);
14709            return;
14710        } finally {
14711            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14712        }
14713
14714        // If we are installing a clustered package add results for the children
14715        if (pkg.childPackages != null) {
14716            synchronized (mPackages) {
14717                final int childCount = pkg.childPackages.size();
14718                for (int i = 0; i < childCount; i++) {
14719                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14720                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14721                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14722                    childRes.pkg = childPkg;
14723                    childRes.name = childPkg.packageName;
14724                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14725                    if (childPs != null) {
14726                        childRes.origUsers = childPs.queryInstalledUsers(
14727                                sUserManager.getUserIds(), true);
14728                    }
14729                    if ((mPackages.containsKey(childPkg.packageName))) {
14730                        childRes.removedInfo = new PackageRemovedInfo();
14731                        childRes.removedInfo.removedPackage = childPkg.packageName;
14732                    }
14733                    if (res.addedChildPackages == null) {
14734                        res.addedChildPackages = new ArrayMap<>();
14735                    }
14736                    res.addedChildPackages.put(childPkg.packageName, childRes);
14737                }
14738            }
14739        }
14740
14741        // If package doesn't declare API override, mark that we have an install
14742        // time CPU ABI override.
14743        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14744            pkg.cpuAbiOverride = args.abiOverride;
14745        }
14746
14747        String pkgName = res.name = pkg.packageName;
14748        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14749            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14750                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14751                return;
14752            }
14753        }
14754
14755        try {
14756            // either use what we've been given or parse directly from the APK
14757            if (args.certificates != null) {
14758                try {
14759                    PackageParser.populateCertificates(pkg, args.certificates);
14760                } catch (PackageParserException e) {
14761                    // there was something wrong with the certificates we were given;
14762                    // try to pull them from the APK
14763                    PackageParser.collectCertificates(pkg, parseFlags);
14764                }
14765            } else {
14766                PackageParser.collectCertificates(pkg, parseFlags);
14767            }
14768        } catch (PackageParserException e) {
14769            res.setError("Failed collect during installPackageLI", e);
14770            return;
14771        }
14772
14773        // Get rid of all references to package scan path via parser.
14774        pp = null;
14775        String oldCodePath = null;
14776        boolean systemApp = false;
14777        synchronized (mPackages) {
14778            // Check if installing already existing package
14779            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14780                String oldName = mSettings.mRenamedPackages.get(pkgName);
14781                if (pkg.mOriginalPackages != null
14782                        && pkg.mOriginalPackages.contains(oldName)
14783                        && mPackages.containsKey(oldName)) {
14784                    // This package is derived from an original package,
14785                    // and this device has been updating from that original
14786                    // name.  We must continue using the original name, so
14787                    // rename the new package here.
14788                    pkg.setPackageName(oldName);
14789                    pkgName = pkg.packageName;
14790                    replace = true;
14791                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14792                            + oldName + " pkgName=" + pkgName);
14793                } else if (mPackages.containsKey(pkgName)) {
14794                    // This package, under its official name, already exists
14795                    // on the device; we should replace it.
14796                    replace = true;
14797                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14798                }
14799
14800                // Child packages are installed through the parent package
14801                if (pkg.parentPackage != null) {
14802                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14803                            "Package " + pkg.packageName + " is child of package "
14804                                    + pkg.parentPackage.parentPackage + ". Child packages "
14805                                    + "can be updated only through the parent package.");
14806                    return;
14807                }
14808
14809                if (replace) {
14810                    // Prevent apps opting out from runtime permissions
14811                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14812                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14813                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14814                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14815                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14816                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14817                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14818                                        + " doesn't support runtime permissions but the old"
14819                                        + " target SDK " + oldTargetSdk + " does.");
14820                        return;
14821                    }
14822
14823                    // Prevent installing of child packages
14824                    if (oldPackage.parentPackage != null) {
14825                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14826                                "Package " + pkg.packageName + " is child of package "
14827                                        + oldPackage.parentPackage + ". Child packages "
14828                                        + "can be updated only through the parent package.");
14829                        return;
14830                    }
14831                }
14832            }
14833
14834            PackageSetting ps = mSettings.mPackages.get(pkgName);
14835            if (ps != null) {
14836                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14837
14838                // Quick sanity check that we're signed correctly if updating;
14839                // we'll check this again later when scanning, but we want to
14840                // bail early here before tripping over redefined permissions.
14841                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14842                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14843                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14844                                + pkg.packageName + " upgrade keys do not match the "
14845                                + "previously installed version");
14846                        return;
14847                    }
14848                } else {
14849                    try {
14850                        verifySignaturesLP(ps, pkg);
14851                    } catch (PackageManagerException e) {
14852                        res.setError(e.error, e.getMessage());
14853                        return;
14854                    }
14855                }
14856
14857                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14858                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14859                    systemApp = (ps.pkg.applicationInfo.flags &
14860                            ApplicationInfo.FLAG_SYSTEM) != 0;
14861                }
14862                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14863            }
14864
14865            // Check whether the newly-scanned package wants to define an already-defined perm
14866            int N = pkg.permissions.size();
14867            for (int i = N-1; i >= 0; i--) {
14868                PackageParser.Permission perm = pkg.permissions.get(i);
14869                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14870                if (bp != null) {
14871                    // If the defining package is signed with our cert, it's okay.  This
14872                    // also includes the "updating the same package" case, of course.
14873                    // "updating same package" could also involve key-rotation.
14874                    final boolean sigsOk;
14875                    if (bp.sourcePackage.equals(pkg.packageName)
14876                            && (bp.packageSetting instanceof PackageSetting)
14877                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14878                                    scanFlags))) {
14879                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14880                    } else {
14881                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14882                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14883                    }
14884                    if (!sigsOk) {
14885                        // If the owning package is the system itself, we log but allow
14886                        // install to proceed; we fail the install on all other permission
14887                        // redefinitions.
14888                        if (!bp.sourcePackage.equals("android")) {
14889                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14890                                    + pkg.packageName + " attempting to redeclare permission "
14891                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14892                            res.origPermission = perm.info.name;
14893                            res.origPackage = bp.sourcePackage;
14894                            return;
14895                        } else {
14896                            Slog.w(TAG, "Package " + pkg.packageName
14897                                    + " attempting to redeclare system permission "
14898                                    + perm.info.name + "; ignoring new declaration");
14899                            pkg.permissions.remove(i);
14900                        }
14901                    }
14902                }
14903            }
14904        }
14905
14906        if (systemApp) {
14907            if (onExternal) {
14908                // Abort update; system app can't be replaced with app on sdcard
14909                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14910                        "Cannot install updates to system apps on sdcard");
14911                return;
14912            } else if (ephemeral) {
14913                // Abort update; system app can't be replaced with an ephemeral app
14914                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14915                        "Cannot update a system app with an ephemeral app");
14916                return;
14917            }
14918        }
14919
14920        if (args.move != null) {
14921            // We did an in-place move, so dex is ready to roll
14922            scanFlags |= SCAN_NO_DEX;
14923            scanFlags |= SCAN_MOVE;
14924
14925            synchronized (mPackages) {
14926                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14927                if (ps == null) {
14928                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14929                            "Missing settings for moved package " + pkgName);
14930                }
14931
14932                // We moved the entire application as-is, so bring over the
14933                // previously derived ABI information.
14934                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14935                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14936            }
14937
14938        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14939            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14940            scanFlags |= SCAN_NO_DEX;
14941
14942            try {
14943                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14944                    args.abiOverride : pkg.cpuAbiOverride);
14945                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14946                        true /* extract libs */);
14947            } catch (PackageManagerException pme) {
14948                Slog.e(TAG, "Error deriving application ABI", pme);
14949                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14950                return;
14951            }
14952
14953            // Shared libraries for the package need to be updated.
14954            synchronized (mPackages) {
14955                try {
14956                    updateSharedLibrariesLPw(pkg, null);
14957                } catch (PackageManagerException e) {
14958                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14959                }
14960            }
14961            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14962            // Do not run PackageDexOptimizer through the local performDexOpt
14963            // method because `pkg` is not in `mPackages` yet.
14964            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14965                    null /* instructionSets */, false /* checkProfiles */,
14966                    getCompilerFilterForReason(REASON_INSTALL));
14967            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14968            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14969                String msg = "Extracting package failed for " + pkgName;
14970                res.setError(INSTALL_FAILED_DEXOPT, msg);
14971                return;
14972            }
14973
14974            // Notify BackgroundDexOptService that the package has been changed.
14975            // If this is an update of a package which used to fail to compile,
14976            // BDOS will remove it from its blacklist.
14977            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14978        }
14979
14980        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14981            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14982            return;
14983        }
14984
14985        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14986
14987        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14988                "installPackageLI")) {
14989            if (replace) {
14990                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14991                        installerPackageName, res);
14992            } else {
14993                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14994                        args.user, installerPackageName, volumeUuid, res);
14995            }
14996        }
14997        synchronized (mPackages) {
14998            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14999            if (ps != null) {
15000                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15001            }
15002
15003            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15004            for (int i = 0; i < childCount; i++) {
15005                PackageParser.Package childPkg = pkg.childPackages.get(i);
15006                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15007                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15008                if (childPs != null) {
15009                    childRes.newUsers = childPs.queryInstalledUsers(
15010                            sUserManager.getUserIds(), true);
15011                }
15012            }
15013        }
15014    }
15015
15016    private void startIntentFilterVerifications(int userId, boolean replacing,
15017            PackageParser.Package pkg) {
15018        if (mIntentFilterVerifierComponent == null) {
15019            Slog.w(TAG, "No IntentFilter verification will not be done as "
15020                    + "there is no IntentFilterVerifier available!");
15021            return;
15022        }
15023
15024        final int verifierUid = getPackageUid(
15025                mIntentFilterVerifierComponent.getPackageName(),
15026                MATCH_DEBUG_TRIAGED_MISSING,
15027                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15028
15029        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15030        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15031        mHandler.sendMessage(msg);
15032
15033        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15034        for (int i = 0; i < childCount; i++) {
15035            PackageParser.Package childPkg = pkg.childPackages.get(i);
15036            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15037            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15038            mHandler.sendMessage(msg);
15039        }
15040    }
15041
15042    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15043            PackageParser.Package pkg) {
15044        int size = pkg.activities.size();
15045        if (size == 0) {
15046            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15047                    "No activity, so no need to verify any IntentFilter!");
15048            return;
15049        }
15050
15051        final boolean hasDomainURLs = hasDomainURLs(pkg);
15052        if (!hasDomainURLs) {
15053            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15054                    "No domain URLs, so no need to verify any IntentFilter!");
15055            return;
15056        }
15057
15058        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15059                + " if any IntentFilter from the " + size
15060                + " Activities needs verification ...");
15061
15062        int count = 0;
15063        final String packageName = pkg.packageName;
15064
15065        synchronized (mPackages) {
15066            // If this is a new install and we see that we've already run verification for this
15067            // package, we have nothing to do: it means the state was restored from backup.
15068            if (!replacing) {
15069                IntentFilterVerificationInfo ivi =
15070                        mSettings.getIntentFilterVerificationLPr(packageName);
15071                if (ivi != null) {
15072                    if (DEBUG_DOMAIN_VERIFICATION) {
15073                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15074                                + ivi.getStatusString());
15075                    }
15076                    return;
15077                }
15078            }
15079
15080            // If any filters need to be verified, then all need to be.
15081            boolean needToVerify = false;
15082            for (PackageParser.Activity a : pkg.activities) {
15083                for (ActivityIntentInfo filter : a.intents) {
15084                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15085                        if (DEBUG_DOMAIN_VERIFICATION) {
15086                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15087                        }
15088                        needToVerify = true;
15089                        break;
15090                    }
15091                }
15092            }
15093
15094            if (needToVerify) {
15095                final int verificationId = mIntentFilterVerificationToken++;
15096                for (PackageParser.Activity a : pkg.activities) {
15097                    for (ActivityIntentInfo filter : a.intents) {
15098                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15099                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15100                                    "Verification needed for IntentFilter:" + filter.toString());
15101                            mIntentFilterVerifier.addOneIntentFilterVerification(
15102                                    verifierUid, userId, verificationId, filter, packageName);
15103                            count++;
15104                        }
15105                    }
15106                }
15107            }
15108        }
15109
15110        if (count > 0) {
15111            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15112                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15113                    +  " for userId:" + userId);
15114            mIntentFilterVerifier.startVerifications(userId);
15115        } else {
15116            if (DEBUG_DOMAIN_VERIFICATION) {
15117                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15118            }
15119        }
15120    }
15121
15122    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15123        final ComponentName cn  = filter.activity.getComponentName();
15124        final String packageName = cn.getPackageName();
15125
15126        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15127                packageName);
15128        if (ivi == null) {
15129            return true;
15130        }
15131        int status = ivi.getStatus();
15132        switch (status) {
15133            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15134            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15135                return true;
15136
15137            default:
15138                // Nothing to do
15139                return false;
15140        }
15141    }
15142
15143    private static boolean isMultiArch(ApplicationInfo info) {
15144        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15145    }
15146
15147    private static boolean isExternal(PackageParser.Package pkg) {
15148        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15149    }
15150
15151    private static boolean isExternal(PackageSetting ps) {
15152        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15153    }
15154
15155    private static boolean isEphemeral(PackageParser.Package pkg) {
15156        return pkg.applicationInfo.isEphemeralApp();
15157    }
15158
15159    private static boolean isEphemeral(PackageSetting ps) {
15160        return ps.pkg != null && isEphemeral(ps.pkg);
15161    }
15162
15163    private static boolean isSystemApp(PackageParser.Package pkg) {
15164        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15165    }
15166
15167    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15168        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15169    }
15170
15171    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15172        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15173    }
15174
15175    private static boolean isSystemApp(PackageSetting ps) {
15176        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15177    }
15178
15179    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15180        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15181    }
15182
15183    private int packageFlagsToInstallFlags(PackageSetting ps) {
15184        int installFlags = 0;
15185        if (isEphemeral(ps)) {
15186            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15187        }
15188        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15189            // This existing package was an external ASEC install when we have
15190            // the external flag without a UUID
15191            installFlags |= PackageManager.INSTALL_EXTERNAL;
15192        }
15193        if (ps.isForwardLocked()) {
15194            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15195        }
15196        return installFlags;
15197    }
15198
15199    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15200        if (isExternal(pkg)) {
15201            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15202                return StorageManager.UUID_PRIMARY_PHYSICAL;
15203            } else {
15204                return pkg.volumeUuid;
15205            }
15206        } else {
15207            return StorageManager.UUID_PRIVATE_INTERNAL;
15208        }
15209    }
15210
15211    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15212        if (isExternal(pkg)) {
15213            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15214                return mSettings.getExternalVersion();
15215            } else {
15216                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15217            }
15218        } else {
15219            return mSettings.getInternalVersion();
15220        }
15221    }
15222
15223    private void deleteTempPackageFiles() {
15224        final FilenameFilter filter = new FilenameFilter() {
15225            public boolean accept(File dir, String name) {
15226                return name.startsWith("vmdl") && name.endsWith(".tmp");
15227            }
15228        };
15229        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15230            file.delete();
15231        }
15232    }
15233
15234    @Override
15235    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15236            int flags) {
15237        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15238                flags);
15239    }
15240
15241    @Override
15242    public void deletePackage(final String packageName,
15243            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15244        mContext.enforceCallingOrSelfPermission(
15245                android.Manifest.permission.DELETE_PACKAGES, null);
15246        Preconditions.checkNotNull(packageName);
15247        Preconditions.checkNotNull(observer);
15248        final int uid = Binder.getCallingUid();
15249        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15250        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15251        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15252            mContext.enforceCallingOrSelfPermission(
15253                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15254                    "deletePackage for user " + userId);
15255        }
15256
15257        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15258            try {
15259                observer.onPackageDeleted(packageName,
15260                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15261            } catch (RemoteException re) {
15262            }
15263            return;
15264        }
15265
15266        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15267            try {
15268                observer.onPackageDeleted(packageName,
15269                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15270            } catch (RemoteException re) {
15271            }
15272            return;
15273        }
15274
15275        if (DEBUG_REMOVE) {
15276            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15277                    + " deleteAllUsers: " + deleteAllUsers );
15278        }
15279        // Queue up an async operation since the package deletion may take a little while.
15280        mHandler.post(new Runnable() {
15281            public void run() {
15282                mHandler.removeCallbacks(this);
15283                int returnCode;
15284                if (!deleteAllUsers) {
15285                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15286                } else {
15287                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15288                    // If nobody is blocking uninstall, proceed with delete for all users
15289                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15290                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15291                    } else {
15292                        // Otherwise uninstall individually for users with blockUninstalls=false
15293                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15294                        for (int userId : users) {
15295                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15296                                returnCode = deletePackageX(packageName, userId, userFlags);
15297                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15298                                    Slog.w(TAG, "Package delete failed for user " + userId
15299                                            + ", returnCode " + returnCode);
15300                                }
15301                            }
15302                        }
15303                        // The app has only been marked uninstalled for certain users.
15304                        // We still need to report that delete was blocked
15305                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15306                    }
15307                }
15308                try {
15309                    observer.onPackageDeleted(packageName, returnCode, null);
15310                } catch (RemoteException e) {
15311                    Log.i(TAG, "Observer no longer exists.");
15312                } //end catch
15313            } //end run
15314        });
15315    }
15316
15317    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15318        int[] result = EMPTY_INT_ARRAY;
15319        for (int userId : userIds) {
15320            if (getBlockUninstallForUser(packageName, userId)) {
15321                result = ArrayUtils.appendInt(result, userId);
15322            }
15323        }
15324        return result;
15325    }
15326
15327    @Override
15328    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15329        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15330    }
15331
15332    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15333        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15334                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15335        try {
15336            if (dpm != null) {
15337                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15338                        /* callingUserOnly =*/ false);
15339                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15340                        : deviceOwnerComponentName.getPackageName();
15341                // Does the package contains the device owner?
15342                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15343                // this check is probably not needed, since DO should be registered as a device
15344                // admin on some user too. (Original bug for this: b/17657954)
15345                if (packageName.equals(deviceOwnerPackageName)) {
15346                    return true;
15347                }
15348                // Does it contain a device admin for any user?
15349                int[] users;
15350                if (userId == UserHandle.USER_ALL) {
15351                    users = sUserManager.getUserIds();
15352                } else {
15353                    users = new int[]{userId};
15354                }
15355                for (int i = 0; i < users.length; ++i) {
15356                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15357                        return true;
15358                    }
15359                }
15360            }
15361        } catch (RemoteException e) {
15362        }
15363        return false;
15364    }
15365
15366    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15367        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15368    }
15369
15370    /**
15371     *  This method is an internal method that could be get invoked either
15372     *  to delete an installed package or to clean up a failed installation.
15373     *  After deleting an installed package, a broadcast is sent to notify any
15374     *  listeners that the package has been removed. For cleaning up a failed
15375     *  installation, the broadcast is not necessary since the package's
15376     *  installation wouldn't have sent the initial broadcast either
15377     *  The key steps in deleting a package are
15378     *  deleting the package information in internal structures like mPackages,
15379     *  deleting the packages base directories through installd
15380     *  updating mSettings to reflect current status
15381     *  persisting settings for later use
15382     *  sending a broadcast if necessary
15383     */
15384    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15385        final PackageRemovedInfo info = new PackageRemovedInfo();
15386        final boolean res;
15387
15388        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15389                ? UserHandle.ALL : new UserHandle(userId);
15390
15391        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15392            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15393            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15394        }
15395
15396        PackageSetting uninstalledPs = null;
15397
15398        // for the uninstall-updates case and restricted profiles, remember the per-
15399        // user handle installed state
15400        int[] allUsers;
15401        synchronized (mPackages) {
15402            uninstalledPs = mSettings.mPackages.get(packageName);
15403            if (uninstalledPs == null) {
15404                Slog.w(TAG, "Not removing non-existent package " + packageName);
15405                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15406            }
15407            allUsers = sUserManager.getUserIds();
15408            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15409        }
15410
15411        synchronized (mInstallLock) {
15412            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15413            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15414                    "deletePackageX")) {
15415                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15416                        deleteFlags | REMOVE_CHATTY, info, true, null);
15417            }
15418            synchronized (mPackages) {
15419                if (res) {
15420                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15421                }
15422            }
15423        }
15424
15425        if (res) {
15426            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15427            info.sendPackageRemovedBroadcasts(killApp);
15428            info.sendSystemPackageUpdatedBroadcasts();
15429            info.sendSystemPackageAppearedBroadcasts();
15430        }
15431        // Force a gc here.
15432        Runtime.getRuntime().gc();
15433        // Delete the resources here after sending the broadcast to let
15434        // other processes clean up before deleting resources.
15435        if (info.args != null) {
15436            synchronized (mInstallLock) {
15437                info.args.doPostDeleteLI(true);
15438            }
15439        }
15440
15441        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15442    }
15443
15444    class PackageRemovedInfo {
15445        String removedPackage;
15446        int uid = -1;
15447        int removedAppId = -1;
15448        int[] origUsers;
15449        int[] removedUsers = null;
15450        boolean isRemovedPackageSystemUpdate = false;
15451        boolean isUpdate;
15452        boolean dataRemoved;
15453        boolean removedForAllUsers;
15454        // Clean up resources deleted packages.
15455        InstallArgs args = null;
15456        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15457        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15458
15459        void sendPackageRemovedBroadcasts(boolean killApp) {
15460            sendPackageRemovedBroadcastInternal(killApp);
15461            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15462            for (int i = 0; i < childCount; i++) {
15463                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15464                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15465            }
15466        }
15467
15468        void sendSystemPackageUpdatedBroadcasts() {
15469            if (isRemovedPackageSystemUpdate) {
15470                sendSystemPackageUpdatedBroadcastsInternal();
15471                final int childCount = (removedChildPackages != null)
15472                        ? removedChildPackages.size() : 0;
15473                for (int i = 0; i < childCount; i++) {
15474                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15475                    if (childInfo.isRemovedPackageSystemUpdate) {
15476                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15477                    }
15478                }
15479            }
15480        }
15481
15482        void sendSystemPackageAppearedBroadcasts() {
15483            final int packageCount = (appearedChildPackages != null)
15484                    ? appearedChildPackages.size() : 0;
15485            for (int i = 0; i < packageCount; i++) {
15486                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15487                for (int userId : installedInfo.newUsers) {
15488                    sendPackageAddedForUser(installedInfo.name, true,
15489                            UserHandle.getAppId(installedInfo.uid), userId);
15490                }
15491            }
15492        }
15493
15494        private void sendSystemPackageUpdatedBroadcastsInternal() {
15495            Bundle extras = new Bundle(2);
15496            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15497            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15498            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15499                    extras, 0, null, null, null);
15500            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15501                    extras, 0, null, null, null);
15502            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15503                    null, 0, removedPackage, null, null);
15504        }
15505
15506        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15507            Bundle extras = new Bundle(2);
15508            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15509            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15510            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15511            if (isUpdate || isRemovedPackageSystemUpdate) {
15512                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15513            }
15514            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15515            if (removedPackage != null) {
15516                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15517                        extras, 0, null, null, removedUsers);
15518                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15519                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15520                            removedPackage, extras, 0, null, null, removedUsers);
15521                }
15522            }
15523            if (removedAppId >= 0) {
15524                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15525                        removedUsers);
15526            }
15527        }
15528    }
15529
15530    /*
15531     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15532     * flag is not set, the data directory is removed as well.
15533     * make sure this flag is set for partially installed apps. If not its meaningless to
15534     * delete a partially installed application.
15535     */
15536    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15537            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15538        String packageName = ps.name;
15539        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15540        // Retrieve object to delete permissions for shared user later on
15541        final PackageParser.Package deletedPkg;
15542        final PackageSetting deletedPs;
15543        // reader
15544        synchronized (mPackages) {
15545            deletedPkg = mPackages.get(packageName);
15546            deletedPs = mSettings.mPackages.get(packageName);
15547            if (outInfo != null) {
15548                outInfo.removedPackage = packageName;
15549                outInfo.removedUsers = deletedPs != null
15550                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15551                        : null;
15552            }
15553        }
15554
15555        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15556
15557        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15558            final PackageParser.Package resolvedPkg;
15559            if (deletedPkg != null) {
15560                resolvedPkg = deletedPkg;
15561            } else {
15562                // We don't have a parsed package when it lives on an ejected
15563                // adopted storage device, so fake something together
15564                resolvedPkg = new PackageParser.Package(ps.name);
15565                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15566            }
15567            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15568                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15569            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15570            if (outInfo != null) {
15571                outInfo.dataRemoved = true;
15572            }
15573            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15574        }
15575
15576        // writer
15577        synchronized (mPackages) {
15578            if (deletedPs != null) {
15579                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15580                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15581                    clearDefaultBrowserIfNeeded(packageName);
15582                    if (outInfo != null) {
15583                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15584                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15585                    }
15586                    updatePermissionsLPw(deletedPs.name, null, 0);
15587                    if (deletedPs.sharedUser != null) {
15588                        // Remove permissions associated with package. Since runtime
15589                        // permissions are per user we have to kill the removed package
15590                        // or packages running under the shared user of the removed
15591                        // package if revoking the permissions requested only by the removed
15592                        // package is successful and this causes a change in gids.
15593                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15594                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15595                                    userId);
15596                            if (userIdToKill == UserHandle.USER_ALL
15597                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15598                                // If gids changed for this user, kill all affected packages.
15599                                mHandler.post(new Runnable() {
15600                                    @Override
15601                                    public void run() {
15602                                        // This has to happen with no lock held.
15603                                        killApplication(deletedPs.name, deletedPs.appId,
15604                                                KILL_APP_REASON_GIDS_CHANGED);
15605                                    }
15606                                });
15607                                break;
15608                            }
15609                        }
15610                    }
15611                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15612                }
15613                // make sure to preserve per-user disabled state if this removal was just
15614                // a downgrade of a system app to the factory package
15615                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15616                    if (DEBUG_REMOVE) {
15617                        Slog.d(TAG, "Propagating install state across downgrade");
15618                    }
15619                    for (int userId : allUserHandles) {
15620                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15621                        if (DEBUG_REMOVE) {
15622                            Slog.d(TAG, "    user " + userId + " => " + installed);
15623                        }
15624                        ps.setInstalled(installed, userId);
15625                    }
15626                }
15627            }
15628            // can downgrade to reader
15629            if (writeSettings) {
15630                // Save settings now
15631                mSettings.writeLPr();
15632            }
15633        }
15634        if (outInfo != null) {
15635            // A user ID was deleted here. Go through all users and remove it
15636            // from KeyStore.
15637            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15638        }
15639    }
15640
15641    static boolean locationIsPrivileged(File path) {
15642        try {
15643            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15644                    .getCanonicalPath();
15645            return path.getCanonicalPath().startsWith(privilegedAppDir);
15646        } catch (IOException e) {
15647            Slog.e(TAG, "Unable to access code path " + path);
15648        }
15649        return false;
15650    }
15651
15652    /*
15653     * Tries to delete system package.
15654     */
15655    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15656            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15657            boolean writeSettings) {
15658        if (deletedPs.parentPackageName != null) {
15659            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15660            return false;
15661        }
15662
15663        final boolean applyUserRestrictions
15664                = (allUserHandles != null) && (outInfo.origUsers != null);
15665        final PackageSetting disabledPs;
15666        // Confirm if the system package has been updated
15667        // An updated system app can be deleted. This will also have to restore
15668        // the system pkg from system partition
15669        // reader
15670        synchronized (mPackages) {
15671            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15672        }
15673
15674        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15675                + " disabledPs=" + disabledPs);
15676
15677        if (disabledPs == null) {
15678            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15679            return false;
15680        } else if (DEBUG_REMOVE) {
15681            Slog.d(TAG, "Deleting system pkg from data partition");
15682        }
15683
15684        if (DEBUG_REMOVE) {
15685            if (applyUserRestrictions) {
15686                Slog.d(TAG, "Remembering install states:");
15687                for (int userId : allUserHandles) {
15688                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15689                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15690                }
15691            }
15692        }
15693
15694        // Delete the updated package
15695        outInfo.isRemovedPackageSystemUpdate = true;
15696        if (outInfo.removedChildPackages != null) {
15697            final int childCount = (deletedPs.childPackageNames != null)
15698                    ? deletedPs.childPackageNames.size() : 0;
15699            for (int i = 0; i < childCount; i++) {
15700                String childPackageName = deletedPs.childPackageNames.get(i);
15701                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15702                        .contains(childPackageName)) {
15703                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15704                            childPackageName);
15705                    if (childInfo != null) {
15706                        childInfo.isRemovedPackageSystemUpdate = true;
15707                    }
15708                }
15709            }
15710        }
15711
15712        if (disabledPs.versionCode < deletedPs.versionCode) {
15713            // Delete data for downgrades
15714            flags &= ~PackageManager.DELETE_KEEP_DATA;
15715        } else {
15716            // Preserve data by setting flag
15717            flags |= PackageManager.DELETE_KEEP_DATA;
15718        }
15719
15720        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15721                outInfo, writeSettings, disabledPs.pkg);
15722        if (!ret) {
15723            return false;
15724        }
15725
15726        // writer
15727        synchronized (mPackages) {
15728            // Reinstate the old system package
15729            enableSystemPackageLPw(disabledPs.pkg);
15730            // Remove any native libraries from the upgraded package.
15731            removeNativeBinariesLI(deletedPs);
15732        }
15733
15734        // Install the system package
15735        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15736        int parseFlags = mDefParseFlags
15737                | PackageParser.PARSE_MUST_BE_APK
15738                | PackageParser.PARSE_IS_SYSTEM
15739                | PackageParser.PARSE_IS_SYSTEM_DIR;
15740        if (locationIsPrivileged(disabledPs.codePath)) {
15741            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15742        }
15743
15744        final PackageParser.Package newPkg;
15745        try {
15746            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15747        } catch (PackageManagerException e) {
15748            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15749                    + e.getMessage());
15750            return false;
15751        }
15752
15753        prepareAppDataAfterInstallLIF(newPkg);
15754
15755        // writer
15756        synchronized (mPackages) {
15757            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15758
15759            // Propagate the permissions state as we do not want to drop on the floor
15760            // runtime permissions. The update permissions method below will take
15761            // care of removing obsolete permissions and grant install permissions.
15762            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15763            updatePermissionsLPw(newPkg.packageName, newPkg,
15764                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15765
15766            if (applyUserRestrictions) {
15767                if (DEBUG_REMOVE) {
15768                    Slog.d(TAG, "Propagating install state across reinstall");
15769                }
15770                for (int userId : allUserHandles) {
15771                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15772                    if (DEBUG_REMOVE) {
15773                        Slog.d(TAG, "    user " + userId + " => " + installed);
15774                    }
15775                    ps.setInstalled(installed, userId);
15776
15777                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15778                }
15779                // Regardless of writeSettings we need to ensure that this restriction
15780                // state propagation is persisted
15781                mSettings.writeAllUsersPackageRestrictionsLPr();
15782            }
15783            // can downgrade to reader here
15784            if (writeSettings) {
15785                mSettings.writeLPr();
15786            }
15787        }
15788        return true;
15789    }
15790
15791    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15792            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15793            PackageRemovedInfo outInfo, boolean writeSettings,
15794            PackageParser.Package replacingPackage) {
15795        synchronized (mPackages) {
15796            if (outInfo != null) {
15797                outInfo.uid = ps.appId;
15798            }
15799
15800            if (outInfo != null && outInfo.removedChildPackages != null) {
15801                final int childCount = (ps.childPackageNames != null)
15802                        ? ps.childPackageNames.size() : 0;
15803                for (int i = 0; i < childCount; i++) {
15804                    String childPackageName = ps.childPackageNames.get(i);
15805                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15806                    if (childPs == null) {
15807                        return false;
15808                    }
15809                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15810                            childPackageName);
15811                    if (childInfo != null) {
15812                        childInfo.uid = childPs.appId;
15813                    }
15814                }
15815            }
15816        }
15817
15818        // Delete package data from internal structures and also remove data if flag is set
15819        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15820
15821        // Delete the child packages data
15822        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15823        for (int i = 0; i < childCount; i++) {
15824            PackageSetting childPs;
15825            synchronized (mPackages) {
15826                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15827            }
15828            if (childPs != null) {
15829                PackageRemovedInfo childOutInfo = (outInfo != null
15830                        && outInfo.removedChildPackages != null)
15831                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15832                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15833                        && (replacingPackage != null
15834                        && !replacingPackage.hasChildPackage(childPs.name))
15835                        ? flags & ~DELETE_KEEP_DATA : flags;
15836                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15837                        deleteFlags, writeSettings);
15838            }
15839        }
15840
15841        // Delete application code and resources only for parent packages
15842        if (ps.parentPackageName == null) {
15843            if (deleteCodeAndResources && (outInfo != null)) {
15844                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15845                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15846                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15847            }
15848        }
15849
15850        return true;
15851    }
15852
15853    @Override
15854    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15855            int userId) {
15856        mContext.enforceCallingOrSelfPermission(
15857                android.Manifest.permission.DELETE_PACKAGES, null);
15858        synchronized (mPackages) {
15859            PackageSetting ps = mSettings.mPackages.get(packageName);
15860            if (ps == null) {
15861                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15862                return false;
15863            }
15864            if (!ps.getInstalled(userId)) {
15865                // Can't block uninstall for an app that is not installed or enabled.
15866                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15867                return false;
15868            }
15869            ps.setBlockUninstall(blockUninstall, userId);
15870            mSettings.writePackageRestrictionsLPr(userId);
15871        }
15872        return true;
15873    }
15874
15875    @Override
15876    public boolean getBlockUninstallForUser(String packageName, int userId) {
15877        synchronized (mPackages) {
15878            PackageSetting ps = mSettings.mPackages.get(packageName);
15879            if (ps == null) {
15880                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15881                return false;
15882            }
15883            return ps.getBlockUninstall(userId);
15884        }
15885    }
15886
15887    @Override
15888    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15889        int callingUid = Binder.getCallingUid();
15890        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15891            throw new SecurityException(
15892                    "setRequiredForSystemUser can only be run by the system or root");
15893        }
15894        synchronized (mPackages) {
15895            PackageSetting ps = mSettings.mPackages.get(packageName);
15896            if (ps == null) {
15897                Log.w(TAG, "Package doesn't exist: " + packageName);
15898                return false;
15899            }
15900            if (systemUserApp) {
15901                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15902            } else {
15903                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15904            }
15905            mSettings.writeLPr();
15906        }
15907        return true;
15908    }
15909
15910    /*
15911     * This method handles package deletion in general
15912     */
15913    private boolean deletePackageLIF(String packageName, UserHandle user,
15914            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15915            PackageRemovedInfo outInfo, boolean writeSettings,
15916            PackageParser.Package replacingPackage) {
15917        if (packageName == null) {
15918            Slog.w(TAG, "Attempt to delete null packageName.");
15919            return false;
15920        }
15921
15922        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15923
15924        PackageSetting ps;
15925
15926        synchronized (mPackages) {
15927            ps = mSettings.mPackages.get(packageName);
15928            if (ps == null) {
15929                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15930                return false;
15931            }
15932
15933            if (ps.parentPackageName != null && (!isSystemApp(ps)
15934                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15935                if (DEBUG_REMOVE) {
15936                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15937                            + ((user == null) ? UserHandle.USER_ALL : user));
15938                }
15939                final int removedUserId = (user != null) ? user.getIdentifier()
15940                        : UserHandle.USER_ALL;
15941                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15942                    return false;
15943                }
15944                markPackageUninstalledForUserLPw(ps, user);
15945                scheduleWritePackageRestrictionsLocked(user);
15946                return true;
15947            }
15948        }
15949
15950        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15951                && user.getIdentifier() != UserHandle.USER_ALL)) {
15952            // The caller is asking that the package only be deleted for a single
15953            // user.  To do this, we just mark its uninstalled state and delete
15954            // its data. If this is a system app, we only allow this to happen if
15955            // they have set the special DELETE_SYSTEM_APP which requests different
15956            // semantics than normal for uninstalling system apps.
15957            markPackageUninstalledForUserLPw(ps, user);
15958
15959            if (!isSystemApp(ps)) {
15960                // Do not uninstall the APK if an app should be cached
15961                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15962                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15963                    // Other user still have this package installed, so all
15964                    // we need to do is clear this user's data and save that
15965                    // it is uninstalled.
15966                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15967                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15968                        return false;
15969                    }
15970                    scheduleWritePackageRestrictionsLocked(user);
15971                    return true;
15972                } else {
15973                    // We need to set it back to 'installed' so the uninstall
15974                    // broadcasts will be sent correctly.
15975                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15976                    ps.setInstalled(true, user.getIdentifier());
15977                }
15978            } else {
15979                // This is a system app, so we assume that the
15980                // other users still have this package installed, so all
15981                // we need to do is clear this user's data and save that
15982                // it is uninstalled.
15983                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15984                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15985                    return false;
15986                }
15987                scheduleWritePackageRestrictionsLocked(user);
15988                return true;
15989            }
15990        }
15991
15992        // If we are deleting a composite package for all users, keep track
15993        // of result for each child.
15994        if (ps.childPackageNames != null && outInfo != null) {
15995            synchronized (mPackages) {
15996                final int childCount = ps.childPackageNames.size();
15997                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15998                for (int i = 0; i < childCount; i++) {
15999                    String childPackageName = ps.childPackageNames.get(i);
16000                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16001                    childInfo.removedPackage = childPackageName;
16002                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16003                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16004                    if (childPs != null) {
16005                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16006                    }
16007                }
16008            }
16009        }
16010
16011        boolean ret = false;
16012        if (isSystemApp(ps)) {
16013            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16014            // When an updated system application is deleted we delete the existing resources
16015            // as well and fall back to existing code in system partition
16016            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16017        } else {
16018            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16019            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16020                    outInfo, writeSettings, replacingPackage);
16021        }
16022
16023        // Take a note whether we deleted the package for all users
16024        if (outInfo != null) {
16025            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16026            if (outInfo.removedChildPackages != null) {
16027                synchronized (mPackages) {
16028                    final int childCount = outInfo.removedChildPackages.size();
16029                    for (int i = 0; i < childCount; i++) {
16030                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16031                        if (childInfo != null) {
16032                            childInfo.removedForAllUsers = mPackages.get(
16033                                    childInfo.removedPackage) == null;
16034                        }
16035                    }
16036                }
16037            }
16038            // If we uninstalled an update to a system app there may be some
16039            // child packages that appeared as they are declared in the system
16040            // app but were not declared in the update.
16041            if (isSystemApp(ps)) {
16042                synchronized (mPackages) {
16043                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16044                    final int childCount = (updatedPs.childPackageNames != null)
16045                            ? updatedPs.childPackageNames.size() : 0;
16046                    for (int i = 0; i < childCount; i++) {
16047                        String childPackageName = updatedPs.childPackageNames.get(i);
16048                        if (outInfo.removedChildPackages == null
16049                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16050                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16051                            if (childPs == null) {
16052                                continue;
16053                            }
16054                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16055                            installRes.name = childPackageName;
16056                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16057                            installRes.pkg = mPackages.get(childPackageName);
16058                            installRes.uid = childPs.pkg.applicationInfo.uid;
16059                            if (outInfo.appearedChildPackages == null) {
16060                                outInfo.appearedChildPackages = new ArrayMap<>();
16061                            }
16062                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16063                        }
16064                    }
16065                }
16066            }
16067        }
16068
16069        return ret;
16070    }
16071
16072    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16073        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16074                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16075        for (int nextUserId : userIds) {
16076            if (DEBUG_REMOVE) {
16077                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16078            }
16079            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16080                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16081                    false /*hidden*/, false /*suspended*/, null, null, null,
16082                    false /*blockUninstall*/,
16083                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16084        }
16085    }
16086
16087    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16088            PackageRemovedInfo outInfo) {
16089        final PackageParser.Package pkg;
16090        synchronized (mPackages) {
16091            pkg = mPackages.get(ps.name);
16092        }
16093
16094        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16095                : new int[] {userId};
16096        for (int nextUserId : userIds) {
16097            if (DEBUG_REMOVE) {
16098                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16099                        + nextUserId);
16100            }
16101
16102            destroyAppDataLIF(pkg, userId,
16103                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16104            destroyAppProfilesLIF(pkg, userId);
16105            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16106            schedulePackageCleaning(ps.name, nextUserId, false);
16107            synchronized (mPackages) {
16108                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16109                    scheduleWritePackageRestrictionsLocked(nextUserId);
16110                }
16111                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16112            }
16113        }
16114
16115        if (outInfo != null) {
16116            outInfo.removedPackage = ps.name;
16117            outInfo.removedAppId = ps.appId;
16118            outInfo.removedUsers = userIds;
16119        }
16120
16121        return true;
16122    }
16123
16124    private final class ClearStorageConnection implements ServiceConnection {
16125        IMediaContainerService mContainerService;
16126
16127        @Override
16128        public void onServiceConnected(ComponentName name, IBinder service) {
16129            synchronized (this) {
16130                mContainerService = IMediaContainerService.Stub.asInterface(service);
16131                notifyAll();
16132            }
16133        }
16134
16135        @Override
16136        public void onServiceDisconnected(ComponentName name) {
16137        }
16138    }
16139
16140    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16141        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16142
16143        final boolean mounted;
16144        if (Environment.isExternalStorageEmulated()) {
16145            mounted = true;
16146        } else {
16147            final String status = Environment.getExternalStorageState();
16148
16149            mounted = status.equals(Environment.MEDIA_MOUNTED)
16150                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16151        }
16152
16153        if (!mounted) {
16154            return;
16155        }
16156
16157        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16158        int[] users;
16159        if (userId == UserHandle.USER_ALL) {
16160            users = sUserManager.getUserIds();
16161        } else {
16162            users = new int[] { userId };
16163        }
16164        final ClearStorageConnection conn = new ClearStorageConnection();
16165        if (mContext.bindServiceAsUser(
16166                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16167            try {
16168                for (int curUser : users) {
16169                    long timeout = SystemClock.uptimeMillis() + 5000;
16170                    synchronized (conn) {
16171                        long now = SystemClock.uptimeMillis();
16172                        while (conn.mContainerService == null && now < timeout) {
16173                            try {
16174                                conn.wait(timeout - now);
16175                            } catch (InterruptedException e) {
16176                            }
16177                        }
16178                    }
16179                    if (conn.mContainerService == null) {
16180                        return;
16181                    }
16182
16183                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16184                    clearDirectory(conn.mContainerService,
16185                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16186                    if (allData) {
16187                        clearDirectory(conn.mContainerService,
16188                                userEnv.buildExternalStorageAppDataDirs(packageName));
16189                        clearDirectory(conn.mContainerService,
16190                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16191                    }
16192                }
16193            } finally {
16194                mContext.unbindService(conn);
16195            }
16196        }
16197    }
16198
16199    @Override
16200    public void clearApplicationProfileData(String packageName) {
16201        enforceSystemOrRoot("Only the system can clear all profile data");
16202
16203        final PackageParser.Package pkg;
16204        synchronized (mPackages) {
16205            pkg = mPackages.get(packageName);
16206        }
16207
16208        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16209            synchronized (mInstallLock) {
16210                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16211            }
16212        }
16213    }
16214
16215    @Override
16216    public void clearApplicationUserData(final String packageName,
16217            final IPackageDataObserver observer, final int userId) {
16218        mContext.enforceCallingOrSelfPermission(
16219                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16220
16221        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16222                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16223
16224        final DevicePolicyManagerInternal dpmi = LocalServices
16225                .getService(DevicePolicyManagerInternal.class);
16226        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16227            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16228        }
16229        // Queue up an async operation since the package deletion may take a little while.
16230        mHandler.post(new Runnable() {
16231            public void run() {
16232                mHandler.removeCallbacks(this);
16233                final boolean succeeded;
16234                try (PackageFreezer freezer = freezePackage(packageName,
16235                        "clearApplicationUserData")) {
16236                    synchronized (mInstallLock) {
16237                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16238                    }
16239                    clearExternalStorageDataSync(packageName, userId, true);
16240                }
16241                if (succeeded) {
16242                    // invoke DeviceStorageMonitor's update method to clear any notifications
16243                    DeviceStorageMonitorInternal dsm = LocalServices
16244                            .getService(DeviceStorageMonitorInternal.class);
16245                    if (dsm != null) {
16246                        dsm.checkMemory();
16247                    }
16248                }
16249                if(observer != null) {
16250                    try {
16251                        observer.onRemoveCompleted(packageName, succeeded);
16252                    } catch (RemoteException e) {
16253                        Log.i(TAG, "Observer no longer exists.");
16254                    }
16255                } //end if observer
16256            } //end run
16257        });
16258    }
16259
16260    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16261        if (packageName == null) {
16262            Slog.w(TAG, "Attempt to delete null packageName.");
16263            return false;
16264        }
16265
16266        // Try finding details about the requested package
16267        PackageParser.Package pkg;
16268        synchronized (mPackages) {
16269            pkg = mPackages.get(packageName);
16270            if (pkg == null) {
16271                final PackageSetting ps = mSettings.mPackages.get(packageName);
16272                if (ps != null) {
16273                    pkg = ps.pkg;
16274                }
16275            }
16276
16277            if (pkg == null) {
16278                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16279                return false;
16280            }
16281
16282            PackageSetting ps = (PackageSetting) pkg.mExtras;
16283            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16284        }
16285
16286        clearAppDataLIF(pkg, userId,
16287                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16288
16289        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16290        removeKeystoreDataIfNeeded(userId, appId);
16291
16292        UserManagerInternal umInternal = getUserManagerInternal();
16293        final int flags;
16294        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16295            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16296        } else if (umInternal.isUserRunning(userId)) {
16297            flags = StorageManager.FLAG_STORAGE_DE;
16298        } else {
16299            flags = 0;
16300        }
16301        prepareAppDataContentsLIF(pkg, userId, flags);
16302
16303        return true;
16304    }
16305
16306    /**
16307     * Reverts user permission state changes (permissions and flags) in
16308     * all packages for a given user.
16309     *
16310     * @param userId The device user for which to do a reset.
16311     */
16312    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16313        final int packageCount = mPackages.size();
16314        for (int i = 0; i < packageCount; i++) {
16315            PackageParser.Package pkg = mPackages.valueAt(i);
16316            PackageSetting ps = (PackageSetting) pkg.mExtras;
16317            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16318        }
16319    }
16320
16321    private void resetNetworkPolicies(int userId) {
16322        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16323    }
16324
16325    /**
16326     * Reverts user permission state changes (permissions and flags).
16327     *
16328     * @param ps The package for which to reset.
16329     * @param userId The device user for which to do a reset.
16330     */
16331    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16332            final PackageSetting ps, final int userId) {
16333        if (ps.pkg == null) {
16334            return;
16335        }
16336
16337        // These are flags that can change base on user actions.
16338        final int userSettableMask = FLAG_PERMISSION_USER_SET
16339                | FLAG_PERMISSION_USER_FIXED
16340                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16341                | FLAG_PERMISSION_REVIEW_REQUIRED;
16342
16343        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16344                | FLAG_PERMISSION_POLICY_FIXED;
16345
16346        boolean writeInstallPermissions = false;
16347        boolean writeRuntimePermissions = false;
16348
16349        final int permissionCount = ps.pkg.requestedPermissions.size();
16350        for (int i = 0; i < permissionCount; i++) {
16351            String permission = ps.pkg.requestedPermissions.get(i);
16352
16353            BasePermission bp = mSettings.mPermissions.get(permission);
16354            if (bp == null) {
16355                continue;
16356            }
16357
16358            // If shared user we just reset the state to which only this app contributed.
16359            if (ps.sharedUser != null) {
16360                boolean used = false;
16361                final int packageCount = ps.sharedUser.packages.size();
16362                for (int j = 0; j < packageCount; j++) {
16363                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16364                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16365                            && pkg.pkg.requestedPermissions.contains(permission)) {
16366                        used = true;
16367                        break;
16368                    }
16369                }
16370                if (used) {
16371                    continue;
16372                }
16373            }
16374
16375            PermissionsState permissionsState = ps.getPermissionsState();
16376
16377            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16378
16379            // Always clear the user settable flags.
16380            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16381                    bp.name) != null;
16382            // If permission review is enabled and this is a legacy app, mark the
16383            // permission as requiring a review as this is the initial state.
16384            int flags = 0;
16385            if (Build.PERMISSIONS_REVIEW_REQUIRED
16386                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16387                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16388            }
16389            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16390                if (hasInstallState) {
16391                    writeInstallPermissions = true;
16392                } else {
16393                    writeRuntimePermissions = true;
16394                }
16395            }
16396
16397            // Below is only runtime permission handling.
16398            if (!bp.isRuntime()) {
16399                continue;
16400            }
16401
16402            // Never clobber system or policy.
16403            if ((oldFlags & policyOrSystemFlags) != 0) {
16404                continue;
16405            }
16406
16407            // If this permission was granted by default, make sure it is.
16408            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16409                if (permissionsState.grantRuntimePermission(bp, userId)
16410                        != PERMISSION_OPERATION_FAILURE) {
16411                    writeRuntimePermissions = true;
16412                }
16413            // If permission review is enabled the permissions for a legacy apps
16414            // are represented as constantly granted runtime ones, so don't revoke.
16415            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16416                // Otherwise, reset the permission.
16417                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16418                switch (revokeResult) {
16419                    case PERMISSION_OPERATION_SUCCESS:
16420                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16421                        writeRuntimePermissions = true;
16422                        final int appId = ps.appId;
16423                        mHandler.post(new Runnable() {
16424                            @Override
16425                            public void run() {
16426                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16427                            }
16428                        });
16429                    } break;
16430                }
16431            }
16432        }
16433
16434        // Synchronously write as we are taking permissions away.
16435        if (writeRuntimePermissions) {
16436            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16437        }
16438
16439        // Synchronously write as we are taking permissions away.
16440        if (writeInstallPermissions) {
16441            mSettings.writeLPr();
16442        }
16443    }
16444
16445    /**
16446     * Remove entries from the keystore daemon. Will only remove it if the
16447     * {@code appId} is valid.
16448     */
16449    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16450        if (appId < 0) {
16451            return;
16452        }
16453
16454        final KeyStore keyStore = KeyStore.getInstance();
16455        if (keyStore != null) {
16456            if (userId == UserHandle.USER_ALL) {
16457                for (final int individual : sUserManager.getUserIds()) {
16458                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16459                }
16460            } else {
16461                keyStore.clearUid(UserHandle.getUid(userId, appId));
16462            }
16463        } else {
16464            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16465        }
16466    }
16467
16468    @Override
16469    public void deleteApplicationCacheFiles(final String packageName,
16470            final IPackageDataObserver observer) {
16471        final int userId = UserHandle.getCallingUserId();
16472        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16473    }
16474
16475    @Override
16476    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16477            final IPackageDataObserver observer) {
16478        mContext.enforceCallingOrSelfPermission(
16479                android.Manifest.permission.DELETE_CACHE_FILES, null);
16480        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16481                /* requireFullPermission= */ true, /* checkShell= */ false,
16482                "delete application cache files");
16483
16484        final PackageParser.Package pkg;
16485        synchronized (mPackages) {
16486            pkg = mPackages.get(packageName);
16487        }
16488
16489        // Queue up an async operation since the package deletion may take a little while.
16490        mHandler.post(new Runnable() {
16491            public void run() {
16492                synchronized (mInstallLock) {
16493                    final int flags = StorageManager.FLAG_STORAGE_DE
16494                            | StorageManager.FLAG_STORAGE_CE;
16495                    // We're only clearing cache files, so we don't care if the
16496                    // app is unfrozen and still able to run
16497                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16498                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16499                }
16500                clearExternalStorageDataSync(packageName, userId, false);
16501                if (observer != null) {
16502                    try {
16503                        observer.onRemoveCompleted(packageName, true);
16504                    } catch (RemoteException e) {
16505                        Log.i(TAG, "Observer no longer exists.");
16506                    }
16507                }
16508            }
16509        });
16510    }
16511
16512    @Override
16513    public void getPackageSizeInfo(final String packageName, int userHandle,
16514            final IPackageStatsObserver observer) {
16515        mContext.enforceCallingOrSelfPermission(
16516                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16517        if (packageName == null) {
16518            throw new IllegalArgumentException("Attempt to get size of null packageName");
16519        }
16520
16521        PackageStats stats = new PackageStats(packageName, userHandle);
16522
16523        /*
16524         * Queue up an async operation since the package measurement may take a
16525         * little while.
16526         */
16527        Message msg = mHandler.obtainMessage(INIT_COPY);
16528        msg.obj = new MeasureParams(stats, observer);
16529        mHandler.sendMessage(msg);
16530    }
16531
16532    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16533        final PackageSetting ps;
16534        synchronized (mPackages) {
16535            ps = mSettings.mPackages.get(packageName);
16536            if (ps == null) {
16537                Slog.w(TAG, "Failed to find settings for " + packageName);
16538                return false;
16539            }
16540        }
16541        try {
16542            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16543                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16544                    ps.getCeDataInode(userId), ps.codePathString, stats);
16545        } catch (InstallerException e) {
16546            Slog.w(TAG, String.valueOf(e));
16547            return false;
16548        }
16549
16550        // For now, ignore code size of packages on system partition
16551        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16552            stats.codeSize = 0;
16553        }
16554
16555        return true;
16556    }
16557
16558    private int getUidTargetSdkVersionLockedLPr(int uid) {
16559        Object obj = mSettings.getUserIdLPr(uid);
16560        if (obj instanceof SharedUserSetting) {
16561            final SharedUserSetting sus = (SharedUserSetting) obj;
16562            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16563            final Iterator<PackageSetting> it = sus.packages.iterator();
16564            while (it.hasNext()) {
16565                final PackageSetting ps = it.next();
16566                if (ps.pkg != null) {
16567                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16568                    if (v < vers) vers = v;
16569                }
16570            }
16571            return vers;
16572        } else if (obj instanceof PackageSetting) {
16573            final PackageSetting ps = (PackageSetting) obj;
16574            if (ps.pkg != null) {
16575                return ps.pkg.applicationInfo.targetSdkVersion;
16576            }
16577        }
16578        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16579    }
16580
16581    @Override
16582    public void addPreferredActivity(IntentFilter filter, int match,
16583            ComponentName[] set, ComponentName activity, int userId) {
16584        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16585                "Adding preferred");
16586    }
16587
16588    private void addPreferredActivityInternal(IntentFilter filter, int match,
16589            ComponentName[] set, ComponentName activity, boolean always, int userId,
16590            String opname) {
16591        // writer
16592        int callingUid = Binder.getCallingUid();
16593        enforceCrossUserPermission(callingUid, userId,
16594                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16595        if (filter.countActions() == 0) {
16596            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16597            return;
16598        }
16599        synchronized (mPackages) {
16600            if (mContext.checkCallingOrSelfPermission(
16601                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16602                    != PackageManager.PERMISSION_GRANTED) {
16603                if (getUidTargetSdkVersionLockedLPr(callingUid)
16604                        < Build.VERSION_CODES.FROYO) {
16605                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16606                            + callingUid);
16607                    return;
16608                }
16609                mContext.enforceCallingOrSelfPermission(
16610                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16611            }
16612
16613            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16614            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16615                    + userId + ":");
16616            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16617            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16618            scheduleWritePackageRestrictionsLocked(userId);
16619        }
16620    }
16621
16622    @Override
16623    public void replacePreferredActivity(IntentFilter filter, int match,
16624            ComponentName[] set, ComponentName activity, int userId) {
16625        if (filter.countActions() != 1) {
16626            throw new IllegalArgumentException(
16627                    "replacePreferredActivity expects filter to have only 1 action.");
16628        }
16629        if (filter.countDataAuthorities() != 0
16630                || filter.countDataPaths() != 0
16631                || filter.countDataSchemes() > 1
16632                || filter.countDataTypes() != 0) {
16633            throw new IllegalArgumentException(
16634                    "replacePreferredActivity expects filter to have no data authorities, " +
16635                    "paths, or types; and at most one scheme.");
16636        }
16637
16638        final int callingUid = Binder.getCallingUid();
16639        enforceCrossUserPermission(callingUid, userId,
16640                true /* requireFullPermission */, false /* checkShell */,
16641                "replace preferred activity");
16642        synchronized (mPackages) {
16643            if (mContext.checkCallingOrSelfPermission(
16644                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16645                    != PackageManager.PERMISSION_GRANTED) {
16646                if (getUidTargetSdkVersionLockedLPr(callingUid)
16647                        < Build.VERSION_CODES.FROYO) {
16648                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16649                            + Binder.getCallingUid());
16650                    return;
16651                }
16652                mContext.enforceCallingOrSelfPermission(
16653                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16654            }
16655
16656            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16657            if (pir != null) {
16658                // Get all of the existing entries that exactly match this filter.
16659                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16660                if (existing != null && existing.size() == 1) {
16661                    PreferredActivity cur = existing.get(0);
16662                    if (DEBUG_PREFERRED) {
16663                        Slog.i(TAG, "Checking replace of preferred:");
16664                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16665                        if (!cur.mPref.mAlways) {
16666                            Slog.i(TAG, "  -- CUR; not mAlways!");
16667                        } else {
16668                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16669                            Slog.i(TAG, "  -- CUR: mSet="
16670                                    + Arrays.toString(cur.mPref.mSetComponents));
16671                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16672                            Slog.i(TAG, "  -- NEW: mMatch="
16673                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16674                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16675                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16676                        }
16677                    }
16678                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16679                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16680                            && cur.mPref.sameSet(set)) {
16681                        // Setting the preferred activity to what it happens to be already
16682                        if (DEBUG_PREFERRED) {
16683                            Slog.i(TAG, "Replacing with same preferred activity "
16684                                    + cur.mPref.mShortComponent + " for user "
16685                                    + userId + ":");
16686                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16687                        }
16688                        return;
16689                    }
16690                }
16691
16692                if (existing != null) {
16693                    if (DEBUG_PREFERRED) {
16694                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16695                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16696                    }
16697                    for (int i = 0; i < existing.size(); i++) {
16698                        PreferredActivity pa = existing.get(i);
16699                        if (DEBUG_PREFERRED) {
16700                            Slog.i(TAG, "Removing existing preferred activity "
16701                                    + pa.mPref.mComponent + ":");
16702                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16703                        }
16704                        pir.removeFilter(pa);
16705                    }
16706                }
16707            }
16708            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16709                    "Replacing preferred");
16710        }
16711    }
16712
16713    @Override
16714    public void clearPackagePreferredActivities(String packageName) {
16715        final int uid = Binder.getCallingUid();
16716        // writer
16717        synchronized (mPackages) {
16718            PackageParser.Package pkg = mPackages.get(packageName);
16719            if (pkg == null || pkg.applicationInfo.uid != uid) {
16720                if (mContext.checkCallingOrSelfPermission(
16721                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16722                        != PackageManager.PERMISSION_GRANTED) {
16723                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16724                            < Build.VERSION_CODES.FROYO) {
16725                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16726                                + Binder.getCallingUid());
16727                        return;
16728                    }
16729                    mContext.enforceCallingOrSelfPermission(
16730                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16731                }
16732            }
16733
16734            int user = UserHandle.getCallingUserId();
16735            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16736                scheduleWritePackageRestrictionsLocked(user);
16737            }
16738        }
16739    }
16740
16741    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16742    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16743        ArrayList<PreferredActivity> removed = null;
16744        boolean changed = false;
16745        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16746            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16747            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16748            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16749                continue;
16750            }
16751            Iterator<PreferredActivity> it = pir.filterIterator();
16752            while (it.hasNext()) {
16753                PreferredActivity pa = it.next();
16754                // Mark entry for removal only if it matches the package name
16755                // and the entry is of type "always".
16756                if (packageName == null ||
16757                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16758                                && pa.mPref.mAlways)) {
16759                    if (removed == null) {
16760                        removed = new ArrayList<PreferredActivity>();
16761                    }
16762                    removed.add(pa);
16763                }
16764            }
16765            if (removed != null) {
16766                for (int j=0; j<removed.size(); j++) {
16767                    PreferredActivity pa = removed.get(j);
16768                    pir.removeFilter(pa);
16769                }
16770                changed = true;
16771            }
16772        }
16773        return changed;
16774    }
16775
16776    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16777    private void clearIntentFilterVerificationsLPw(int userId) {
16778        final int packageCount = mPackages.size();
16779        for (int i = 0; i < packageCount; i++) {
16780            PackageParser.Package pkg = mPackages.valueAt(i);
16781            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16782        }
16783    }
16784
16785    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16786    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16787        if (userId == UserHandle.USER_ALL) {
16788            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16789                    sUserManager.getUserIds())) {
16790                for (int oneUserId : sUserManager.getUserIds()) {
16791                    scheduleWritePackageRestrictionsLocked(oneUserId);
16792                }
16793            }
16794        } else {
16795            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16796                scheduleWritePackageRestrictionsLocked(userId);
16797            }
16798        }
16799    }
16800
16801    void clearDefaultBrowserIfNeeded(String packageName) {
16802        for (int oneUserId : sUserManager.getUserIds()) {
16803            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16804            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16805            if (packageName.equals(defaultBrowserPackageName)) {
16806                setDefaultBrowserPackageName(null, oneUserId);
16807            }
16808        }
16809    }
16810
16811    @Override
16812    public void resetApplicationPreferences(int userId) {
16813        mContext.enforceCallingOrSelfPermission(
16814                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16815        final long identity = Binder.clearCallingIdentity();
16816        // writer
16817        try {
16818            synchronized (mPackages) {
16819                clearPackagePreferredActivitiesLPw(null, userId);
16820                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16821                // TODO: We have to reset the default SMS and Phone. This requires
16822                // significant refactoring to keep all default apps in the package
16823                // manager (cleaner but more work) or have the services provide
16824                // callbacks to the package manager to request a default app reset.
16825                applyFactoryDefaultBrowserLPw(userId);
16826                clearIntentFilterVerificationsLPw(userId);
16827                primeDomainVerificationsLPw(userId);
16828                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16829                scheduleWritePackageRestrictionsLocked(userId);
16830            }
16831            resetNetworkPolicies(userId);
16832        } finally {
16833            Binder.restoreCallingIdentity(identity);
16834        }
16835    }
16836
16837    @Override
16838    public int getPreferredActivities(List<IntentFilter> outFilters,
16839            List<ComponentName> outActivities, String packageName) {
16840
16841        int num = 0;
16842        final int userId = UserHandle.getCallingUserId();
16843        // reader
16844        synchronized (mPackages) {
16845            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16846            if (pir != null) {
16847                final Iterator<PreferredActivity> it = pir.filterIterator();
16848                while (it.hasNext()) {
16849                    final PreferredActivity pa = it.next();
16850                    if (packageName == null
16851                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16852                                    && pa.mPref.mAlways)) {
16853                        if (outFilters != null) {
16854                            outFilters.add(new IntentFilter(pa));
16855                        }
16856                        if (outActivities != null) {
16857                            outActivities.add(pa.mPref.mComponent);
16858                        }
16859                    }
16860                }
16861            }
16862        }
16863
16864        return num;
16865    }
16866
16867    @Override
16868    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16869            int userId) {
16870        int callingUid = Binder.getCallingUid();
16871        if (callingUid != Process.SYSTEM_UID) {
16872            throw new SecurityException(
16873                    "addPersistentPreferredActivity can only be run by the system");
16874        }
16875        if (filter.countActions() == 0) {
16876            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16877            return;
16878        }
16879        synchronized (mPackages) {
16880            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16881                    ":");
16882            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16883            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16884                    new PersistentPreferredActivity(filter, activity));
16885            scheduleWritePackageRestrictionsLocked(userId);
16886        }
16887    }
16888
16889    @Override
16890    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16891        int callingUid = Binder.getCallingUid();
16892        if (callingUid != Process.SYSTEM_UID) {
16893            throw new SecurityException(
16894                    "clearPackagePersistentPreferredActivities can only be run by the system");
16895        }
16896        ArrayList<PersistentPreferredActivity> removed = null;
16897        boolean changed = false;
16898        synchronized (mPackages) {
16899            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16900                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16901                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16902                        .valueAt(i);
16903                if (userId != thisUserId) {
16904                    continue;
16905                }
16906                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16907                while (it.hasNext()) {
16908                    PersistentPreferredActivity ppa = it.next();
16909                    // Mark entry for removal only if it matches the package name.
16910                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16911                        if (removed == null) {
16912                            removed = new ArrayList<PersistentPreferredActivity>();
16913                        }
16914                        removed.add(ppa);
16915                    }
16916                }
16917                if (removed != null) {
16918                    for (int j=0; j<removed.size(); j++) {
16919                        PersistentPreferredActivity ppa = removed.get(j);
16920                        ppir.removeFilter(ppa);
16921                    }
16922                    changed = true;
16923                }
16924            }
16925
16926            if (changed) {
16927                scheduleWritePackageRestrictionsLocked(userId);
16928            }
16929        }
16930    }
16931
16932    /**
16933     * Common machinery for picking apart a restored XML blob and passing
16934     * it to a caller-supplied functor to be applied to the running system.
16935     */
16936    private void restoreFromXml(XmlPullParser parser, int userId,
16937            String expectedStartTag, BlobXmlRestorer functor)
16938            throws IOException, XmlPullParserException {
16939        int type;
16940        while ((type = parser.next()) != XmlPullParser.START_TAG
16941                && type != XmlPullParser.END_DOCUMENT) {
16942        }
16943        if (type != XmlPullParser.START_TAG) {
16944            // oops didn't find a start tag?!
16945            if (DEBUG_BACKUP) {
16946                Slog.e(TAG, "Didn't find start tag during restore");
16947            }
16948            return;
16949        }
16950Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16951        // this is supposed to be TAG_PREFERRED_BACKUP
16952        if (!expectedStartTag.equals(parser.getName())) {
16953            if (DEBUG_BACKUP) {
16954                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16955            }
16956            return;
16957        }
16958
16959        // skip interfering stuff, then we're aligned with the backing implementation
16960        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16961Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16962        functor.apply(parser, userId);
16963    }
16964
16965    private interface BlobXmlRestorer {
16966        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16967    }
16968
16969    /**
16970     * Non-Binder method, support for the backup/restore mechanism: write the
16971     * full set of preferred activities in its canonical XML format.  Returns the
16972     * XML output as a byte array, or null if there is none.
16973     */
16974    @Override
16975    public byte[] getPreferredActivityBackup(int userId) {
16976        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16977            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16978        }
16979
16980        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16981        try {
16982            final XmlSerializer serializer = new FastXmlSerializer();
16983            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16984            serializer.startDocument(null, true);
16985            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16986
16987            synchronized (mPackages) {
16988                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16989            }
16990
16991            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16992            serializer.endDocument();
16993            serializer.flush();
16994        } catch (Exception e) {
16995            if (DEBUG_BACKUP) {
16996                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16997            }
16998            return null;
16999        }
17000
17001        return dataStream.toByteArray();
17002    }
17003
17004    @Override
17005    public void restorePreferredActivities(byte[] backup, int userId) {
17006        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17007            throw new SecurityException("Only the system may call restorePreferredActivities()");
17008        }
17009
17010        try {
17011            final XmlPullParser parser = Xml.newPullParser();
17012            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17013            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17014                    new BlobXmlRestorer() {
17015                        @Override
17016                        public void apply(XmlPullParser parser, int userId)
17017                                throws XmlPullParserException, IOException {
17018                            synchronized (mPackages) {
17019                                mSettings.readPreferredActivitiesLPw(parser, userId);
17020                            }
17021                        }
17022                    } );
17023        } catch (Exception e) {
17024            if (DEBUG_BACKUP) {
17025                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17026            }
17027        }
17028    }
17029
17030    /**
17031     * Non-Binder method, support for the backup/restore mechanism: write the
17032     * default browser (etc) settings in its canonical XML format.  Returns the default
17033     * browser XML representation as a byte array, or null if there is none.
17034     */
17035    @Override
17036    public byte[] getDefaultAppsBackup(int userId) {
17037        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17038            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17039        }
17040
17041        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17042        try {
17043            final XmlSerializer serializer = new FastXmlSerializer();
17044            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17045            serializer.startDocument(null, true);
17046            serializer.startTag(null, TAG_DEFAULT_APPS);
17047
17048            synchronized (mPackages) {
17049                mSettings.writeDefaultAppsLPr(serializer, userId);
17050            }
17051
17052            serializer.endTag(null, TAG_DEFAULT_APPS);
17053            serializer.endDocument();
17054            serializer.flush();
17055        } catch (Exception e) {
17056            if (DEBUG_BACKUP) {
17057                Slog.e(TAG, "Unable to write default apps for backup", e);
17058            }
17059            return null;
17060        }
17061
17062        return dataStream.toByteArray();
17063    }
17064
17065    @Override
17066    public void restoreDefaultApps(byte[] backup, int userId) {
17067        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17068            throw new SecurityException("Only the system may call restoreDefaultApps()");
17069        }
17070
17071        try {
17072            final XmlPullParser parser = Xml.newPullParser();
17073            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17074            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17075                    new BlobXmlRestorer() {
17076                        @Override
17077                        public void apply(XmlPullParser parser, int userId)
17078                                throws XmlPullParserException, IOException {
17079                            synchronized (mPackages) {
17080                                mSettings.readDefaultAppsLPw(parser, userId);
17081                            }
17082                        }
17083                    } );
17084        } catch (Exception e) {
17085            if (DEBUG_BACKUP) {
17086                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17087            }
17088        }
17089    }
17090
17091    @Override
17092    public byte[] getIntentFilterVerificationBackup(int userId) {
17093        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17094            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17095        }
17096
17097        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17098        try {
17099            final XmlSerializer serializer = new FastXmlSerializer();
17100            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17101            serializer.startDocument(null, true);
17102            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17103
17104            synchronized (mPackages) {
17105                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17106            }
17107
17108            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17109            serializer.endDocument();
17110            serializer.flush();
17111        } catch (Exception e) {
17112            if (DEBUG_BACKUP) {
17113                Slog.e(TAG, "Unable to write default apps for backup", e);
17114            }
17115            return null;
17116        }
17117
17118        return dataStream.toByteArray();
17119    }
17120
17121    @Override
17122    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17123        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17124            throw new SecurityException("Only the system may call restorePreferredActivities()");
17125        }
17126
17127        try {
17128            final XmlPullParser parser = Xml.newPullParser();
17129            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17130            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17131                    new BlobXmlRestorer() {
17132                        @Override
17133                        public void apply(XmlPullParser parser, int userId)
17134                                throws XmlPullParserException, IOException {
17135                            synchronized (mPackages) {
17136                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17137                                mSettings.writeLPr();
17138                            }
17139                        }
17140                    } );
17141        } catch (Exception e) {
17142            if (DEBUG_BACKUP) {
17143                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17144            }
17145        }
17146    }
17147
17148    @Override
17149    public byte[] getPermissionGrantBackup(int userId) {
17150        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17151            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17152        }
17153
17154        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17155        try {
17156            final XmlSerializer serializer = new FastXmlSerializer();
17157            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17158            serializer.startDocument(null, true);
17159            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17160
17161            synchronized (mPackages) {
17162                serializeRuntimePermissionGrantsLPr(serializer, userId);
17163            }
17164
17165            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17166            serializer.endDocument();
17167            serializer.flush();
17168        } catch (Exception e) {
17169            if (DEBUG_BACKUP) {
17170                Slog.e(TAG, "Unable to write default apps for backup", e);
17171            }
17172            return null;
17173        }
17174
17175        return dataStream.toByteArray();
17176    }
17177
17178    @Override
17179    public void restorePermissionGrants(byte[] backup, int userId) {
17180        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17181            throw new SecurityException("Only the system may call restorePermissionGrants()");
17182        }
17183
17184        try {
17185            final XmlPullParser parser = Xml.newPullParser();
17186            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17187            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17188                    new BlobXmlRestorer() {
17189                        @Override
17190                        public void apply(XmlPullParser parser, int userId)
17191                                throws XmlPullParserException, IOException {
17192                            synchronized (mPackages) {
17193                                processRestoredPermissionGrantsLPr(parser, userId);
17194                            }
17195                        }
17196                    } );
17197        } catch (Exception e) {
17198            if (DEBUG_BACKUP) {
17199                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17200            }
17201        }
17202    }
17203
17204    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17205            throws IOException {
17206        serializer.startTag(null, TAG_ALL_GRANTS);
17207
17208        final int N = mSettings.mPackages.size();
17209        for (int i = 0; i < N; i++) {
17210            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17211            boolean pkgGrantsKnown = false;
17212
17213            PermissionsState packagePerms = ps.getPermissionsState();
17214
17215            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17216                final int grantFlags = state.getFlags();
17217                // only look at grants that are not system/policy fixed
17218                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17219                    final boolean isGranted = state.isGranted();
17220                    // And only back up the user-twiddled state bits
17221                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17222                        final String packageName = mSettings.mPackages.keyAt(i);
17223                        if (!pkgGrantsKnown) {
17224                            serializer.startTag(null, TAG_GRANT);
17225                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17226                            pkgGrantsKnown = true;
17227                        }
17228
17229                        final boolean userSet =
17230                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17231                        final boolean userFixed =
17232                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17233                        final boolean revoke =
17234                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17235
17236                        serializer.startTag(null, TAG_PERMISSION);
17237                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17238                        if (isGranted) {
17239                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17240                        }
17241                        if (userSet) {
17242                            serializer.attribute(null, ATTR_USER_SET, "true");
17243                        }
17244                        if (userFixed) {
17245                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17246                        }
17247                        if (revoke) {
17248                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17249                        }
17250                        serializer.endTag(null, TAG_PERMISSION);
17251                    }
17252                }
17253            }
17254
17255            if (pkgGrantsKnown) {
17256                serializer.endTag(null, TAG_GRANT);
17257            }
17258        }
17259
17260        serializer.endTag(null, TAG_ALL_GRANTS);
17261    }
17262
17263    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17264            throws XmlPullParserException, IOException {
17265        String pkgName = null;
17266        int outerDepth = parser.getDepth();
17267        int type;
17268        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17269                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17270            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17271                continue;
17272            }
17273
17274            final String tagName = parser.getName();
17275            if (tagName.equals(TAG_GRANT)) {
17276                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17277                if (DEBUG_BACKUP) {
17278                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17279                }
17280            } else if (tagName.equals(TAG_PERMISSION)) {
17281
17282                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17283                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17284
17285                int newFlagSet = 0;
17286                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17287                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17288                }
17289                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17290                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17291                }
17292                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17293                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17294                }
17295                if (DEBUG_BACKUP) {
17296                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17297                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17298                }
17299                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17300                if (ps != null) {
17301                    // Already installed so we apply the grant immediately
17302                    if (DEBUG_BACKUP) {
17303                        Slog.v(TAG, "        + already installed; applying");
17304                    }
17305                    PermissionsState perms = ps.getPermissionsState();
17306                    BasePermission bp = mSettings.mPermissions.get(permName);
17307                    if (bp != null) {
17308                        if (isGranted) {
17309                            perms.grantRuntimePermission(bp, userId);
17310                        }
17311                        if (newFlagSet != 0) {
17312                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17313                        }
17314                    }
17315                } else {
17316                    // Need to wait for post-restore install to apply the grant
17317                    if (DEBUG_BACKUP) {
17318                        Slog.v(TAG, "        - not yet installed; saving for later");
17319                    }
17320                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17321                            isGranted, newFlagSet, userId);
17322                }
17323            } else {
17324                PackageManagerService.reportSettingsProblem(Log.WARN,
17325                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17326                XmlUtils.skipCurrentTag(parser);
17327            }
17328        }
17329
17330        scheduleWriteSettingsLocked();
17331        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17332    }
17333
17334    @Override
17335    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17336            int sourceUserId, int targetUserId, int flags) {
17337        mContext.enforceCallingOrSelfPermission(
17338                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17339        int callingUid = Binder.getCallingUid();
17340        enforceOwnerRights(ownerPackage, callingUid);
17341        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17342        if (intentFilter.countActions() == 0) {
17343            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17344            return;
17345        }
17346        synchronized (mPackages) {
17347            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17348                    ownerPackage, targetUserId, flags);
17349            CrossProfileIntentResolver resolver =
17350                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17351            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17352            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17353            if (existing != null) {
17354                int size = existing.size();
17355                for (int i = 0; i < size; i++) {
17356                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17357                        return;
17358                    }
17359                }
17360            }
17361            resolver.addFilter(newFilter);
17362            scheduleWritePackageRestrictionsLocked(sourceUserId);
17363        }
17364    }
17365
17366    @Override
17367    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17368        mContext.enforceCallingOrSelfPermission(
17369                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17370        int callingUid = Binder.getCallingUid();
17371        enforceOwnerRights(ownerPackage, callingUid);
17372        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17373        synchronized (mPackages) {
17374            CrossProfileIntentResolver resolver =
17375                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17376            ArraySet<CrossProfileIntentFilter> set =
17377                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17378            for (CrossProfileIntentFilter filter : set) {
17379                if (filter.getOwnerPackage().equals(ownerPackage)) {
17380                    resolver.removeFilter(filter);
17381                }
17382            }
17383            scheduleWritePackageRestrictionsLocked(sourceUserId);
17384        }
17385    }
17386
17387    // Enforcing that callingUid is owning pkg on userId
17388    private void enforceOwnerRights(String pkg, int callingUid) {
17389        // The system owns everything.
17390        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17391            return;
17392        }
17393        int callingUserId = UserHandle.getUserId(callingUid);
17394        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17395        if (pi == null) {
17396            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17397                    + callingUserId);
17398        }
17399        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17400            throw new SecurityException("Calling uid " + callingUid
17401                    + " does not own package " + pkg);
17402        }
17403    }
17404
17405    @Override
17406    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17407        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17408    }
17409
17410    private Intent getHomeIntent() {
17411        Intent intent = new Intent(Intent.ACTION_MAIN);
17412        intent.addCategory(Intent.CATEGORY_HOME);
17413        return intent;
17414    }
17415
17416    private IntentFilter getHomeFilter() {
17417        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17418        filter.addCategory(Intent.CATEGORY_HOME);
17419        filter.addCategory(Intent.CATEGORY_DEFAULT);
17420        return filter;
17421    }
17422
17423    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17424            int userId) {
17425        Intent intent  = getHomeIntent();
17426        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17427                PackageManager.GET_META_DATA, userId);
17428        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17429                true, false, false, userId);
17430
17431        allHomeCandidates.clear();
17432        if (list != null) {
17433            for (ResolveInfo ri : list) {
17434                allHomeCandidates.add(ri);
17435            }
17436        }
17437        return (preferred == null || preferred.activityInfo == null)
17438                ? null
17439                : new ComponentName(preferred.activityInfo.packageName,
17440                        preferred.activityInfo.name);
17441    }
17442
17443    @Override
17444    public void setHomeActivity(ComponentName comp, int userId) {
17445        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17446        getHomeActivitiesAsUser(homeActivities, userId);
17447
17448        boolean found = false;
17449
17450        final int size = homeActivities.size();
17451        final ComponentName[] set = new ComponentName[size];
17452        for (int i = 0; i < size; i++) {
17453            final ResolveInfo candidate = homeActivities.get(i);
17454            final ActivityInfo info = candidate.activityInfo;
17455            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17456            set[i] = activityName;
17457            if (!found && activityName.equals(comp)) {
17458                found = true;
17459            }
17460        }
17461        if (!found) {
17462            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17463                    + userId);
17464        }
17465        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17466                set, comp, userId);
17467    }
17468
17469    private @Nullable String getSetupWizardPackageName() {
17470        final Intent intent = new Intent(Intent.ACTION_MAIN);
17471        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17472
17473        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17474                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17475                        | MATCH_DISABLED_COMPONENTS,
17476                UserHandle.myUserId());
17477        if (matches.size() == 1) {
17478            return matches.get(0).getComponentInfo().packageName;
17479        } else {
17480            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17481                    + ": matches=" + matches);
17482            return null;
17483        }
17484    }
17485
17486    @Override
17487    public void setApplicationEnabledSetting(String appPackageName,
17488            int newState, int flags, int userId, String callingPackage) {
17489        if (!sUserManager.exists(userId)) return;
17490        if (callingPackage == null) {
17491            callingPackage = Integer.toString(Binder.getCallingUid());
17492        }
17493        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17494    }
17495
17496    @Override
17497    public void setComponentEnabledSetting(ComponentName componentName,
17498            int newState, int flags, int userId) {
17499        if (!sUserManager.exists(userId)) return;
17500        setEnabledSetting(componentName.getPackageName(),
17501                componentName.getClassName(), newState, flags, userId, null);
17502    }
17503
17504    private void setEnabledSetting(final String packageName, String className, int newState,
17505            final int flags, int userId, String callingPackage) {
17506        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17507              || newState == COMPONENT_ENABLED_STATE_ENABLED
17508              || newState == COMPONENT_ENABLED_STATE_DISABLED
17509              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17510              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17511            throw new IllegalArgumentException("Invalid new component state: "
17512                    + newState);
17513        }
17514        PackageSetting pkgSetting;
17515        final int uid = Binder.getCallingUid();
17516        final int permission;
17517        if (uid == Process.SYSTEM_UID) {
17518            permission = PackageManager.PERMISSION_GRANTED;
17519        } else {
17520            permission = mContext.checkCallingOrSelfPermission(
17521                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17522        }
17523        enforceCrossUserPermission(uid, userId,
17524                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17525        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17526        boolean sendNow = false;
17527        boolean isApp = (className == null);
17528        String componentName = isApp ? packageName : className;
17529        int packageUid = -1;
17530        ArrayList<String> components;
17531
17532        // writer
17533        synchronized (mPackages) {
17534            pkgSetting = mSettings.mPackages.get(packageName);
17535            if (pkgSetting == null) {
17536                if (className == null) {
17537                    throw new IllegalArgumentException("Unknown package: " + packageName);
17538                }
17539                throw new IllegalArgumentException(
17540                        "Unknown component: " + packageName + "/" + className);
17541            }
17542        }
17543
17544        // Limit who can change which apps
17545        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17546            // Don't allow apps that don't have permission to modify other apps
17547            if (!allowedByPermission) {
17548                throw new SecurityException(
17549                        "Permission Denial: attempt to change component state from pid="
17550                        + Binder.getCallingPid()
17551                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17552            }
17553            // Don't allow changing profile and device owners. Calling into DPMS, so no locking.
17554            final DevicePolicyManagerInternal dpmi = LocalServices
17555                    .getService(DevicePolicyManagerInternal.class);
17556            if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
17557                throw new SecurityException("Cannot disable a device owner or a profile owner");
17558            }
17559        }
17560
17561        synchronized (mPackages) {
17562            if (uid == Process.SHELL_UID) {
17563                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17564                int oldState = pkgSetting.getEnabled(userId);
17565                if (className == null
17566                    &&
17567                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17568                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17569                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17570                    &&
17571                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17572                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17573                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17574                    // ok
17575                } else {
17576                    throw new SecurityException(
17577                            "Shell cannot change component state for " + packageName + "/"
17578                            + className + " to " + newState);
17579                }
17580            }
17581            if (className == null) {
17582                // We're dealing with an application/package level state change
17583                if (pkgSetting.getEnabled(userId) == newState) {
17584                    // Nothing to do
17585                    return;
17586                }
17587                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17588                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17589                    // Don't care about who enables an app.
17590                    callingPackage = null;
17591                }
17592                pkgSetting.setEnabled(newState, userId, callingPackage);
17593                // pkgSetting.pkg.mSetEnabled = newState;
17594            } else {
17595                // We're dealing with a component level state change
17596                // First, verify that this is a valid class name.
17597                PackageParser.Package pkg = pkgSetting.pkg;
17598                if (pkg == null || !pkg.hasComponentClassName(className)) {
17599                    if (pkg != null &&
17600                            pkg.applicationInfo.targetSdkVersion >=
17601                                    Build.VERSION_CODES.JELLY_BEAN) {
17602                        throw new IllegalArgumentException("Component class " + className
17603                                + " does not exist in " + packageName);
17604                    } else {
17605                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17606                                + className + " does not exist in " + packageName);
17607                    }
17608                }
17609                switch (newState) {
17610                case COMPONENT_ENABLED_STATE_ENABLED:
17611                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17612                        return;
17613                    }
17614                    break;
17615                case COMPONENT_ENABLED_STATE_DISABLED:
17616                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17617                        return;
17618                    }
17619                    break;
17620                case COMPONENT_ENABLED_STATE_DEFAULT:
17621                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17622                        return;
17623                    }
17624                    break;
17625                default:
17626                    Slog.e(TAG, "Invalid new component state: " + newState);
17627                    return;
17628                }
17629            }
17630            scheduleWritePackageRestrictionsLocked(userId);
17631            components = mPendingBroadcasts.get(userId, packageName);
17632            final boolean newPackage = components == null;
17633            if (newPackage) {
17634                components = new ArrayList<String>();
17635            }
17636            if (!components.contains(componentName)) {
17637                components.add(componentName);
17638            }
17639            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17640                sendNow = true;
17641                // Purge entry from pending broadcast list if another one exists already
17642                // since we are sending one right away.
17643                mPendingBroadcasts.remove(userId, packageName);
17644            } else {
17645                if (newPackage) {
17646                    mPendingBroadcasts.put(userId, packageName, components);
17647                }
17648                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17649                    // Schedule a message
17650                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17651                }
17652            }
17653        }
17654
17655        long callingId = Binder.clearCallingIdentity();
17656        try {
17657            if (sendNow) {
17658                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17659                sendPackageChangedBroadcast(packageName,
17660                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17661            }
17662        } finally {
17663            Binder.restoreCallingIdentity(callingId);
17664        }
17665    }
17666
17667    @Override
17668    public void flushPackageRestrictionsAsUser(int userId) {
17669        if (!sUserManager.exists(userId)) {
17670            return;
17671        }
17672        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17673                false /* checkShell */, "flushPackageRestrictions");
17674        synchronized (mPackages) {
17675            mSettings.writePackageRestrictionsLPr(userId);
17676            mDirtyUsers.remove(userId);
17677            if (mDirtyUsers.isEmpty()) {
17678                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17679            }
17680        }
17681    }
17682
17683    private void sendPackageChangedBroadcast(String packageName,
17684            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17685        if (DEBUG_INSTALL)
17686            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17687                    + componentNames);
17688        Bundle extras = new Bundle(4);
17689        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17690        String nameList[] = new String[componentNames.size()];
17691        componentNames.toArray(nameList);
17692        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17693        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17694        extras.putInt(Intent.EXTRA_UID, packageUid);
17695        // If this is not reporting a change of the overall package, then only send it
17696        // to registered receivers.  We don't want to launch a swath of apps for every
17697        // little component state change.
17698        final int flags = !componentNames.contains(packageName)
17699                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17700        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17701                new int[] {UserHandle.getUserId(packageUid)});
17702    }
17703
17704    @Override
17705    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17706        if (!sUserManager.exists(userId)) return;
17707        final int uid = Binder.getCallingUid();
17708        final int permission = mContext.checkCallingOrSelfPermission(
17709                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17710        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17711        enforceCrossUserPermission(uid, userId,
17712                true /* requireFullPermission */, true /* checkShell */, "stop package");
17713        // writer
17714        synchronized (mPackages) {
17715            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17716                    allowedByPermission, uid, userId)) {
17717                scheduleWritePackageRestrictionsLocked(userId);
17718            }
17719        }
17720    }
17721
17722    @Override
17723    public String getInstallerPackageName(String packageName) {
17724        // reader
17725        synchronized (mPackages) {
17726            return mSettings.getInstallerPackageNameLPr(packageName);
17727        }
17728    }
17729
17730    public boolean isOrphaned(String packageName) {
17731        // reader
17732        synchronized (mPackages) {
17733            return mSettings.isOrphaned(packageName);
17734        }
17735    }
17736
17737    @Override
17738    public int getApplicationEnabledSetting(String packageName, int userId) {
17739        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17740        int uid = Binder.getCallingUid();
17741        enforceCrossUserPermission(uid, userId,
17742                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17743        // reader
17744        synchronized (mPackages) {
17745            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17746        }
17747    }
17748
17749    @Override
17750    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17751        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17752        int uid = Binder.getCallingUid();
17753        enforceCrossUserPermission(uid, userId,
17754                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17755        // reader
17756        synchronized (mPackages) {
17757            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17758        }
17759    }
17760
17761    @Override
17762    public void enterSafeMode() {
17763        enforceSystemOrRoot("Only the system can request entering safe mode");
17764
17765        if (!mSystemReady) {
17766            mSafeMode = true;
17767        }
17768    }
17769
17770    @Override
17771    public void systemReady() {
17772        mSystemReady = true;
17773
17774        // Read the compatibilty setting when the system is ready.
17775        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17776                mContext.getContentResolver(),
17777                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17778        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17779        if (DEBUG_SETTINGS) {
17780            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17781        }
17782
17783        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17784
17785        synchronized (mPackages) {
17786            // Verify that all of the preferred activity components actually
17787            // exist.  It is possible for applications to be updated and at
17788            // that point remove a previously declared activity component that
17789            // had been set as a preferred activity.  We try to clean this up
17790            // the next time we encounter that preferred activity, but it is
17791            // possible for the user flow to never be able to return to that
17792            // situation so here we do a sanity check to make sure we haven't
17793            // left any junk around.
17794            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17795            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17796                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17797                removed.clear();
17798                for (PreferredActivity pa : pir.filterSet()) {
17799                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17800                        removed.add(pa);
17801                    }
17802                }
17803                if (removed.size() > 0) {
17804                    for (int r=0; r<removed.size(); r++) {
17805                        PreferredActivity pa = removed.get(r);
17806                        Slog.w(TAG, "Removing dangling preferred activity: "
17807                                + pa.mPref.mComponent);
17808                        pir.removeFilter(pa);
17809                    }
17810                    mSettings.writePackageRestrictionsLPr(
17811                            mSettings.mPreferredActivities.keyAt(i));
17812                }
17813            }
17814
17815            for (int userId : UserManagerService.getInstance().getUserIds()) {
17816                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17817                    grantPermissionsUserIds = ArrayUtils.appendInt(
17818                            grantPermissionsUserIds, userId);
17819                }
17820            }
17821        }
17822        sUserManager.systemReady();
17823
17824        // If we upgraded grant all default permissions before kicking off.
17825        for (int userId : grantPermissionsUserIds) {
17826            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17827        }
17828
17829        // Kick off any messages waiting for system ready
17830        if (mPostSystemReadyMessages != null) {
17831            for (Message msg : mPostSystemReadyMessages) {
17832                msg.sendToTarget();
17833            }
17834            mPostSystemReadyMessages = null;
17835        }
17836
17837        // Watch for external volumes that come and go over time
17838        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17839        storage.registerListener(mStorageListener);
17840
17841        mInstallerService.systemReady();
17842        mPackageDexOptimizer.systemReady();
17843
17844        MountServiceInternal mountServiceInternal = LocalServices.getService(
17845                MountServiceInternal.class);
17846        mountServiceInternal.addExternalStoragePolicy(
17847                new MountServiceInternal.ExternalStorageMountPolicy() {
17848            @Override
17849            public int getMountMode(int uid, String packageName) {
17850                if (Process.isIsolated(uid)) {
17851                    return Zygote.MOUNT_EXTERNAL_NONE;
17852                }
17853                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17854                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17855                }
17856                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17857                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17858                }
17859                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17860                    return Zygote.MOUNT_EXTERNAL_READ;
17861                }
17862                return Zygote.MOUNT_EXTERNAL_WRITE;
17863            }
17864
17865            @Override
17866            public boolean hasExternalStorage(int uid, String packageName) {
17867                return true;
17868            }
17869        });
17870
17871        // Now that we're mostly running, clean up stale users and apps
17872        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17873        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17874    }
17875
17876    @Override
17877    public boolean isSafeMode() {
17878        return mSafeMode;
17879    }
17880
17881    @Override
17882    public boolean hasSystemUidErrors() {
17883        return mHasSystemUidErrors;
17884    }
17885
17886    static String arrayToString(int[] array) {
17887        StringBuffer buf = new StringBuffer(128);
17888        buf.append('[');
17889        if (array != null) {
17890            for (int i=0; i<array.length; i++) {
17891                if (i > 0) buf.append(", ");
17892                buf.append(array[i]);
17893            }
17894        }
17895        buf.append(']');
17896        return buf.toString();
17897    }
17898
17899    static class DumpState {
17900        public static final int DUMP_LIBS = 1 << 0;
17901        public static final int DUMP_FEATURES = 1 << 1;
17902        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17903        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17904        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17905        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17906        public static final int DUMP_PERMISSIONS = 1 << 6;
17907        public static final int DUMP_PACKAGES = 1 << 7;
17908        public static final int DUMP_SHARED_USERS = 1 << 8;
17909        public static final int DUMP_MESSAGES = 1 << 9;
17910        public static final int DUMP_PROVIDERS = 1 << 10;
17911        public static final int DUMP_VERIFIERS = 1 << 11;
17912        public static final int DUMP_PREFERRED = 1 << 12;
17913        public static final int DUMP_PREFERRED_XML = 1 << 13;
17914        public static final int DUMP_KEYSETS = 1 << 14;
17915        public static final int DUMP_VERSION = 1 << 15;
17916        public static final int DUMP_INSTALLS = 1 << 16;
17917        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17918        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17919        public static final int DUMP_FROZEN = 1 << 19;
17920        public static final int DUMP_DEXOPT = 1 << 20;
17921
17922        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17923
17924        private int mTypes;
17925
17926        private int mOptions;
17927
17928        private boolean mTitlePrinted;
17929
17930        private SharedUserSetting mSharedUser;
17931
17932        public boolean isDumping(int type) {
17933            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17934                return true;
17935            }
17936
17937            return (mTypes & type) != 0;
17938        }
17939
17940        public void setDump(int type) {
17941            mTypes |= type;
17942        }
17943
17944        public boolean isOptionEnabled(int option) {
17945            return (mOptions & option) != 0;
17946        }
17947
17948        public void setOptionEnabled(int option) {
17949            mOptions |= option;
17950        }
17951
17952        public boolean onTitlePrinted() {
17953            final boolean printed = mTitlePrinted;
17954            mTitlePrinted = true;
17955            return printed;
17956        }
17957
17958        public boolean getTitlePrinted() {
17959            return mTitlePrinted;
17960        }
17961
17962        public void setTitlePrinted(boolean enabled) {
17963            mTitlePrinted = enabled;
17964        }
17965
17966        public SharedUserSetting getSharedUser() {
17967            return mSharedUser;
17968        }
17969
17970        public void setSharedUser(SharedUserSetting user) {
17971            mSharedUser = user;
17972        }
17973    }
17974
17975    @Override
17976    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17977            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17978        (new PackageManagerShellCommand(this)).exec(
17979                this, in, out, err, args, resultReceiver);
17980    }
17981
17982    @Override
17983    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17984        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17985                != PackageManager.PERMISSION_GRANTED) {
17986            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17987                    + Binder.getCallingPid()
17988                    + ", uid=" + Binder.getCallingUid()
17989                    + " without permission "
17990                    + android.Manifest.permission.DUMP);
17991            return;
17992        }
17993
17994        DumpState dumpState = new DumpState();
17995        boolean fullPreferred = false;
17996        boolean checkin = false;
17997
17998        String packageName = null;
17999        ArraySet<String> permissionNames = null;
18000
18001        int opti = 0;
18002        while (opti < args.length) {
18003            String opt = args[opti];
18004            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18005                break;
18006            }
18007            opti++;
18008
18009            if ("-a".equals(opt)) {
18010                // Right now we only know how to print all.
18011            } else if ("-h".equals(opt)) {
18012                pw.println("Package manager dump options:");
18013                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18014                pw.println("    --checkin: dump for a checkin");
18015                pw.println("    -f: print details of intent filters");
18016                pw.println("    -h: print this help");
18017                pw.println("  cmd may be one of:");
18018                pw.println("    l[ibraries]: list known shared libraries");
18019                pw.println("    f[eatures]: list device features");
18020                pw.println("    k[eysets]: print known keysets");
18021                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18022                pw.println("    perm[issions]: dump permissions");
18023                pw.println("    permission [name ...]: dump declaration and use of given permission");
18024                pw.println("    pref[erred]: print preferred package settings");
18025                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18026                pw.println("    prov[iders]: dump content providers");
18027                pw.println("    p[ackages]: dump installed packages");
18028                pw.println("    s[hared-users]: dump shared user IDs");
18029                pw.println("    m[essages]: print collected runtime messages");
18030                pw.println("    v[erifiers]: print package verifier info");
18031                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18032                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18033                pw.println("    version: print database version info");
18034                pw.println("    write: write current settings now");
18035                pw.println("    installs: details about install sessions");
18036                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18037                pw.println("    dexopt: dump dexopt state");
18038                pw.println("    <package.name>: info about given package");
18039                return;
18040            } else if ("--checkin".equals(opt)) {
18041                checkin = true;
18042            } else if ("-f".equals(opt)) {
18043                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18044            } else {
18045                pw.println("Unknown argument: " + opt + "; use -h for help");
18046            }
18047        }
18048
18049        // Is the caller requesting to dump a particular piece of data?
18050        if (opti < args.length) {
18051            String cmd = args[opti];
18052            opti++;
18053            // Is this a package name?
18054            if ("android".equals(cmd) || cmd.contains(".")) {
18055                packageName = cmd;
18056                // When dumping a single package, we always dump all of its
18057                // filter information since the amount of data will be reasonable.
18058                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18059            } else if ("check-permission".equals(cmd)) {
18060                if (opti >= args.length) {
18061                    pw.println("Error: check-permission missing permission argument");
18062                    return;
18063                }
18064                String perm = args[opti];
18065                opti++;
18066                if (opti >= args.length) {
18067                    pw.println("Error: check-permission missing package argument");
18068                    return;
18069                }
18070                String pkg = args[opti];
18071                opti++;
18072                int user = UserHandle.getUserId(Binder.getCallingUid());
18073                if (opti < args.length) {
18074                    try {
18075                        user = Integer.parseInt(args[opti]);
18076                    } catch (NumberFormatException e) {
18077                        pw.println("Error: check-permission user argument is not a number: "
18078                                + args[opti]);
18079                        return;
18080                    }
18081                }
18082                pw.println(checkPermission(perm, pkg, user));
18083                return;
18084            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18085                dumpState.setDump(DumpState.DUMP_LIBS);
18086            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18087                dumpState.setDump(DumpState.DUMP_FEATURES);
18088            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18089                if (opti >= args.length) {
18090                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18091                            | DumpState.DUMP_SERVICE_RESOLVERS
18092                            | DumpState.DUMP_RECEIVER_RESOLVERS
18093                            | DumpState.DUMP_CONTENT_RESOLVERS);
18094                } else {
18095                    while (opti < args.length) {
18096                        String name = args[opti];
18097                        if ("a".equals(name) || "activity".equals(name)) {
18098                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18099                        } else if ("s".equals(name) || "service".equals(name)) {
18100                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18101                        } else if ("r".equals(name) || "receiver".equals(name)) {
18102                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18103                        } else if ("c".equals(name) || "content".equals(name)) {
18104                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18105                        } else {
18106                            pw.println("Error: unknown resolver table type: " + name);
18107                            return;
18108                        }
18109                        opti++;
18110                    }
18111                }
18112            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18113                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18114            } else if ("permission".equals(cmd)) {
18115                if (opti >= args.length) {
18116                    pw.println("Error: permission requires permission name");
18117                    return;
18118                }
18119                permissionNames = new ArraySet<>();
18120                while (opti < args.length) {
18121                    permissionNames.add(args[opti]);
18122                    opti++;
18123                }
18124                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18125                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18126            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18127                dumpState.setDump(DumpState.DUMP_PREFERRED);
18128            } else if ("preferred-xml".equals(cmd)) {
18129                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18130                if (opti < args.length && "--full".equals(args[opti])) {
18131                    fullPreferred = true;
18132                    opti++;
18133                }
18134            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18135                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18136            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18137                dumpState.setDump(DumpState.DUMP_PACKAGES);
18138            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18139                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18140            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18141                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18142            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18143                dumpState.setDump(DumpState.DUMP_MESSAGES);
18144            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18145                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18146            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18147                    || "intent-filter-verifiers".equals(cmd)) {
18148                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18149            } else if ("version".equals(cmd)) {
18150                dumpState.setDump(DumpState.DUMP_VERSION);
18151            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18152                dumpState.setDump(DumpState.DUMP_KEYSETS);
18153            } else if ("installs".equals(cmd)) {
18154                dumpState.setDump(DumpState.DUMP_INSTALLS);
18155            } else if ("frozen".equals(cmd)) {
18156                dumpState.setDump(DumpState.DUMP_FROZEN);
18157            } else if ("dexopt".equals(cmd)) {
18158                dumpState.setDump(DumpState.DUMP_DEXOPT);
18159            } else if ("write".equals(cmd)) {
18160                synchronized (mPackages) {
18161                    mSettings.writeLPr();
18162                    pw.println("Settings written.");
18163                    return;
18164                }
18165            }
18166        }
18167
18168        if (checkin) {
18169            pw.println("vers,1");
18170        }
18171
18172        // reader
18173        synchronized (mPackages) {
18174            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18175                if (!checkin) {
18176                    if (dumpState.onTitlePrinted())
18177                        pw.println();
18178                    pw.println("Database versions:");
18179                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18180                }
18181            }
18182
18183            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18184                if (!checkin) {
18185                    if (dumpState.onTitlePrinted())
18186                        pw.println();
18187                    pw.println("Verifiers:");
18188                    pw.print("  Required: ");
18189                    pw.print(mRequiredVerifierPackage);
18190                    pw.print(" (uid=");
18191                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18192                            UserHandle.USER_SYSTEM));
18193                    pw.println(")");
18194                } else if (mRequiredVerifierPackage != null) {
18195                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18196                    pw.print(",");
18197                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18198                            UserHandle.USER_SYSTEM));
18199                }
18200            }
18201
18202            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18203                    packageName == null) {
18204                if (mIntentFilterVerifierComponent != null) {
18205                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18206                    if (!checkin) {
18207                        if (dumpState.onTitlePrinted())
18208                            pw.println();
18209                        pw.println("Intent Filter Verifier:");
18210                        pw.print("  Using: ");
18211                        pw.print(verifierPackageName);
18212                        pw.print(" (uid=");
18213                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18214                                UserHandle.USER_SYSTEM));
18215                        pw.println(")");
18216                    } else if (verifierPackageName != null) {
18217                        pw.print("ifv,"); pw.print(verifierPackageName);
18218                        pw.print(",");
18219                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18220                                UserHandle.USER_SYSTEM));
18221                    }
18222                } else {
18223                    pw.println();
18224                    pw.println("No Intent Filter Verifier available!");
18225                }
18226            }
18227
18228            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18229                boolean printedHeader = false;
18230                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18231                while (it.hasNext()) {
18232                    String name = it.next();
18233                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18234                    if (!checkin) {
18235                        if (!printedHeader) {
18236                            if (dumpState.onTitlePrinted())
18237                                pw.println();
18238                            pw.println("Libraries:");
18239                            printedHeader = true;
18240                        }
18241                        pw.print("  ");
18242                    } else {
18243                        pw.print("lib,");
18244                    }
18245                    pw.print(name);
18246                    if (!checkin) {
18247                        pw.print(" -> ");
18248                    }
18249                    if (ent.path != null) {
18250                        if (!checkin) {
18251                            pw.print("(jar) ");
18252                            pw.print(ent.path);
18253                        } else {
18254                            pw.print(",jar,");
18255                            pw.print(ent.path);
18256                        }
18257                    } else {
18258                        if (!checkin) {
18259                            pw.print("(apk) ");
18260                            pw.print(ent.apk);
18261                        } else {
18262                            pw.print(",apk,");
18263                            pw.print(ent.apk);
18264                        }
18265                    }
18266                    pw.println();
18267                }
18268            }
18269
18270            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18271                if (dumpState.onTitlePrinted())
18272                    pw.println();
18273                if (!checkin) {
18274                    pw.println("Features:");
18275                }
18276
18277                for (FeatureInfo feat : mAvailableFeatures.values()) {
18278                    if (checkin) {
18279                        pw.print("feat,");
18280                        pw.print(feat.name);
18281                        pw.print(",");
18282                        pw.println(feat.version);
18283                    } else {
18284                        pw.print("  ");
18285                        pw.print(feat.name);
18286                        if (feat.version > 0) {
18287                            pw.print(" version=");
18288                            pw.print(feat.version);
18289                        }
18290                        pw.println();
18291                    }
18292                }
18293            }
18294
18295            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18296                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18297                        : "Activity Resolver Table:", "  ", packageName,
18298                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18299                    dumpState.setTitlePrinted(true);
18300                }
18301            }
18302            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18303                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18304                        : "Receiver Resolver Table:", "  ", packageName,
18305                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18306                    dumpState.setTitlePrinted(true);
18307                }
18308            }
18309            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18310                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18311                        : "Service Resolver Table:", "  ", packageName,
18312                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18313                    dumpState.setTitlePrinted(true);
18314                }
18315            }
18316            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18317                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18318                        : "Provider Resolver Table:", "  ", packageName,
18319                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18320                    dumpState.setTitlePrinted(true);
18321                }
18322            }
18323
18324            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18325                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18326                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18327                    int user = mSettings.mPreferredActivities.keyAt(i);
18328                    if (pir.dump(pw,
18329                            dumpState.getTitlePrinted()
18330                                ? "\nPreferred Activities User " + user + ":"
18331                                : "Preferred Activities User " + user + ":", "  ",
18332                            packageName, true, false)) {
18333                        dumpState.setTitlePrinted(true);
18334                    }
18335                }
18336            }
18337
18338            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18339                pw.flush();
18340                FileOutputStream fout = new FileOutputStream(fd);
18341                BufferedOutputStream str = new BufferedOutputStream(fout);
18342                XmlSerializer serializer = new FastXmlSerializer();
18343                try {
18344                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18345                    serializer.startDocument(null, true);
18346                    serializer.setFeature(
18347                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18348                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18349                    serializer.endDocument();
18350                    serializer.flush();
18351                } catch (IllegalArgumentException e) {
18352                    pw.println("Failed writing: " + e);
18353                } catch (IllegalStateException e) {
18354                    pw.println("Failed writing: " + e);
18355                } catch (IOException e) {
18356                    pw.println("Failed writing: " + e);
18357                }
18358            }
18359
18360            if (!checkin
18361                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18362                    && packageName == null) {
18363                pw.println();
18364                int count = mSettings.mPackages.size();
18365                if (count == 0) {
18366                    pw.println("No applications!");
18367                    pw.println();
18368                } else {
18369                    final String prefix = "  ";
18370                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18371                    if (allPackageSettings.size() == 0) {
18372                        pw.println("No domain preferred apps!");
18373                        pw.println();
18374                    } else {
18375                        pw.println("App verification status:");
18376                        pw.println();
18377                        count = 0;
18378                        for (PackageSetting ps : allPackageSettings) {
18379                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18380                            if (ivi == null || ivi.getPackageName() == null) continue;
18381                            pw.println(prefix + "Package: " + ivi.getPackageName());
18382                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18383                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18384                            pw.println();
18385                            count++;
18386                        }
18387                        if (count == 0) {
18388                            pw.println(prefix + "No app verification established.");
18389                            pw.println();
18390                        }
18391                        for (int userId : sUserManager.getUserIds()) {
18392                            pw.println("App linkages for user " + userId + ":");
18393                            pw.println();
18394                            count = 0;
18395                            for (PackageSetting ps : allPackageSettings) {
18396                                final long status = ps.getDomainVerificationStatusForUser(userId);
18397                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18398                                    continue;
18399                                }
18400                                pw.println(prefix + "Package: " + ps.name);
18401                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18402                                String statusStr = IntentFilterVerificationInfo.
18403                                        getStatusStringFromValue(status);
18404                                pw.println(prefix + "Status:  " + statusStr);
18405                                pw.println();
18406                                count++;
18407                            }
18408                            if (count == 0) {
18409                                pw.println(prefix + "No configured app linkages.");
18410                                pw.println();
18411                            }
18412                        }
18413                    }
18414                }
18415            }
18416
18417            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18418                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18419                if (packageName == null && permissionNames == null) {
18420                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18421                        if (iperm == 0) {
18422                            if (dumpState.onTitlePrinted())
18423                                pw.println();
18424                            pw.println("AppOp Permissions:");
18425                        }
18426                        pw.print("  AppOp Permission ");
18427                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18428                        pw.println(":");
18429                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18430                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18431                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18432                        }
18433                    }
18434                }
18435            }
18436
18437            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18438                boolean printedSomething = false;
18439                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18440                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18441                        continue;
18442                    }
18443                    if (!printedSomething) {
18444                        if (dumpState.onTitlePrinted())
18445                            pw.println();
18446                        pw.println("Registered ContentProviders:");
18447                        printedSomething = true;
18448                    }
18449                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18450                    pw.print("    "); pw.println(p.toString());
18451                }
18452                printedSomething = false;
18453                for (Map.Entry<String, PackageParser.Provider> entry :
18454                        mProvidersByAuthority.entrySet()) {
18455                    PackageParser.Provider p = entry.getValue();
18456                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18457                        continue;
18458                    }
18459                    if (!printedSomething) {
18460                        if (dumpState.onTitlePrinted())
18461                            pw.println();
18462                        pw.println("ContentProvider Authorities:");
18463                        printedSomething = true;
18464                    }
18465                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18466                    pw.print("    "); pw.println(p.toString());
18467                    if (p.info != null && p.info.applicationInfo != null) {
18468                        final String appInfo = p.info.applicationInfo.toString();
18469                        pw.print("      applicationInfo="); pw.println(appInfo);
18470                    }
18471                }
18472            }
18473
18474            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18475                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18476            }
18477
18478            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18479                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18480            }
18481
18482            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18483                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18484            }
18485
18486            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18487                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18488            }
18489
18490            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18491                // XXX should handle packageName != null by dumping only install data that
18492                // the given package is involved with.
18493                if (dumpState.onTitlePrinted()) pw.println();
18494                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18495            }
18496
18497            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18498                // XXX should handle packageName != null by dumping only install data that
18499                // the given package is involved with.
18500                if (dumpState.onTitlePrinted()) pw.println();
18501
18502                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18503                ipw.println();
18504                ipw.println("Frozen packages:");
18505                ipw.increaseIndent();
18506                if (mFrozenPackages.size() == 0) {
18507                    ipw.println("(none)");
18508                } else {
18509                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18510                        ipw.println(mFrozenPackages.valueAt(i));
18511                    }
18512                }
18513                ipw.decreaseIndent();
18514            }
18515
18516            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18517                if (dumpState.onTitlePrinted()) pw.println();
18518                dumpDexoptStateLPr(pw, packageName);
18519            }
18520
18521            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18522                if (dumpState.onTitlePrinted()) pw.println();
18523                mSettings.dumpReadMessagesLPr(pw, dumpState);
18524
18525                pw.println();
18526                pw.println("Package warning messages:");
18527                BufferedReader in = null;
18528                String line = null;
18529                try {
18530                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18531                    while ((line = in.readLine()) != null) {
18532                        if (line.contains("ignored: updated version")) continue;
18533                        pw.println(line);
18534                    }
18535                } catch (IOException ignored) {
18536                } finally {
18537                    IoUtils.closeQuietly(in);
18538                }
18539            }
18540
18541            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18542                BufferedReader in = null;
18543                String line = null;
18544                try {
18545                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18546                    while ((line = in.readLine()) != null) {
18547                        if (line.contains("ignored: updated version")) continue;
18548                        pw.print("msg,");
18549                        pw.println(line);
18550                    }
18551                } catch (IOException ignored) {
18552                } finally {
18553                    IoUtils.closeQuietly(in);
18554                }
18555            }
18556        }
18557    }
18558
18559    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18560        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18561        ipw.println();
18562        ipw.println("Dexopt state:");
18563        ipw.increaseIndent();
18564        Collection<PackageParser.Package> packages = null;
18565        if (packageName != null) {
18566            PackageParser.Package targetPackage = mPackages.get(packageName);
18567            if (targetPackage != null) {
18568                packages = Collections.singletonList(targetPackage);
18569            } else {
18570                ipw.println("Unable to find package: " + packageName);
18571                return;
18572            }
18573        } else {
18574            packages = mPackages.values();
18575        }
18576
18577        for (PackageParser.Package pkg : packages) {
18578            ipw.println("[" + pkg.packageName + "]");
18579            ipw.increaseIndent();
18580            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18581            ipw.decreaseIndent();
18582        }
18583    }
18584
18585    private String dumpDomainString(String packageName) {
18586        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18587                .getList();
18588        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18589
18590        ArraySet<String> result = new ArraySet<>();
18591        if (iviList.size() > 0) {
18592            for (IntentFilterVerificationInfo ivi : iviList) {
18593                for (String host : ivi.getDomains()) {
18594                    result.add(host);
18595                }
18596            }
18597        }
18598        if (filters != null && filters.size() > 0) {
18599            for (IntentFilter filter : filters) {
18600                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18601                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18602                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18603                    result.addAll(filter.getHostsList());
18604                }
18605            }
18606        }
18607
18608        StringBuilder sb = new StringBuilder(result.size() * 16);
18609        for (String domain : result) {
18610            if (sb.length() > 0) sb.append(" ");
18611            sb.append(domain);
18612        }
18613        return sb.toString();
18614    }
18615
18616    // ------- apps on sdcard specific code -------
18617    static final boolean DEBUG_SD_INSTALL = false;
18618
18619    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18620
18621    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18622
18623    private boolean mMediaMounted = false;
18624
18625    static String getEncryptKey() {
18626        try {
18627            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18628                    SD_ENCRYPTION_KEYSTORE_NAME);
18629            if (sdEncKey == null) {
18630                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18631                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18632                if (sdEncKey == null) {
18633                    Slog.e(TAG, "Failed to create encryption keys");
18634                    return null;
18635                }
18636            }
18637            return sdEncKey;
18638        } catch (NoSuchAlgorithmException nsae) {
18639            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18640            return null;
18641        } catch (IOException ioe) {
18642            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18643            return null;
18644        }
18645    }
18646
18647    /*
18648     * Update media status on PackageManager.
18649     */
18650    @Override
18651    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18652        int callingUid = Binder.getCallingUid();
18653        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18654            throw new SecurityException("Media status can only be updated by the system");
18655        }
18656        // reader; this apparently protects mMediaMounted, but should probably
18657        // be a different lock in that case.
18658        synchronized (mPackages) {
18659            Log.i(TAG, "Updating external media status from "
18660                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18661                    + (mediaStatus ? "mounted" : "unmounted"));
18662            if (DEBUG_SD_INSTALL)
18663                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18664                        + ", mMediaMounted=" + mMediaMounted);
18665            if (mediaStatus == mMediaMounted) {
18666                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18667                        : 0, -1);
18668                mHandler.sendMessage(msg);
18669                return;
18670            }
18671            mMediaMounted = mediaStatus;
18672        }
18673        // Queue up an async operation since the package installation may take a
18674        // little while.
18675        mHandler.post(new Runnable() {
18676            public void run() {
18677                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18678            }
18679        });
18680    }
18681
18682    /**
18683     * Called by MountService when the initial ASECs to scan are available.
18684     * Should block until all the ASEC containers are finished being scanned.
18685     */
18686    public void scanAvailableAsecs() {
18687        updateExternalMediaStatusInner(true, false, false);
18688    }
18689
18690    /*
18691     * Collect information of applications on external media, map them against
18692     * existing containers and update information based on current mount status.
18693     * Please note that we always have to report status if reportStatus has been
18694     * set to true especially when unloading packages.
18695     */
18696    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18697            boolean externalStorage) {
18698        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18699        int[] uidArr = EmptyArray.INT;
18700
18701        final String[] list = PackageHelper.getSecureContainerList();
18702        if (ArrayUtils.isEmpty(list)) {
18703            Log.i(TAG, "No secure containers found");
18704        } else {
18705            // Process list of secure containers and categorize them
18706            // as active or stale based on their package internal state.
18707
18708            // reader
18709            synchronized (mPackages) {
18710                for (String cid : list) {
18711                    // Leave stages untouched for now; installer service owns them
18712                    if (PackageInstallerService.isStageName(cid)) continue;
18713
18714                    if (DEBUG_SD_INSTALL)
18715                        Log.i(TAG, "Processing container " + cid);
18716                    String pkgName = getAsecPackageName(cid);
18717                    if (pkgName == null) {
18718                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18719                        continue;
18720                    }
18721                    if (DEBUG_SD_INSTALL)
18722                        Log.i(TAG, "Looking for pkg : " + pkgName);
18723
18724                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18725                    if (ps == null) {
18726                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18727                        continue;
18728                    }
18729
18730                    /*
18731                     * Skip packages that are not external if we're unmounting
18732                     * external storage.
18733                     */
18734                    if (externalStorage && !isMounted && !isExternal(ps)) {
18735                        continue;
18736                    }
18737
18738                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18739                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18740                    // The package status is changed only if the code path
18741                    // matches between settings and the container id.
18742                    if (ps.codePathString != null
18743                            && ps.codePathString.startsWith(args.getCodePath())) {
18744                        if (DEBUG_SD_INSTALL) {
18745                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18746                                    + " at code path: " + ps.codePathString);
18747                        }
18748
18749                        // We do have a valid package installed on sdcard
18750                        processCids.put(args, ps.codePathString);
18751                        final int uid = ps.appId;
18752                        if (uid != -1) {
18753                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18754                        }
18755                    } else {
18756                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18757                                + ps.codePathString);
18758                    }
18759                }
18760            }
18761
18762            Arrays.sort(uidArr);
18763        }
18764
18765        // Process packages with valid entries.
18766        if (isMounted) {
18767            if (DEBUG_SD_INSTALL)
18768                Log.i(TAG, "Loading packages");
18769            loadMediaPackages(processCids, uidArr, externalStorage);
18770            startCleaningPackages();
18771            mInstallerService.onSecureContainersAvailable();
18772        } else {
18773            if (DEBUG_SD_INSTALL)
18774                Log.i(TAG, "Unloading packages");
18775            unloadMediaPackages(processCids, uidArr, reportStatus);
18776        }
18777    }
18778
18779    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18780            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18781        final int size = infos.size();
18782        final String[] packageNames = new String[size];
18783        final int[] packageUids = new int[size];
18784        for (int i = 0; i < size; i++) {
18785            final ApplicationInfo info = infos.get(i);
18786            packageNames[i] = info.packageName;
18787            packageUids[i] = info.uid;
18788        }
18789        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18790                finishedReceiver);
18791    }
18792
18793    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18794            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18795        sendResourcesChangedBroadcast(mediaStatus, replacing,
18796                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18797    }
18798
18799    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18800            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18801        int size = pkgList.length;
18802        if (size > 0) {
18803            // Send broadcasts here
18804            Bundle extras = new Bundle();
18805            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18806            if (uidArr != null) {
18807                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18808            }
18809            if (replacing) {
18810                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18811            }
18812            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18813                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18814            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18815        }
18816    }
18817
18818   /*
18819     * Look at potentially valid container ids from processCids If package
18820     * information doesn't match the one on record or package scanning fails,
18821     * the cid is added to list of removeCids. We currently don't delete stale
18822     * containers.
18823     */
18824    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18825            boolean externalStorage) {
18826        ArrayList<String> pkgList = new ArrayList<String>();
18827        Set<AsecInstallArgs> keys = processCids.keySet();
18828
18829        for (AsecInstallArgs args : keys) {
18830            String codePath = processCids.get(args);
18831            if (DEBUG_SD_INSTALL)
18832                Log.i(TAG, "Loading container : " + args.cid);
18833            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18834            try {
18835                // Make sure there are no container errors first.
18836                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18837                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18838                            + " when installing from sdcard");
18839                    continue;
18840                }
18841                // Check code path here.
18842                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18843                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18844                            + " does not match one in settings " + codePath);
18845                    continue;
18846                }
18847                // Parse package
18848                int parseFlags = mDefParseFlags;
18849                if (args.isExternalAsec()) {
18850                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18851                }
18852                if (args.isFwdLocked()) {
18853                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18854                }
18855
18856                synchronized (mInstallLock) {
18857                    PackageParser.Package pkg = null;
18858                    try {
18859                        // Sadly we don't know the package name yet to freeze it
18860                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18861                                SCAN_IGNORE_FROZEN, 0, null);
18862                    } catch (PackageManagerException e) {
18863                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18864                    }
18865                    // Scan the package
18866                    if (pkg != null) {
18867                        /*
18868                         * TODO why is the lock being held? doPostInstall is
18869                         * called in other places without the lock. This needs
18870                         * to be straightened out.
18871                         */
18872                        // writer
18873                        synchronized (mPackages) {
18874                            retCode = PackageManager.INSTALL_SUCCEEDED;
18875                            pkgList.add(pkg.packageName);
18876                            // Post process args
18877                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18878                                    pkg.applicationInfo.uid);
18879                        }
18880                    } else {
18881                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18882                    }
18883                }
18884
18885            } finally {
18886                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18887                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18888                }
18889            }
18890        }
18891        // writer
18892        synchronized (mPackages) {
18893            // If the platform SDK has changed since the last time we booted,
18894            // we need to re-grant app permission to catch any new ones that
18895            // appear. This is really a hack, and means that apps can in some
18896            // cases get permissions that the user didn't initially explicitly
18897            // allow... it would be nice to have some better way to handle
18898            // this situation.
18899            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18900                    : mSettings.getInternalVersion();
18901            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18902                    : StorageManager.UUID_PRIVATE_INTERNAL;
18903
18904            int updateFlags = UPDATE_PERMISSIONS_ALL;
18905            if (ver.sdkVersion != mSdkVersion) {
18906                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18907                        + mSdkVersion + "; regranting permissions for external");
18908                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18909            }
18910            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18911
18912            // Yay, everything is now upgraded
18913            ver.forceCurrent();
18914
18915            // can downgrade to reader
18916            // Persist settings
18917            mSettings.writeLPr();
18918        }
18919        // Send a broadcast to let everyone know we are done processing
18920        if (pkgList.size() > 0) {
18921            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18922        }
18923    }
18924
18925   /*
18926     * Utility method to unload a list of specified containers
18927     */
18928    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18929        // Just unmount all valid containers.
18930        for (AsecInstallArgs arg : cidArgs) {
18931            synchronized (mInstallLock) {
18932                arg.doPostDeleteLI(false);
18933           }
18934       }
18935   }
18936
18937    /*
18938     * Unload packages mounted on external media. This involves deleting package
18939     * data from internal structures, sending broadcasts about disabled packages,
18940     * gc'ing to free up references, unmounting all secure containers
18941     * corresponding to packages on external media, and posting a
18942     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18943     * that we always have to post this message if status has been requested no
18944     * matter what.
18945     */
18946    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18947            final boolean reportStatus) {
18948        if (DEBUG_SD_INSTALL)
18949            Log.i(TAG, "unloading media packages");
18950        ArrayList<String> pkgList = new ArrayList<String>();
18951        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18952        final Set<AsecInstallArgs> keys = processCids.keySet();
18953        for (AsecInstallArgs args : keys) {
18954            String pkgName = args.getPackageName();
18955            if (DEBUG_SD_INSTALL)
18956                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18957            // Delete package internally
18958            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18959            synchronized (mInstallLock) {
18960                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18961                final boolean res;
18962                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18963                        "unloadMediaPackages")) {
18964                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18965                            null);
18966                }
18967                if (res) {
18968                    pkgList.add(pkgName);
18969                } else {
18970                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18971                    failedList.add(args);
18972                }
18973            }
18974        }
18975
18976        // reader
18977        synchronized (mPackages) {
18978            // We didn't update the settings after removing each package;
18979            // write them now for all packages.
18980            mSettings.writeLPr();
18981        }
18982
18983        // We have to absolutely send UPDATED_MEDIA_STATUS only
18984        // after confirming that all the receivers processed the ordered
18985        // broadcast when packages get disabled, force a gc to clean things up.
18986        // and unload all the containers.
18987        if (pkgList.size() > 0) {
18988            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18989                    new IIntentReceiver.Stub() {
18990                public void performReceive(Intent intent, int resultCode, String data,
18991                        Bundle extras, boolean ordered, boolean sticky,
18992                        int sendingUser) throws RemoteException {
18993                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18994                            reportStatus ? 1 : 0, 1, keys);
18995                    mHandler.sendMessage(msg);
18996                }
18997            });
18998        } else {
18999            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19000                    keys);
19001            mHandler.sendMessage(msg);
19002        }
19003    }
19004
19005    private void loadPrivatePackages(final VolumeInfo vol) {
19006        mHandler.post(new Runnable() {
19007            @Override
19008            public void run() {
19009                loadPrivatePackagesInner(vol);
19010            }
19011        });
19012    }
19013
19014    private void loadPrivatePackagesInner(VolumeInfo vol) {
19015        final String volumeUuid = vol.fsUuid;
19016        if (TextUtils.isEmpty(volumeUuid)) {
19017            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19018            return;
19019        }
19020
19021        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19022        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19023        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19024
19025        final VersionInfo ver;
19026        final List<PackageSetting> packages;
19027        synchronized (mPackages) {
19028            ver = mSettings.findOrCreateVersion(volumeUuid);
19029            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19030        }
19031
19032        for (PackageSetting ps : packages) {
19033            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19034            synchronized (mInstallLock) {
19035                final PackageParser.Package pkg;
19036                try {
19037                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19038                    loaded.add(pkg.applicationInfo);
19039
19040                } catch (PackageManagerException e) {
19041                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19042                }
19043
19044                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19045                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19046                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19047                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19048                }
19049            }
19050        }
19051
19052        // Reconcile app data for all started/unlocked users
19053        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19054        final UserManager um = mContext.getSystemService(UserManager.class);
19055        UserManagerInternal umInternal = getUserManagerInternal();
19056        for (UserInfo user : um.getUsers()) {
19057            final int flags;
19058            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19059                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19060            } else if (umInternal.isUserRunning(user.id)) {
19061                flags = StorageManager.FLAG_STORAGE_DE;
19062            } else {
19063                continue;
19064            }
19065
19066            try {
19067                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19068                synchronized (mInstallLock) {
19069                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19070                }
19071            } catch (IllegalStateException e) {
19072                // Device was probably ejected, and we'll process that event momentarily
19073                Slog.w(TAG, "Failed to prepare storage: " + e);
19074            }
19075        }
19076
19077        synchronized (mPackages) {
19078            int updateFlags = UPDATE_PERMISSIONS_ALL;
19079            if (ver.sdkVersion != mSdkVersion) {
19080                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19081                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19082                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19083            }
19084            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19085
19086            // Yay, everything is now upgraded
19087            ver.forceCurrent();
19088
19089            mSettings.writeLPr();
19090        }
19091
19092        for (PackageFreezer freezer : freezers) {
19093            freezer.close();
19094        }
19095
19096        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19097        sendResourcesChangedBroadcast(true, false, loaded, null);
19098    }
19099
19100    private void unloadPrivatePackages(final VolumeInfo vol) {
19101        mHandler.post(new Runnable() {
19102            @Override
19103            public void run() {
19104                unloadPrivatePackagesInner(vol);
19105            }
19106        });
19107    }
19108
19109    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19110        final String volumeUuid = vol.fsUuid;
19111        if (TextUtils.isEmpty(volumeUuid)) {
19112            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19113            return;
19114        }
19115
19116        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19117        synchronized (mInstallLock) {
19118        synchronized (mPackages) {
19119            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19120            for (PackageSetting ps : packages) {
19121                if (ps.pkg == null) continue;
19122
19123                final ApplicationInfo info = ps.pkg.applicationInfo;
19124                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19125                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19126
19127                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19128                        "unloadPrivatePackagesInner")) {
19129                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19130                            false, null)) {
19131                        unloaded.add(info);
19132                    } else {
19133                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19134                    }
19135                }
19136            }
19137
19138            mSettings.writeLPr();
19139        }
19140        }
19141
19142        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19143        sendResourcesChangedBroadcast(false, false, unloaded, null);
19144    }
19145
19146    /**
19147     * Prepare storage areas for given user on all mounted devices.
19148     */
19149    void prepareUserData(int userId, int userSerial, int flags) {
19150        synchronized (mInstallLock) {
19151            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19152            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19153                final String volumeUuid = vol.getFsUuid();
19154                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19155            }
19156        }
19157    }
19158
19159    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19160            boolean allowRecover) {
19161        // Prepare storage and verify that serial numbers are consistent; if
19162        // there's a mismatch we need to destroy to avoid leaking data
19163        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19164        try {
19165            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19166
19167            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19168                UserManagerService.enforceSerialNumber(
19169                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19170            }
19171            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19172                UserManagerService.enforceSerialNumber(
19173                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19174            }
19175
19176            synchronized (mInstallLock) {
19177                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19178            }
19179        } catch (Exception e) {
19180            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19181                    + " because we failed to prepare: " + e);
19182            destroyUserDataLI(volumeUuid, userId,
19183                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19184
19185            if (allowRecover) {
19186                // Try one last time; if we fail again we're really in trouble
19187                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19188            }
19189        }
19190    }
19191
19192    /**
19193     * Destroy storage areas for given user on all mounted devices.
19194     */
19195    void destroyUserData(int userId, int flags) {
19196        synchronized (mInstallLock) {
19197            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19198            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19199                final String volumeUuid = vol.getFsUuid();
19200                destroyUserDataLI(volumeUuid, userId, flags);
19201            }
19202        }
19203    }
19204
19205    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19206        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19207        try {
19208            // Clean up app data, profile data, and media data
19209            mInstaller.destroyUserData(volumeUuid, userId, flags);
19210
19211            // Clean up system data
19212            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19213                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19214                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19215                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19216                }
19217                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19218                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19219                }
19220            }
19221
19222            // Data with special labels is now gone, so finish the job
19223            storage.destroyUserStorage(volumeUuid, userId, flags);
19224
19225        } catch (Exception e) {
19226            logCriticalInfo(Log.WARN,
19227                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19228        }
19229    }
19230
19231    /**
19232     * Examine all users present on given mounted volume, and destroy data
19233     * belonging to users that are no longer valid, or whose user ID has been
19234     * recycled.
19235     */
19236    private void reconcileUsers(String volumeUuid) {
19237        final List<File> files = new ArrayList<>();
19238        Collections.addAll(files, FileUtils
19239                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19240        Collections.addAll(files, FileUtils
19241                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19242        for (File file : files) {
19243            if (!file.isDirectory()) continue;
19244
19245            final int userId;
19246            final UserInfo info;
19247            try {
19248                userId = Integer.parseInt(file.getName());
19249                info = sUserManager.getUserInfo(userId);
19250            } catch (NumberFormatException e) {
19251                Slog.w(TAG, "Invalid user directory " + file);
19252                continue;
19253            }
19254
19255            boolean destroyUser = false;
19256            if (info == null) {
19257                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19258                        + " because no matching user was found");
19259                destroyUser = true;
19260            } else if (!mOnlyCore) {
19261                try {
19262                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19263                } catch (IOException e) {
19264                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19265                            + " because we failed to enforce serial number: " + e);
19266                    destroyUser = true;
19267                }
19268            }
19269
19270            if (destroyUser) {
19271                synchronized (mInstallLock) {
19272                    destroyUserDataLI(volumeUuid, userId,
19273                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19274                }
19275            }
19276        }
19277    }
19278
19279    private void assertPackageKnown(String volumeUuid, String packageName)
19280            throws PackageManagerException {
19281        synchronized (mPackages) {
19282            final PackageSetting ps = mSettings.mPackages.get(packageName);
19283            if (ps == null) {
19284                throw new PackageManagerException("Package " + packageName + " is unknown");
19285            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19286                throw new PackageManagerException(
19287                        "Package " + packageName + " found on unknown volume " + volumeUuid
19288                                + "; expected volume " + ps.volumeUuid);
19289            }
19290        }
19291    }
19292
19293    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19294            throws PackageManagerException {
19295        synchronized (mPackages) {
19296            final PackageSetting ps = mSettings.mPackages.get(packageName);
19297            if (ps == null) {
19298                throw new PackageManagerException("Package " + packageName + " is unknown");
19299            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19300                throw new PackageManagerException(
19301                        "Package " + packageName + " found on unknown volume " + volumeUuid
19302                                + "; expected volume " + ps.volumeUuid);
19303            } else if (!ps.getInstalled(userId)) {
19304                throw new PackageManagerException(
19305                        "Package " + packageName + " not installed for user " + userId);
19306            }
19307        }
19308    }
19309
19310    /**
19311     * Examine all apps present on given mounted volume, and destroy apps that
19312     * aren't expected, either due to uninstallation or reinstallation on
19313     * another volume.
19314     */
19315    private void reconcileApps(String volumeUuid) {
19316        final File[] files = FileUtils
19317                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19318        for (File file : files) {
19319            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19320                    && !PackageInstallerService.isStageName(file.getName());
19321            if (!isPackage) {
19322                // Ignore entries which are not packages
19323                continue;
19324            }
19325
19326            try {
19327                final PackageLite pkg = PackageParser.parsePackageLite(file,
19328                        PackageParser.PARSE_MUST_BE_APK);
19329                assertPackageKnown(volumeUuid, pkg.packageName);
19330
19331            } catch (PackageParserException | PackageManagerException e) {
19332                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19333                synchronized (mInstallLock) {
19334                    removeCodePathLI(file);
19335                }
19336            }
19337        }
19338    }
19339
19340    /**
19341     * Reconcile all app data for the given user.
19342     * <p>
19343     * Verifies that directories exist and that ownership and labeling is
19344     * correct for all installed apps on all mounted volumes.
19345     */
19346    void reconcileAppsData(int userId, int flags) {
19347        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19348        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19349            final String volumeUuid = vol.getFsUuid();
19350            synchronized (mInstallLock) {
19351                reconcileAppsDataLI(volumeUuid, userId, flags);
19352            }
19353        }
19354    }
19355
19356    /**
19357     * Reconcile all app data on given mounted volume.
19358     * <p>
19359     * Destroys app data that isn't expected, either due to uninstallation or
19360     * reinstallation on another volume.
19361     * <p>
19362     * Verifies that directories exist and that ownership and labeling is
19363     * correct for all installed apps.
19364     */
19365    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19366        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19367                + Integer.toHexString(flags));
19368
19369        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19370        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19371
19372        boolean restoreconNeeded = false;
19373
19374        // First look for stale data that doesn't belong, and check if things
19375        // have changed since we did our last restorecon
19376        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19377            if (StorageManager.isFileEncryptedNativeOrEmulated()
19378                    && !StorageManager.isUserKeyUnlocked(userId)) {
19379                throw new RuntimeException(
19380                        "Yikes, someone asked us to reconcile CE storage while " + userId
19381                                + " was still locked; this would have caused massive data loss!");
19382            }
19383
19384            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19385
19386            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19387            for (File file : files) {
19388                final String packageName = file.getName();
19389                try {
19390                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19391                } catch (PackageManagerException e) {
19392                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19393                    try {
19394                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19395                                StorageManager.FLAG_STORAGE_CE, 0);
19396                    } catch (InstallerException e2) {
19397                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19398                    }
19399                }
19400            }
19401        }
19402        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19403            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19404
19405            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19406            for (File file : files) {
19407                final String packageName = file.getName();
19408                try {
19409                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19410                } catch (PackageManagerException e) {
19411                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19412                    try {
19413                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19414                                StorageManager.FLAG_STORAGE_DE, 0);
19415                    } catch (InstallerException e2) {
19416                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19417                    }
19418                }
19419            }
19420        }
19421
19422        // Ensure that data directories are ready to roll for all packages
19423        // installed for this volume and user
19424        final List<PackageSetting> packages;
19425        synchronized (mPackages) {
19426            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19427        }
19428        int preparedCount = 0;
19429        for (PackageSetting ps : packages) {
19430            final String packageName = ps.name;
19431            if (ps.pkg == null) {
19432                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19433                // TODO: might be due to legacy ASEC apps; we should circle back
19434                // and reconcile again once they're scanned
19435                continue;
19436            }
19437
19438            if (ps.getInstalled(userId)) {
19439                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19440
19441                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19442                    // We may have just shuffled around app data directories, so
19443                    // prepare them one more time
19444                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19445                }
19446
19447                preparedCount++;
19448            }
19449        }
19450
19451        if (restoreconNeeded) {
19452            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19453                SELinuxMMAC.setRestoreconDone(ceDir);
19454            }
19455            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19456                SELinuxMMAC.setRestoreconDone(deDir);
19457            }
19458        }
19459
19460        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19461                + " packages; restoreconNeeded was " + restoreconNeeded);
19462    }
19463
19464    /**
19465     * Prepare app data for the given app just after it was installed or
19466     * upgraded. This method carefully only touches users that it's installed
19467     * for, and it forces a restorecon to handle any seinfo changes.
19468     * <p>
19469     * Verifies that directories exist and that ownership and labeling is
19470     * correct for all installed apps. If there is an ownership mismatch, it
19471     * will try recovering system apps by wiping data; third-party app data is
19472     * left intact.
19473     * <p>
19474     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19475     */
19476    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19477        final PackageSetting ps;
19478        synchronized (mPackages) {
19479            ps = mSettings.mPackages.get(pkg.packageName);
19480            mSettings.writeKernelMappingLPr(ps);
19481        }
19482
19483        final UserManager um = mContext.getSystemService(UserManager.class);
19484        UserManagerInternal umInternal = getUserManagerInternal();
19485        for (UserInfo user : um.getUsers()) {
19486            final int flags;
19487            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19488                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19489            } else if (umInternal.isUserRunning(user.id)) {
19490                flags = StorageManager.FLAG_STORAGE_DE;
19491            } else {
19492                continue;
19493            }
19494
19495            if (ps.getInstalled(user.id)) {
19496                // Whenever an app changes, force a restorecon of its data
19497                // TODO: when user data is locked, mark that we're still dirty
19498                prepareAppDataLIF(pkg, user.id, flags, true);
19499            }
19500        }
19501    }
19502
19503    /**
19504     * Prepare app data for the given app.
19505     * <p>
19506     * Verifies that directories exist and that ownership and labeling is
19507     * correct for all installed apps. If there is an ownership mismatch, this
19508     * will try recovering system apps by wiping data; third-party app data is
19509     * left intact.
19510     */
19511    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19512            boolean restoreconNeeded) {
19513        if (pkg == null) {
19514            Slog.wtf(TAG, "Package was null!", new Throwable());
19515            return;
19516        }
19517        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19518        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19519        for (int i = 0; i < childCount; i++) {
19520            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19521        }
19522    }
19523
19524    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19525            boolean restoreconNeeded) {
19526        if (DEBUG_APP_DATA) {
19527            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19528                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19529        }
19530
19531        final String volumeUuid = pkg.volumeUuid;
19532        final String packageName = pkg.packageName;
19533        final ApplicationInfo app = pkg.applicationInfo;
19534        final int appId = UserHandle.getAppId(app.uid);
19535
19536        Preconditions.checkNotNull(app.seinfo);
19537
19538        try {
19539            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19540                    appId, app.seinfo, app.targetSdkVersion);
19541        } catch (InstallerException e) {
19542            if (app.isSystemApp()) {
19543                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19544                        + ", but trying to recover: " + e);
19545                destroyAppDataLeafLIF(pkg, userId, flags);
19546                try {
19547                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19548                            appId, app.seinfo, app.targetSdkVersion);
19549                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19550                } catch (InstallerException e2) {
19551                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19552                }
19553            } else {
19554                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19555            }
19556        }
19557
19558        if (restoreconNeeded) {
19559            try {
19560                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19561                        app.seinfo);
19562            } catch (InstallerException e) {
19563                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19564            }
19565        }
19566
19567        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19568            try {
19569                // CE storage is unlocked right now, so read out the inode and
19570                // remember for use later when it's locked
19571                // TODO: mark this structure as dirty so we persist it!
19572                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19573                        StorageManager.FLAG_STORAGE_CE);
19574                synchronized (mPackages) {
19575                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19576                    if (ps != null) {
19577                        ps.setCeDataInode(ceDataInode, userId);
19578                    }
19579                }
19580            } catch (InstallerException e) {
19581                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19582            }
19583        }
19584
19585        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19586    }
19587
19588    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19589        if (pkg == null) {
19590            Slog.wtf(TAG, "Package was null!", new Throwable());
19591            return;
19592        }
19593        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19594        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19595        for (int i = 0; i < childCount; i++) {
19596            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19597        }
19598    }
19599
19600    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19601        final String volumeUuid = pkg.volumeUuid;
19602        final String packageName = pkg.packageName;
19603        final ApplicationInfo app = pkg.applicationInfo;
19604
19605        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19606            // Create a native library symlink only if we have native libraries
19607            // and if the native libraries are 32 bit libraries. We do not provide
19608            // this symlink for 64 bit libraries.
19609            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19610                final String nativeLibPath = app.nativeLibraryDir;
19611                try {
19612                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19613                            nativeLibPath, userId);
19614                } catch (InstallerException e) {
19615                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19616                }
19617            }
19618        }
19619    }
19620
19621    /**
19622     * For system apps on non-FBE devices, this method migrates any existing
19623     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19624     * requested by the app.
19625     */
19626    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19627        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19628                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19629            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19630                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19631            try {
19632                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19633                        storageTarget);
19634            } catch (InstallerException e) {
19635                logCriticalInfo(Log.WARN,
19636                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19637            }
19638            return true;
19639        } else {
19640            return false;
19641        }
19642    }
19643
19644    public PackageFreezer freezePackage(String packageName, String killReason) {
19645        return new PackageFreezer(packageName, killReason);
19646    }
19647
19648    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19649            String killReason) {
19650        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19651            return new PackageFreezer();
19652        } else {
19653            return freezePackage(packageName, killReason);
19654        }
19655    }
19656
19657    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19658            String killReason) {
19659        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19660            return new PackageFreezer();
19661        } else {
19662            return freezePackage(packageName, killReason);
19663        }
19664    }
19665
19666    /**
19667     * Class that freezes and kills the given package upon creation, and
19668     * unfreezes it upon closing. This is typically used when doing surgery on
19669     * app code/data to prevent the app from running while you're working.
19670     */
19671    private class PackageFreezer implements AutoCloseable {
19672        private final String mPackageName;
19673        private final PackageFreezer[] mChildren;
19674
19675        private final boolean mWeFroze;
19676
19677        private final AtomicBoolean mClosed = new AtomicBoolean();
19678        private final CloseGuard mCloseGuard = CloseGuard.get();
19679
19680        /**
19681         * Create and return a stub freezer that doesn't actually do anything,
19682         * typically used when someone requested
19683         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19684         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19685         */
19686        public PackageFreezer() {
19687            mPackageName = null;
19688            mChildren = null;
19689            mWeFroze = false;
19690            mCloseGuard.open("close");
19691        }
19692
19693        public PackageFreezer(String packageName, String killReason) {
19694            synchronized (mPackages) {
19695                mPackageName = packageName;
19696                mWeFroze = mFrozenPackages.add(mPackageName);
19697
19698                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19699                if (ps != null) {
19700                    killApplication(ps.name, ps.appId, killReason);
19701                }
19702
19703                final PackageParser.Package p = mPackages.get(packageName);
19704                if (p != null && p.childPackages != null) {
19705                    final int N = p.childPackages.size();
19706                    mChildren = new PackageFreezer[N];
19707                    for (int i = 0; i < N; i++) {
19708                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19709                                killReason);
19710                    }
19711                } else {
19712                    mChildren = null;
19713                }
19714            }
19715            mCloseGuard.open("close");
19716        }
19717
19718        @Override
19719        protected void finalize() throws Throwable {
19720            try {
19721                mCloseGuard.warnIfOpen();
19722                close();
19723            } finally {
19724                super.finalize();
19725            }
19726        }
19727
19728        @Override
19729        public void close() {
19730            mCloseGuard.close();
19731            if (mClosed.compareAndSet(false, true)) {
19732                synchronized (mPackages) {
19733                    if (mWeFroze) {
19734                        mFrozenPackages.remove(mPackageName);
19735                    }
19736
19737                    if (mChildren != null) {
19738                        for (PackageFreezer freezer : mChildren) {
19739                            freezer.close();
19740                        }
19741                    }
19742                }
19743            }
19744        }
19745    }
19746
19747    /**
19748     * Verify that given package is currently frozen.
19749     */
19750    private void checkPackageFrozen(String packageName) {
19751        synchronized (mPackages) {
19752            if (!mFrozenPackages.contains(packageName)) {
19753                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19754            }
19755        }
19756    }
19757
19758    @Override
19759    public int movePackage(final String packageName, final String volumeUuid) {
19760        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19761
19762        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19763        final int moveId = mNextMoveId.getAndIncrement();
19764        mHandler.post(new Runnable() {
19765            @Override
19766            public void run() {
19767                try {
19768                    movePackageInternal(packageName, volumeUuid, moveId, user);
19769                } catch (PackageManagerException e) {
19770                    Slog.w(TAG, "Failed to move " + packageName, e);
19771                    mMoveCallbacks.notifyStatusChanged(moveId,
19772                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19773                }
19774            }
19775        });
19776        return moveId;
19777    }
19778
19779    private void movePackageInternal(final String packageName, final String volumeUuid,
19780            final int moveId, UserHandle user) throws PackageManagerException {
19781        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19782        final PackageManager pm = mContext.getPackageManager();
19783
19784        final boolean currentAsec;
19785        final String currentVolumeUuid;
19786        final File codeFile;
19787        final String installerPackageName;
19788        final String packageAbiOverride;
19789        final int appId;
19790        final String seinfo;
19791        final String label;
19792        final int targetSdkVersion;
19793        final PackageFreezer freezer;
19794        final int[] installedUserIds;
19795
19796        // reader
19797        synchronized (mPackages) {
19798            final PackageParser.Package pkg = mPackages.get(packageName);
19799            final PackageSetting ps = mSettings.mPackages.get(packageName);
19800            if (pkg == null || ps == null) {
19801                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19802            }
19803
19804            if (pkg.applicationInfo.isSystemApp()) {
19805                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19806                        "Cannot move system application");
19807            }
19808
19809            if (pkg.applicationInfo.isExternalAsec()) {
19810                currentAsec = true;
19811                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19812            } else if (pkg.applicationInfo.isForwardLocked()) {
19813                currentAsec = true;
19814                currentVolumeUuid = "forward_locked";
19815            } else {
19816                currentAsec = false;
19817                currentVolumeUuid = ps.volumeUuid;
19818
19819                final File probe = new File(pkg.codePath);
19820                final File probeOat = new File(probe, "oat");
19821                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19822                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19823                            "Move only supported for modern cluster style installs");
19824                }
19825            }
19826
19827            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19828                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19829                        "Package already moved to " + volumeUuid);
19830            }
19831            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19832                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19833                        "Device admin cannot be moved");
19834            }
19835
19836            if (mFrozenPackages.contains(packageName)) {
19837                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19838                        "Failed to move already frozen package");
19839            }
19840
19841            codeFile = new File(pkg.codePath);
19842            installerPackageName = ps.installerPackageName;
19843            packageAbiOverride = ps.cpuAbiOverrideString;
19844            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19845            seinfo = pkg.applicationInfo.seinfo;
19846            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19847            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19848            freezer = new PackageFreezer(packageName, "movePackageInternal");
19849            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19850        }
19851
19852        final Bundle extras = new Bundle();
19853        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19854        extras.putString(Intent.EXTRA_TITLE, label);
19855        mMoveCallbacks.notifyCreated(moveId, extras);
19856
19857        int installFlags;
19858        final boolean moveCompleteApp;
19859        final File measurePath;
19860
19861        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19862            installFlags = INSTALL_INTERNAL;
19863            moveCompleteApp = !currentAsec;
19864            measurePath = Environment.getDataAppDirectory(volumeUuid);
19865        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19866            installFlags = INSTALL_EXTERNAL;
19867            moveCompleteApp = false;
19868            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19869        } else {
19870            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19871            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19872                    || !volume.isMountedWritable()) {
19873                freezer.close();
19874                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19875                        "Move location not mounted private volume");
19876            }
19877
19878            Preconditions.checkState(!currentAsec);
19879
19880            installFlags = INSTALL_INTERNAL;
19881            moveCompleteApp = true;
19882            measurePath = Environment.getDataAppDirectory(volumeUuid);
19883        }
19884
19885        final PackageStats stats = new PackageStats(null, -1);
19886        synchronized (mInstaller) {
19887            for (int userId : installedUserIds) {
19888                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
19889                    freezer.close();
19890                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19891                            "Failed to measure package size");
19892                }
19893            }
19894        }
19895
19896        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19897                + stats.dataSize);
19898
19899        final long startFreeBytes = measurePath.getFreeSpace();
19900        final long sizeBytes;
19901        if (moveCompleteApp) {
19902            sizeBytes = stats.codeSize + stats.dataSize;
19903        } else {
19904            sizeBytes = stats.codeSize;
19905        }
19906
19907        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19908            freezer.close();
19909            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19910                    "Not enough free space to move");
19911        }
19912
19913        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19914
19915        final CountDownLatch installedLatch = new CountDownLatch(1);
19916        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19917            @Override
19918            public void onUserActionRequired(Intent intent) throws RemoteException {
19919                throw new IllegalStateException();
19920            }
19921
19922            @Override
19923            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19924                    Bundle extras) throws RemoteException {
19925                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19926                        + PackageManager.installStatusToString(returnCode, msg));
19927
19928                installedLatch.countDown();
19929                freezer.close();
19930
19931                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19932                switch (status) {
19933                    case PackageInstaller.STATUS_SUCCESS:
19934                        mMoveCallbacks.notifyStatusChanged(moveId,
19935                                PackageManager.MOVE_SUCCEEDED);
19936                        break;
19937                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19938                        mMoveCallbacks.notifyStatusChanged(moveId,
19939                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19940                        break;
19941                    default:
19942                        mMoveCallbacks.notifyStatusChanged(moveId,
19943                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19944                        break;
19945                }
19946            }
19947        };
19948
19949        final MoveInfo move;
19950        if (moveCompleteApp) {
19951            // Kick off a thread to report progress estimates
19952            new Thread() {
19953                @Override
19954                public void run() {
19955                    while (true) {
19956                        try {
19957                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19958                                break;
19959                            }
19960                        } catch (InterruptedException ignored) {
19961                        }
19962
19963                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19964                        final int progress = 10 + (int) MathUtils.constrain(
19965                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19966                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19967                    }
19968                }
19969            }.start();
19970
19971            final String dataAppName = codeFile.getName();
19972            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19973                    dataAppName, appId, seinfo, targetSdkVersion);
19974        } else {
19975            move = null;
19976        }
19977
19978        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19979
19980        final Message msg = mHandler.obtainMessage(INIT_COPY);
19981        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19982        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19983                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19984                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19985        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19986        msg.obj = params;
19987
19988        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19989                System.identityHashCode(msg.obj));
19990        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19991                System.identityHashCode(msg.obj));
19992
19993        mHandler.sendMessage(msg);
19994    }
19995
19996    @Override
19997    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19998        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19999
20000        final int realMoveId = mNextMoveId.getAndIncrement();
20001        final Bundle extras = new Bundle();
20002        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20003        mMoveCallbacks.notifyCreated(realMoveId, extras);
20004
20005        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20006            @Override
20007            public void onCreated(int moveId, Bundle extras) {
20008                // Ignored
20009            }
20010
20011            @Override
20012            public void onStatusChanged(int moveId, int status, long estMillis) {
20013                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20014            }
20015        };
20016
20017        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20018        storage.setPrimaryStorageUuid(volumeUuid, callback);
20019        return realMoveId;
20020    }
20021
20022    @Override
20023    public int getMoveStatus(int moveId) {
20024        mContext.enforceCallingOrSelfPermission(
20025                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20026        return mMoveCallbacks.mLastStatus.get(moveId);
20027    }
20028
20029    @Override
20030    public void registerMoveCallback(IPackageMoveObserver callback) {
20031        mContext.enforceCallingOrSelfPermission(
20032                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20033        mMoveCallbacks.register(callback);
20034    }
20035
20036    @Override
20037    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20038        mContext.enforceCallingOrSelfPermission(
20039                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20040        mMoveCallbacks.unregister(callback);
20041    }
20042
20043    @Override
20044    public boolean setInstallLocation(int loc) {
20045        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20046                null);
20047        if (getInstallLocation() == loc) {
20048            return true;
20049        }
20050        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20051                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20052            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20053                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20054            return true;
20055        }
20056        return false;
20057   }
20058
20059    @Override
20060    public int getInstallLocation() {
20061        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20062                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20063                PackageHelper.APP_INSTALL_AUTO);
20064    }
20065
20066    /** Called by UserManagerService */
20067    void cleanUpUser(UserManagerService userManager, int userHandle) {
20068        synchronized (mPackages) {
20069            mDirtyUsers.remove(userHandle);
20070            mUserNeedsBadging.delete(userHandle);
20071            mSettings.removeUserLPw(userHandle);
20072            mPendingBroadcasts.remove(userHandle);
20073            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20074            removeUnusedPackagesLPw(userManager, userHandle);
20075        }
20076    }
20077
20078    /**
20079     * We're removing userHandle and would like to remove any downloaded packages
20080     * that are no longer in use by any other user.
20081     * @param userHandle the user being removed
20082     */
20083    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20084        final boolean DEBUG_CLEAN_APKS = false;
20085        int [] users = userManager.getUserIds();
20086        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20087        while (psit.hasNext()) {
20088            PackageSetting ps = psit.next();
20089            if (ps.pkg == null) {
20090                continue;
20091            }
20092            final String packageName = ps.pkg.packageName;
20093            // Skip over if system app
20094            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20095                continue;
20096            }
20097            if (DEBUG_CLEAN_APKS) {
20098                Slog.i(TAG, "Checking package " + packageName);
20099            }
20100            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20101            if (keep) {
20102                if (DEBUG_CLEAN_APKS) {
20103                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20104                }
20105            } else {
20106                for (int i = 0; i < users.length; i++) {
20107                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20108                        keep = true;
20109                        if (DEBUG_CLEAN_APKS) {
20110                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20111                                    + users[i]);
20112                        }
20113                        break;
20114                    }
20115                }
20116            }
20117            if (!keep) {
20118                if (DEBUG_CLEAN_APKS) {
20119                    Slog.i(TAG, "  Removing package " + packageName);
20120                }
20121                mHandler.post(new Runnable() {
20122                    public void run() {
20123                        deletePackageX(packageName, userHandle, 0);
20124                    } //end run
20125                });
20126            }
20127        }
20128    }
20129
20130    /** Called by UserManagerService */
20131    void createNewUser(int userId) {
20132        synchronized (mInstallLock) {
20133            mSettings.createNewUserLI(this, mInstaller, userId);
20134        }
20135        synchronized (mPackages) {
20136            scheduleWritePackageRestrictionsLocked(userId);
20137            scheduleWritePackageListLocked(userId);
20138            applyFactoryDefaultBrowserLPw(userId);
20139            primeDomainVerificationsLPw(userId);
20140        }
20141    }
20142
20143    void onBeforeUserStartUninitialized(final int userId) {
20144        synchronized (mPackages) {
20145            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20146                return;
20147            }
20148        }
20149        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20150        // If permission review for legacy apps is required, we represent
20151        // dagerous permissions for such apps as always granted runtime
20152        // permissions to keep per user flag state whether review is needed.
20153        // Hence, if a new user is added we have to propagate dangerous
20154        // permission grants for these legacy apps.
20155        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20156            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20157                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20158        }
20159    }
20160
20161    @Override
20162    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20163        mContext.enforceCallingOrSelfPermission(
20164                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20165                "Only package verification agents can read the verifier device identity");
20166
20167        synchronized (mPackages) {
20168            return mSettings.getVerifierDeviceIdentityLPw();
20169        }
20170    }
20171
20172    @Override
20173    public void setPermissionEnforced(String permission, boolean enforced) {
20174        // TODO: Now that we no longer change GID for storage, this should to away.
20175        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20176                "setPermissionEnforced");
20177        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20178            synchronized (mPackages) {
20179                if (mSettings.mReadExternalStorageEnforced == null
20180                        || mSettings.mReadExternalStorageEnforced != enforced) {
20181                    mSettings.mReadExternalStorageEnforced = enforced;
20182                    mSettings.writeLPr();
20183                }
20184            }
20185            // kill any non-foreground processes so we restart them and
20186            // grant/revoke the GID.
20187            final IActivityManager am = ActivityManagerNative.getDefault();
20188            if (am != null) {
20189                final long token = Binder.clearCallingIdentity();
20190                try {
20191                    am.killProcessesBelowForeground("setPermissionEnforcement");
20192                } catch (RemoteException e) {
20193                } finally {
20194                    Binder.restoreCallingIdentity(token);
20195                }
20196            }
20197        } else {
20198            throw new IllegalArgumentException("No selective enforcement for " + permission);
20199        }
20200    }
20201
20202    @Override
20203    @Deprecated
20204    public boolean isPermissionEnforced(String permission) {
20205        return true;
20206    }
20207
20208    @Override
20209    public boolean isStorageLow() {
20210        final long token = Binder.clearCallingIdentity();
20211        try {
20212            final DeviceStorageMonitorInternal
20213                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20214            if (dsm != null) {
20215                return dsm.isMemoryLow();
20216            } else {
20217                return false;
20218            }
20219        } finally {
20220            Binder.restoreCallingIdentity(token);
20221        }
20222    }
20223
20224    @Override
20225    public IPackageInstaller getPackageInstaller() {
20226        return mInstallerService;
20227    }
20228
20229    private boolean userNeedsBadging(int userId) {
20230        int index = mUserNeedsBadging.indexOfKey(userId);
20231        if (index < 0) {
20232            final UserInfo userInfo;
20233            final long token = Binder.clearCallingIdentity();
20234            try {
20235                userInfo = sUserManager.getUserInfo(userId);
20236            } finally {
20237                Binder.restoreCallingIdentity(token);
20238            }
20239            final boolean b;
20240            if (userInfo != null && userInfo.isManagedProfile()) {
20241                b = true;
20242            } else {
20243                b = false;
20244            }
20245            mUserNeedsBadging.put(userId, b);
20246            return b;
20247        }
20248        return mUserNeedsBadging.valueAt(index);
20249    }
20250
20251    @Override
20252    public KeySet getKeySetByAlias(String packageName, String alias) {
20253        if (packageName == null || alias == null) {
20254            return null;
20255        }
20256        synchronized(mPackages) {
20257            final PackageParser.Package pkg = mPackages.get(packageName);
20258            if (pkg == null) {
20259                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20260                throw new IllegalArgumentException("Unknown package: " + packageName);
20261            }
20262            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20263            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20264        }
20265    }
20266
20267    @Override
20268    public KeySet getSigningKeySet(String packageName) {
20269        if (packageName == null) {
20270            return null;
20271        }
20272        synchronized(mPackages) {
20273            final PackageParser.Package pkg = mPackages.get(packageName);
20274            if (pkg == null) {
20275                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20276                throw new IllegalArgumentException("Unknown package: " + packageName);
20277            }
20278            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20279                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20280                throw new SecurityException("May not access signing KeySet of other apps.");
20281            }
20282            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20283            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20284        }
20285    }
20286
20287    @Override
20288    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20289        if (packageName == null || ks == null) {
20290            return false;
20291        }
20292        synchronized(mPackages) {
20293            final PackageParser.Package pkg = mPackages.get(packageName);
20294            if (pkg == null) {
20295                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20296                throw new IllegalArgumentException("Unknown package: " + packageName);
20297            }
20298            IBinder ksh = ks.getToken();
20299            if (ksh instanceof KeySetHandle) {
20300                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20301                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20302            }
20303            return false;
20304        }
20305    }
20306
20307    @Override
20308    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20309        if (packageName == null || ks == null) {
20310            return false;
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            IBinder ksh = ks.getToken();
20319            if (ksh instanceof KeySetHandle) {
20320                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20321                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20322            }
20323            return false;
20324        }
20325    }
20326
20327    private void deletePackageIfUnusedLPr(final String packageName) {
20328        PackageSetting ps = mSettings.mPackages.get(packageName);
20329        if (ps == null) {
20330            return;
20331        }
20332        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20333            // TODO Implement atomic delete if package is unused
20334            // It is currently possible that the package will be deleted even if it is installed
20335            // after this method returns.
20336            mHandler.post(new Runnable() {
20337                public void run() {
20338                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20339                }
20340            });
20341        }
20342    }
20343
20344    /**
20345     * Check and throw if the given before/after packages would be considered a
20346     * downgrade.
20347     */
20348    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20349            throws PackageManagerException {
20350        if (after.versionCode < before.mVersionCode) {
20351            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20352                    "Update version code " + after.versionCode + " is older than current "
20353                    + before.mVersionCode);
20354        } else if (after.versionCode == before.mVersionCode) {
20355            if (after.baseRevisionCode < before.baseRevisionCode) {
20356                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20357                        "Update base revision code " + after.baseRevisionCode
20358                        + " is older than current " + before.baseRevisionCode);
20359            }
20360
20361            if (!ArrayUtils.isEmpty(after.splitNames)) {
20362                for (int i = 0; i < after.splitNames.length; i++) {
20363                    final String splitName = after.splitNames[i];
20364                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20365                    if (j != -1) {
20366                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20367                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20368                                    "Update split " + splitName + " revision code "
20369                                    + after.splitRevisionCodes[i] + " is older than current "
20370                                    + before.splitRevisionCodes[j]);
20371                        }
20372                    }
20373                }
20374            }
20375        }
20376    }
20377
20378    private static class MoveCallbacks extends Handler {
20379        private static final int MSG_CREATED = 1;
20380        private static final int MSG_STATUS_CHANGED = 2;
20381
20382        private final RemoteCallbackList<IPackageMoveObserver>
20383                mCallbacks = new RemoteCallbackList<>();
20384
20385        private final SparseIntArray mLastStatus = new SparseIntArray();
20386
20387        public MoveCallbacks(Looper looper) {
20388            super(looper);
20389        }
20390
20391        public void register(IPackageMoveObserver callback) {
20392            mCallbacks.register(callback);
20393        }
20394
20395        public void unregister(IPackageMoveObserver callback) {
20396            mCallbacks.unregister(callback);
20397        }
20398
20399        @Override
20400        public void handleMessage(Message msg) {
20401            final SomeArgs args = (SomeArgs) msg.obj;
20402            final int n = mCallbacks.beginBroadcast();
20403            for (int i = 0; i < n; i++) {
20404                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20405                try {
20406                    invokeCallback(callback, msg.what, args);
20407                } catch (RemoteException ignored) {
20408                }
20409            }
20410            mCallbacks.finishBroadcast();
20411            args.recycle();
20412        }
20413
20414        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20415                throws RemoteException {
20416            switch (what) {
20417                case MSG_CREATED: {
20418                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20419                    break;
20420                }
20421                case MSG_STATUS_CHANGED: {
20422                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20423                    break;
20424                }
20425            }
20426        }
20427
20428        private void notifyCreated(int moveId, Bundle extras) {
20429            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20430
20431            final SomeArgs args = SomeArgs.obtain();
20432            args.argi1 = moveId;
20433            args.arg2 = extras;
20434            obtainMessage(MSG_CREATED, args).sendToTarget();
20435        }
20436
20437        private void notifyStatusChanged(int moveId, int status) {
20438            notifyStatusChanged(moveId, status, -1);
20439        }
20440
20441        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20442            Slog.v(TAG, "Move " + moveId + " status " + status);
20443
20444            final SomeArgs args = SomeArgs.obtain();
20445            args.argi1 = moveId;
20446            args.argi2 = status;
20447            args.arg3 = estMillis;
20448            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20449
20450            synchronized (mLastStatus) {
20451                mLastStatus.put(moveId, status);
20452            }
20453        }
20454    }
20455
20456    private final static class OnPermissionChangeListeners extends Handler {
20457        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20458
20459        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20460                new RemoteCallbackList<>();
20461
20462        public OnPermissionChangeListeners(Looper looper) {
20463            super(looper);
20464        }
20465
20466        @Override
20467        public void handleMessage(Message msg) {
20468            switch (msg.what) {
20469                case MSG_ON_PERMISSIONS_CHANGED: {
20470                    final int uid = msg.arg1;
20471                    handleOnPermissionsChanged(uid);
20472                } break;
20473            }
20474        }
20475
20476        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20477            mPermissionListeners.register(listener);
20478
20479        }
20480
20481        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20482            mPermissionListeners.unregister(listener);
20483        }
20484
20485        public void onPermissionsChanged(int uid) {
20486            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20487                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20488            }
20489        }
20490
20491        private void handleOnPermissionsChanged(int uid) {
20492            final int count = mPermissionListeners.beginBroadcast();
20493            try {
20494                for (int i = 0; i < count; i++) {
20495                    IOnPermissionsChangeListener callback = mPermissionListeners
20496                            .getBroadcastItem(i);
20497                    try {
20498                        callback.onPermissionsChanged(uid);
20499                    } catch (RemoteException e) {
20500                        Log.e(TAG, "Permission listener is dead", e);
20501                    }
20502                }
20503            } finally {
20504                mPermissionListeners.finishBroadcast();
20505            }
20506        }
20507    }
20508
20509    private class PackageManagerInternalImpl extends PackageManagerInternal {
20510        @Override
20511        public void setLocationPackagesProvider(PackagesProvider provider) {
20512            synchronized (mPackages) {
20513                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20514            }
20515        }
20516
20517        @Override
20518        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20519            synchronized (mPackages) {
20520                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20521            }
20522        }
20523
20524        @Override
20525        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20526            synchronized (mPackages) {
20527                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20528            }
20529        }
20530
20531        @Override
20532        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20533            synchronized (mPackages) {
20534                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20535            }
20536        }
20537
20538        @Override
20539        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20540            synchronized (mPackages) {
20541                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20542            }
20543        }
20544
20545        @Override
20546        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20547            synchronized (mPackages) {
20548                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20549            }
20550        }
20551
20552        @Override
20553        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20554            synchronized (mPackages) {
20555                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20556                        packageName, userId);
20557            }
20558        }
20559
20560        @Override
20561        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20562            synchronized (mPackages) {
20563                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20564                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20565                        packageName, userId);
20566            }
20567        }
20568
20569        @Override
20570        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20571            synchronized (mPackages) {
20572                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20573                        packageName, userId);
20574            }
20575        }
20576
20577        @Override
20578        public void setKeepUninstalledPackages(final List<String> packageList) {
20579            Preconditions.checkNotNull(packageList);
20580            List<String> removedFromList = null;
20581            synchronized (mPackages) {
20582                if (mKeepUninstalledPackages != null) {
20583                    final int packagesCount = mKeepUninstalledPackages.size();
20584                    for (int i = 0; i < packagesCount; i++) {
20585                        String oldPackage = mKeepUninstalledPackages.get(i);
20586                        if (packageList != null && packageList.contains(oldPackage)) {
20587                            continue;
20588                        }
20589                        if (removedFromList == null) {
20590                            removedFromList = new ArrayList<>();
20591                        }
20592                        removedFromList.add(oldPackage);
20593                    }
20594                }
20595                mKeepUninstalledPackages = new ArrayList<>(packageList);
20596                if (removedFromList != null) {
20597                    final int removedCount = removedFromList.size();
20598                    for (int i = 0; i < removedCount; i++) {
20599                        deletePackageIfUnusedLPr(removedFromList.get(i));
20600                    }
20601                }
20602            }
20603        }
20604
20605        @Override
20606        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20607            synchronized (mPackages) {
20608                // If we do not support permission review, done.
20609                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20610                    return false;
20611                }
20612
20613                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20614                if (packageSetting == null) {
20615                    return false;
20616                }
20617
20618                // Permission review applies only to apps not supporting the new permission model.
20619                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20620                    return false;
20621                }
20622
20623                // Legacy apps have the permission and get user consent on launch.
20624                PermissionsState permissionsState = packageSetting.getPermissionsState();
20625                return permissionsState.isPermissionReviewRequired(userId);
20626            }
20627        }
20628
20629        @Override
20630        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20631            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20632        }
20633
20634        @Override
20635        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20636                int userId) {
20637            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20638        }
20639    }
20640
20641    @Override
20642    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20643        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20644        synchronized (mPackages) {
20645            final long identity = Binder.clearCallingIdentity();
20646            try {
20647                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20648                        packageNames, userId);
20649            } finally {
20650                Binder.restoreCallingIdentity(identity);
20651            }
20652        }
20653    }
20654
20655    private static void enforceSystemOrPhoneCaller(String tag) {
20656        int callingUid = Binder.getCallingUid();
20657        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20658            throw new SecurityException(
20659                    "Cannot call " + tag + " from UID " + callingUid);
20660        }
20661    }
20662
20663    boolean isHistoricalPackageUsageAvailable() {
20664        return mPackageUsage.isHistoricalPackageUsageAvailable();
20665    }
20666
20667    /**
20668     * Return a <b>copy</b> of the collection of packages known to the package manager.
20669     * @return A copy of the values of mPackages.
20670     */
20671    Collection<PackageParser.Package> getPackages() {
20672        synchronized (mPackages) {
20673            return new ArrayList<>(mPackages.values());
20674        }
20675    }
20676
20677    /**
20678     * Logs process start information (including base APK hash) to the security log.
20679     * @hide
20680     */
20681    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20682            String apkFile, int pid) {
20683        if (!SecurityLog.isLoggingEnabled()) {
20684            return;
20685        }
20686        Bundle data = new Bundle();
20687        data.putLong("startTimestamp", System.currentTimeMillis());
20688        data.putString("processName", processName);
20689        data.putInt("uid", uid);
20690        data.putString("seinfo", seinfo);
20691        data.putString("apkFile", apkFile);
20692        data.putInt("pid", pid);
20693        Message msg = mProcessLoggingHandler.obtainMessage(
20694                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20695        msg.setData(data);
20696        mProcessLoggingHandler.sendMessage(msg);
20697    }
20698}
20699