PackageManagerService.java revision bf6154a5ba3ec164d5f29465dcb65213cc641b22
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_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralResolveInfo;
125import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.Process;
181import android.os.RemoteCallbackList;
182import android.os.RemoteException;
183import android.os.ResultReceiver;
184import android.os.SELinux;
185import android.os.ServiceManager;
186import android.os.SystemClock;
187import android.os.SystemProperties;
188import android.os.Trace;
189import android.os.UserHandle;
190import android.os.UserManager;
191import android.os.UserManagerInternal;
192import android.os.storage.IMountService;
193import android.os.storage.MountServiceInternal;
194import android.os.storage.StorageEventListener;
195import android.os.storage.StorageManager;
196import android.os.storage.VolumeInfo;
197import android.os.storage.VolumeRecord;
198import android.provider.Settings.Global;
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.DisplayMetrics;
208import android.util.EventLog;
209import android.util.ExceptionUtils;
210import android.util.Log;
211import android.util.LogPrinter;
212import android.util.MathUtils;
213import android.util.PrintStreamPrinter;
214import android.util.Slog;
215import android.util.SparseArray;
216import android.util.SparseBooleanArray;
217import android.util.SparseIntArray;
218import android.util.Xml;
219import android.util.jar.StrictJarFile;
220import android.view.Display;
221
222import com.android.internal.R;
223import com.android.internal.annotations.GuardedBy;
224import com.android.internal.app.IMediaContainerService;
225import com.android.internal.app.ResolverActivity;
226import com.android.internal.content.NativeLibraryHelper;
227import com.android.internal.content.PackageHelper;
228import com.android.internal.logging.MetricsLogger;
229import com.android.internal.os.IParcelFileDescriptorFactory;
230import com.android.internal.os.InstallerConnection.InstallerException;
231import com.android.internal.os.SomeArgs;
232import com.android.internal.os.Zygote;
233import com.android.internal.telephony.CarrierAppUtils;
234import com.android.internal.util.ArrayUtils;
235import com.android.internal.util.FastPrintWriter;
236import com.android.internal.util.FastXmlSerializer;
237import com.android.internal.util.IndentingPrintWriter;
238import com.android.internal.util.Preconditions;
239import com.android.internal.util.XmlUtils;
240import com.android.server.AttributeCache;
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.BufferedOutputStream;
266import java.io.BufferedReader;
267import java.io.ByteArrayInputStream;
268import java.io.ByteArrayOutputStream;
269import java.io.File;
270import java.io.FileDescriptor;
271import java.io.FileInputStream;
272import java.io.FileNotFoundException;
273import java.io.FileOutputStream;
274import java.io.FileReader;
275import java.io.FilenameFilter;
276import java.io.IOException;
277import java.io.PrintWriter;
278import java.nio.charset.StandardCharsets;
279import java.security.DigestInputStream;
280import java.security.MessageDigest;
281import java.security.NoSuchAlgorithmException;
282import java.security.PublicKey;
283import java.security.cert.Certificate;
284import java.security.cert.CertificateEncodingException;
285import java.security.cert.CertificateException;
286import java.text.SimpleDateFormat;
287import java.util.ArrayList;
288import java.util.Arrays;
289import java.util.Collection;
290import java.util.Collections;
291import java.util.Comparator;
292import java.util.Date;
293import java.util.HashSet;
294import java.util.Iterator;
295import java.util.List;
296import java.util.Map;
297import java.util.Objects;
298import java.util.Set;
299import java.util.concurrent.CountDownLatch;
300import java.util.concurrent.TimeUnit;
301import java.util.concurrent.atomic.AtomicBoolean;
302import java.util.concurrent.atomic.AtomicInteger;
303
304/**
305 * Keep track of all those APKs everywhere.
306 * <p>
307 * Internally there are two important locks:
308 * <ul>
309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
310 * and other related state. It is a fine-grained lock that should only be held
311 * momentarily, as it's one of the most contended locks in the system.
312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
313 * operations typically involve heavy lifting of application data on disk. Since
314 * {@code installd} is single-threaded, and it's operations can often be slow,
315 * this lock should never be acquired while already holding {@link #mPackages}.
316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
317 * holding {@link #mInstallLock}.
318 * </ul>
319 * Many internal methods rely on the caller to hold the appropriate locks, and
320 * this contract is expressed through method name suffixes:
321 * <ul>
322 * <li>fooLI(): the caller must hold {@link #mInstallLock}
323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
324 * being modified must be frozen
325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
327 * </ul>
328 * <p>
329 * Because this class is very central to the platform's security; please run all
330 * CTS and unit tests whenever making modifications:
331 *
332 * <pre>
333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
335 * </pre>
336 */
337public class PackageManagerService extends IPackageManager.Stub {
338    static final String TAG = "PackageManager";
339    static final boolean DEBUG_SETTINGS = false;
340    static final boolean DEBUG_PREFERRED = false;
341    static final boolean DEBUG_UPGRADE = false;
342    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
343    private static final boolean DEBUG_BACKUP = false;
344    private static final boolean DEBUG_INSTALL = false;
345    private static final boolean DEBUG_REMOVE = false;
346    private static final boolean DEBUG_BROADCASTS = false;
347    private static final boolean DEBUG_SHOW_INFO = false;
348    private static final boolean DEBUG_PACKAGE_INFO = false;
349    private static final boolean DEBUG_INTENT_MATCHING = false;
350    private static final boolean DEBUG_PACKAGE_SCANNING = false;
351    private static final boolean DEBUG_VERIFY = false;
352    private static final boolean DEBUG_FILTERS = false;
353
354    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
355    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
356    // user, but by default initialize to this.
357    static final boolean DEBUG_DEXOPT = false;
358
359    private static final boolean DEBUG_ABI_SELECTION = false;
360    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
361    private static final boolean DEBUG_TRIAGED_MISSING = false;
362    private static final boolean DEBUG_APP_DATA = false;
363
364    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
365
366    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
367
368    private static final int RADIO_UID = Process.PHONE_UID;
369    private static final int LOG_UID = Process.LOG_UID;
370    private static final int NFC_UID = Process.NFC_UID;
371    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
372    private static final int SHELL_UID = Process.SHELL_UID;
373
374    // Cap the size of permission trees that 3rd party apps can define
375    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
376
377    // Suffix used during package installation when copying/moving
378    // package apks to install directory.
379    private static final String INSTALL_PACKAGE_SUFFIX = "-";
380
381    static final int SCAN_NO_DEX = 1<<1;
382    static final int SCAN_FORCE_DEX = 1<<2;
383    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
384    static final int SCAN_NEW_INSTALL = 1<<4;
385    static final int SCAN_NO_PATHS = 1<<5;
386    static final int SCAN_UPDATE_TIME = 1<<6;
387    static final int SCAN_DEFER_DEX = 1<<7;
388    static final int SCAN_BOOTING = 1<<8;
389    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
390    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
391    static final int SCAN_REPLACING = 1<<11;
392    static final int SCAN_REQUIRE_KNOWN = 1<<12;
393    static final int SCAN_MOVE = 1<<13;
394    static final int SCAN_INITIAL = 1<<14;
395    static final int SCAN_CHECK_ONLY = 1<<15;
396    static final int SCAN_DONT_KILL_APP = 1<<17;
397    static final int SCAN_IGNORE_FROZEN = 1<<18;
398
399    static final int REMOVE_CHATTY = 1<<16;
400
401    private static final int[] EMPTY_INT_ARRAY = new int[0];
402
403    /**
404     * Timeout (in milliseconds) after which the watchdog should declare that
405     * our handler thread is wedged.  The usual default for such things is one
406     * minute but we sometimes do very lengthy I/O operations on this thread,
407     * such as installing multi-gigabyte applications, so ours needs to be longer.
408     */
409    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
410
411    /**
412     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
413     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
414     * settings entry if available, otherwise we use the hardcoded default.  If it's been
415     * more than this long since the last fstrim, we force one during the boot sequence.
416     *
417     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
418     * one gets run at the next available charging+idle time.  This final mandatory
419     * no-fstrim check kicks in only of the other scheduling criteria is never met.
420     */
421    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
422
423    /**
424     * Whether verification is enabled by default.
425     */
426    private static final boolean DEFAULT_VERIFY_ENABLE = true;
427
428    /**
429     * The default maximum time to wait for the verification agent to return in
430     * milliseconds.
431     */
432    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
433
434    /**
435     * The default response for package verification timeout.
436     *
437     * This can be either PackageManager.VERIFICATION_ALLOW or
438     * PackageManager.VERIFICATION_REJECT.
439     */
440    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
441
442    static final String PLATFORM_PACKAGE_NAME = "android";
443
444    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
445
446    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
447            DEFAULT_CONTAINER_PACKAGE,
448            "com.android.defcontainer.DefaultContainerService");
449
450    private static final String KILL_APP_REASON_GIDS_CHANGED =
451            "permission grant or revoke changed gids";
452
453    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
454            "permissions revoked";
455
456    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
457
458    private static final String PACKAGE_SCHEME = "package";
459
460    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
461
462    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
463    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
464
465    /** Permission grant: not grant the permission. */
466    private static final int GRANT_DENIED = 1;
467
468    /** Permission grant: grant the permission as an install permission. */
469    private static final int GRANT_INSTALL = 2;
470
471    /** Permission grant: grant the permission as a runtime one. */
472    private static final int GRANT_RUNTIME = 3;
473
474    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475    private static final int GRANT_UPGRADE = 4;
476
477    /** Canonical intent used to identify what counts as a "web browser" app */
478    private static final Intent sBrowserIntent;
479    static {
480        sBrowserIntent = new Intent();
481        sBrowserIntent.setAction(Intent.ACTION_VIEW);
482        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483        sBrowserIntent.setData(Uri.parse("http:"));
484    }
485
486    /**
487     * The set of all protected actions [i.e. those actions for which a high priority
488     * intent filter is disallowed].
489     */
490    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491    static {
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496    }
497
498    // Compilation reasons.
499    public static final int REASON_FIRST_BOOT = 0;
500    public static final int REASON_BOOT = 1;
501    public static final int REASON_INSTALL = 2;
502    public static final int REASON_BACKGROUND_DEXOPT = 3;
503    public static final int REASON_AB_OTA = 4;
504    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505    public static final int REASON_SHARED_APK = 6;
506    public static final int REASON_FORCED_DEXOPT = 7;
507    public static final int REASON_CORE_APP = 8;
508
509    public static final int REASON_LAST = REASON_CORE_APP;
510
511    /** Special library name that skips shared libraries check during compilation. */
512    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514    final ServiceThread mHandlerThread;
515
516    final PackageHandler mHandler;
517
518    private final ProcessLoggingHandler mProcessLoggingHandler;
519
520    /**
521     * Messages for {@link #mHandler} that need to wait for system ready before
522     * being dispatched.
523     */
524    private ArrayList<Message> mPostSystemReadyMessages;
525
526    final int mSdkVersion = Build.VERSION.SDK_INT;
527
528    final Context mContext;
529    final boolean mFactoryTest;
530    final boolean mOnlyCore;
531    final DisplayMetrics mMetrics;
532    final int mDefParseFlags;
533    final String[] mSeparateProcesses;
534    final boolean mIsUpgrade;
535    final boolean mIsPreNUpgrade;
536    final boolean mIsPreNMR1Upgrade;
537
538    /** The location for ASEC container files on internal storage. */
539    final String mAsecInternalPath;
540
541    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
542    // LOCK HELD.  Can be called with mInstallLock held.
543    @GuardedBy("mInstallLock")
544    final Installer mInstaller;
545
546    /** Directory where installed third-party apps stored */
547    final File mAppInstallDir;
548    final File mEphemeralInstallDir;
549
550    /**
551     * Directory to which applications installed internally have their
552     * 32 bit native libraries copied.
553     */
554    private File mAppLib32InstallDir;
555
556    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
557    // apps.
558    final File mDrmAppPrivateInstallDir;
559
560    // ----------------------------------------------------------------
561
562    // Lock for state used when installing and doing other long running
563    // operations.  Methods that must be called with this lock held have
564    // the suffix "LI".
565    final Object mInstallLock = new Object();
566
567    // ----------------------------------------------------------------
568
569    // Keys are String (package name), values are Package.  This also serves
570    // as the lock for the global state.  Methods that must be called with
571    // this lock held have the prefix "LP".
572    @GuardedBy("mPackages")
573    final ArrayMap<String, PackageParser.Package> mPackages =
574            new ArrayMap<String, PackageParser.Package>();
575
576    final ArrayMap<String, Set<String>> mKnownCodebase =
577            new ArrayMap<String, Set<String>>();
578
579    // Tracks available target package names -> overlay package paths.
580    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
581        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
582
583    /**
584     * Tracks new system packages [received in an OTA] that we expect to
585     * find updated user-installed versions. Keys are package name, values
586     * are package location.
587     */
588    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
589    /**
590     * Tracks high priority intent filters for protected actions. During boot, certain
591     * filter actions are protected and should never be allowed to have a high priority
592     * intent filter for them. However, there is one, and only one exception -- the
593     * setup wizard. It must be able to define a high priority intent filter for these
594     * actions to ensure there are no escapes from the wizard. We need to delay processing
595     * of these during boot as we need to look at all of the system packages in order
596     * to know which component is the setup wizard.
597     */
598    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
599    /**
600     * Whether or not processing protected filters should be deferred.
601     */
602    private boolean mDeferProtectedFilters = true;
603
604    /**
605     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
606     */
607    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
608    /**
609     * Whether or not system app permissions should be promoted from install to runtime.
610     */
611    boolean mPromoteSystemApps;
612
613    @GuardedBy("mPackages")
614    final Settings mSettings;
615
616    /**
617     * Set of package names that are currently "frozen", which means active
618     * surgery is being done on the code/data for that package. The platform
619     * will refuse to launch frozen packages to avoid race conditions.
620     *
621     * @see PackageFreezer
622     */
623    @GuardedBy("mPackages")
624    final ArraySet<String> mFrozenPackages = new ArraySet<>();
625
626    final ProtectedPackages mProtectedPackages;
627
628    boolean mFirstBoot;
629
630    // System configuration read by SystemConfig.
631    final int[] mGlobalGids;
632    final SparseArray<ArraySet<String>> mSystemPermissions;
633    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
634
635    // If mac_permissions.xml was found for seinfo labeling.
636    boolean mFoundPolicyFile;
637
638    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
639
640    public static final class SharedLibraryEntry {
641        public final String path;
642        public final String apk;
643
644        SharedLibraryEntry(String _path, String _apk) {
645            path = _path;
646            apk = _apk;
647        }
648    }
649
650    // Currently known shared libraries.
651    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
652            new ArrayMap<String, SharedLibraryEntry>();
653
654    // All available activities, for your resolving pleasure.
655    final ActivityIntentResolver mActivities =
656            new ActivityIntentResolver();
657
658    // All available receivers, for your resolving pleasure.
659    final ActivityIntentResolver mReceivers =
660            new ActivityIntentResolver();
661
662    // All available services, for your resolving pleasure.
663    final ServiceIntentResolver mServices = new ServiceIntentResolver();
664
665    // All available providers, for your resolving pleasure.
666    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
667
668    // Mapping from provider base names (first directory in content URI codePath)
669    // to the provider information.
670    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
671            new ArrayMap<String, PackageParser.Provider>();
672
673    // Mapping from instrumentation class names to info about them.
674    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
675            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
676
677    // Mapping from permission names to info about them.
678    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
679            new ArrayMap<String, PackageParser.PermissionGroup>();
680
681    // Packages whose data we have transfered into another package, thus
682    // should no longer exist.
683    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
684
685    // Broadcast actions that are only available to the system.
686    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
687
688    /** List of packages waiting for verification. */
689    final SparseArray<PackageVerificationState> mPendingVerification
690            = new SparseArray<PackageVerificationState>();
691
692    /** Set of packages associated with each app op permission. */
693    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
694
695    final PackageInstallerService mInstallerService;
696
697    private final PackageDexOptimizer mPackageDexOptimizer;
698
699    private AtomicInteger mNextMoveId = new AtomicInteger();
700    private final MoveCallbacks mMoveCallbacks;
701
702    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
703
704    // Cache of users who need badging.
705    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
706
707    /** Token for keys in mPendingVerification. */
708    private int mPendingVerificationToken = 0;
709
710    volatile boolean mSystemReady;
711    volatile boolean mSafeMode;
712    volatile boolean mHasSystemUidErrors;
713
714    ApplicationInfo mAndroidApplication;
715    final ActivityInfo mResolveActivity = new ActivityInfo();
716    final ResolveInfo mResolveInfo = new ResolveInfo();
717    ComponentName mResolveComponentName;
718    PackageParser.Package mPlatformPackage;
719    ComponentName mCustomResolverComponentName;
720
721    boolean mResolverReplaced = false;
722
723    private final @Nullable ComponentName mIntentFilterVerifierComponent;
724    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
725
726    private int mIntentFilterVerificationToken = 0;
727
728    /** Component that knows whether or not an ephemeral application exists */
729    final ComponentName mEphemeralResolverComponent;
730    /** The service connection to the ephemeral resolver */
731    final EphemeralResolverConnection mEphemeralResolverConnection;
732
733    /** Component used to install ephemeral applications */
734    final ComponentName mEphemeralInstallerComponent;
735    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
736    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
737
738    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
739            = new SparseArray<IntentFilterVerificationState>();
740
741    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
742
743    // List of packages names to keep cached, even if they are uninstalled for all users
744    private List<String> mKeepUninstalledPackages;
745
746    private UserManagerInternal mUserManagerInternal;
747
748    private static class IFVerificationParams {
749        PackageParser.Package pkg;
750        boolean replacing;
751        int userId;
752        int verifierUid;
753
754        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                int _userId, int _verifierUid) {
756            pkg = _pkg;
757            replacing = _replacing;
758            userId = _userId;
759            replacing = _replacing;
760            verifierUid = _verifierUid;
761        }
762    }
763
764    private interface IntentFilterVerifier<T extends IntentFilter> {
765        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                               T filter, String packageName);
767        void startVerifications(int userId);
768        void receiveVerificationResponse(int verificationId);
769    }
770
771    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772        private Context mContext;
773        private ComponentName mIntentFilterVerifierComponent;
774        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777            mContext = context;
778            mIntentFilterVerifierComponent = verifierComponent;
779        }
780
781        private String getDefaultScheme() {
782            return IntentFilter.SCHEME_HTTPS;
783        }
784
785        @Override
786        public void startVerifications(int userId) {
787            // Launch verifications requests
788            int count = mCurrentIntentFilterVerifications.size();
789            for (int n=0; n<count; n++) {
790                int verificationId = mCurrentIntentFilterVerifications.get(n);
791                final IntentFilterVerificationState ivs =
792                        mIntentFilterVerificationStates.get(verificationId);
793
794                String packageName = ivs.getPackageName();
795
796                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                final int filterCount = filters.size();
798                ArraySet<String> domainsSet = new ArraySet<>();
799                for (int m=0; m<filterCount; m++) {
800                    PackageParser.ActivityIntentInfo filter = filters.get(m);
801                    domainsSet.addAll(filter.getHostsList());
802                }
803                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                synchronized (mPackages) {
805                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                            packageName, domainsList) != null) {
807                        scheduleWriteSettingsLocked();
808                    }
809                }
810                sendVerificationRequest(userId, verificationId, ivs);
811            }
812            mCurrentIntentFilterVerifications.clear();
813        }
814
815        private void sendVerificationRequest(int userId, int verificationId,
816                IntentFilterVerificationState ivs) {
817
818            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819            verificationIntent.putExtra(
820                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                    verificationId);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                    getDefaultScheme());
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                    ivs.getHostsString());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                    ivs.getPackageName());
831            verificationIntent.setComponent(mIntentFilterVerifierComponent);
832            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834            UserHandle user = new UserHandle(userId);
835            mContext.sendBroadcastAsUser(verificationIntent, user);
836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                    "Sending IntentFilter verification broadcast");
838        }
839
840        public void receiveVerificationResponse(int verificationId) {
841            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843            final boolean verified = ivs.isVerified();
844
845            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846            final int count = filters.size();
847            if (DEBUG_DOMAIN_VERIFICATION) {
848                Slog.i(TAG, "Received verification response " + verificationId
849                        + " for " + count + " filters, verified=" + verified);
850            }
851            for (int n=0; n<count; n++) {
852                PackageParser.ActivityIntentInfo filter = filters.get(n);
853                filter.setVerified(verified);
854
855                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                        + " verified with result:" + verified + " and hosts:"
857                        + ivs.getHostsString());
858            }
859
860            mIntentFilterVerificationStates.remove(verificationId);
861
862            final String packageName = ivs.getPackageName();
863            IntentFilterVerificationInfo ivi = null;
864
865            synchronized (mPackages) {
866                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867            }
868            if (ivi == null) {
869                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                        + verificationId + " packageName:" + packageName);
871                return;
872            }
873            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                    "Updating IntentFilterVerificationInfo for package " + packageName
875                            +" verificationId:" + verificationId);
876
877            synchronized (mPackages) {
878                if (verified) {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                } else {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                }
883                scheduleWriteSettingsLocked();
884
885                final int userId = ivs.getUserId();
886                if (userId != UserHandle.USER_ALL) {
887                    final int userStatus =
888                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                    boolean needUpdate = false;
892
893                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                    // already been set by the User thru the Disambiguation dialog
895                    switch (userStatus) {
896                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                            if (verified) {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                            } else {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                            }
902                            needUpdate = true;
903                            break;
904
905                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                            if (verified) {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                needUpdate = true;
909                            }
910                            break;
911
912                        default:
913                            // Nothing to do
914                    }
915
916                    if (needUpdate) {
917                        mSettings.updateIntentFilterVerificationStatusLPw(
918                                packageName, updatedStatus, userId);
919                        scheduleWritePackageRestrictionsLocked(userId);
920                    }
921                }
922            }
923        }
924
925        @Override
926        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                    ActivityIntentInfo filter, String packageName) {
928            if (!hasValidDomains(filter)) {
929                return false;
930            }
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932            if (ivs == null) {
933                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                        packageName);
935            }
936            if (DEBUG_DOMAIN_VERIFICATION) {
937                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938            }
939            ivs.addFilter(filter);
940            return true;
941        }
942
943        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                int userId, int verificationId, String packageName) {
945            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                    verifierUid, userId, packageName);
947            ivs.setPendingState();
948            synchronized (mPackages) {
949                mIntentFilterVerificationStates.append(verificationId, ivs);
950                mCurrentIntentFilterVerifications.add(verificationId);
951            }
952            return ivs;
953        }
954    }
955
956    private static boolean hasValidDomains(ActivityIntentInfo filter) {
957        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960    }
961
962    // Set of pending broadcasts for aggregating enable/disable of components.
963    static class PendingPackageBroadcasts {
964        // for each user id, a map of <package name -> components within that package>
965        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967        public PendingPackageBroadcasts() {
968            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969        }
970
971        public ArrayList<String> get(int userId, String packageName) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            return packages.get(packageName);
974        }
975
976        public void put(int userId, String packageName, ArrayList<String> components) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            packages.put(packageName, components);
979        }
980
981        public void remove(int userId, String packageName) {
982            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983            if (packages != null) {
984                packages.remove(packageName);
985            }
986        }
987
988        public void remove(int userId) {
989            mUidMap.remove(userId);
990        }
991
992        public int userIdCount() {
993            return mUidMap.size();
994        }
995
996        public int userIdAt(int n) {
997            return mUidMap.keyAt(n);
998        }
999
1000        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001            return mUidMap.get(userId);
1002        }
1003
1004        public int size() {
1005            // total number of pending broadcast entries across all userIds
1006            int num = 0;
1007            for (int i = 0; i< mUidMap.size(); i++) {
1008                num += mUidMap.valueAt(i).size();
1009            }
1010            return num;
1011        }
1012
1013        public void clear() {
1014            mUidMap.clear();
1015        }
1016
1017        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019            if (map == null) {
1020                map = new ArrayMap<String, ArrayList<String>>();
1021                mUidMap.put(userId, map);
1022            }
1023            return map;
1024        }
1025    }
1026    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028    // Service Connection to remote media container service to copy
1029    // package uri's from external media onto secure containers
1030    // or internal storage.
1031    private IMediaContainerService mContainerService = null;
1032
1033    static final int SEND_PENDING_BROADCAST = 1;
1034    static final int MCS_BOUND = 3;
1035    static final int END_COPY = 4;
1036    static final int INIT_COPY = 5;
1037    static final int MCS_UNBIND = 6;
1038    static final int START_CLEANING_PACKAGE = 7;
1039    static final int FIND_INSTALL_LOC = 8;
1040    static final int POST_INSTALL = 9;
1041    static final int MCS_RECONNECT = 10;
1042    static final int MCS_GIVE_UP = 11;
1043    static final int UPDATED_MEDIA_STATUS = 12;
1044    static final int WRITE_SETTINGS = 13;
1045    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046    static final int PACKAGE_VERIFIED = 15;
1047    static final int CHECK_PENDING_VERIFICATION = 16;
1048    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049    static final int INTENT_FILTER_VERIFIED = 18;
1050    static final int WRITE_PACKAGE_LIST = 19;
1051
1052    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054    // Delay time in millisecs
1055    static final int BROADCAST_DELAY = 10 * 1000;
1056
1057    static UserManagerService sUserManager;
1058
1059    // Stores a list of users whose package restrictions file needs to be updated
1060    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062    final private DefaultContainerConnection mDefContainerConn =
1063            new DefaultContainerConnection();
1064    class DefaultContainerConnection implements ServiceConnection {
1065        public void onServiceConnected(ComponentName name, IBinder service) {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067            IMediaContainerService imcs =
1068                IMediaContainerService.Stub.asInterface(service);
1069            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070        }
1071
1072        public void onServiceDisconnected(ComponentName name) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074        }
1075    }
1076
1077    // Recordkeeping of restore-after-install operations that are currently in flight
1078    // between the Package Manager and the Backup Manager
1079    static class PostInstallData {
1080        public InstallArgs args;
1081        public PackageInstalledInfo res;
1082
1083        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084            args = _a;
1085            res = _r;
1086        }
1087    }
1088
1089    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092    // XML tags for backup/restore of various bits of state
1093    private static final String TAG_PREFERRED_BACKUP = "pa";
1094    private static final String TAG_DEFAULT_APPS = "da";
1095    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098    private static final String TAG_ALL_GRANTS = "rt-grants";
1099    private static final String TAG_GRANT = "grant";
1100    private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102    private static final String TAG_PERMISSION = "perm";
1103    private static final String ATTR_PERMISSION_NAME = "name";
1104    private static final String ATTR_IS_GRANTED = "g";
1105    private static final String ATTR_USER_SET = "set";
1106    private static final String ATTR_USER_FIXED = "fixed";
1107    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109    // System/policy permission grants are not backed up
1110    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111            FLAG_PERMISSION_POLICY_FIXED
1112            | FLAG_PERMISSION_SYSTEM_FIXED
1113            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115    // And we back up these user-adjusted states
1116    private static final int USER_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_USER_SET
1118            | FLAG_PERMISSION_USER_FIXED
1119            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121    final @Nullable String mRequiredVerifierPackage;
1122    final @NonNull String mRequiredInstallerPackage;
1123    final @NonNull String mRequiredUninstallerPackage;
1124    final @Nullable String mSetupWizardPackage;
1125    final @NonNull String mServicesSystemSharedLibraryPackageName;
1126    final @NonNull String mSharedSystemSharedLibraryPackageName;
1127
1128    private final PackageUsage mPackageUsage = new PackageUsage();
1129    private final CompilerStats mCompilerStats = new CompilerStats();
1130
1131    class PackageHandler extends Handler {
1132        private boolean mBound = false;
1133        final ArrayList<HandlerParams> mPendingInstalls =
1134            new ArrayList<HandlerParams>();
1135
1136        private boolean connectToService() {
1137            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1138                    " DefaultContainerService");
1139            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1141            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1142                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1143                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1144                mBound = true;
1145                return true;
1146            }
1147            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1148            return false;
1149        }
1150
1151        private void disconnectService() {
1152            mContainerService = null;
1153            mBound = false;
1154            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1155            mContext.unbindService(mDefContainerConn);
1156            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1157        }
1158
1159        PackageHandler(Looper looper) {
1160            super(looper);
1161        }
1162
1163        public void handleMessage(Message msg) {
1164            try {
1165                doHandleMessage(msg);
1166            } finally {
1167                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1168            }
1169        }
1170
1171        void doHandleMessage(Message msg) {
1172            switch (msg.what) {
1173                case INIT_COPY: {
1174                    HandlerParams params = (HandlerParams) msg.obj;
1175                    int idx = mPendingInstalls.size();
1176                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1177                    // If a bind was already initiated we dont really
1178                    // need to do anything. The pending install
1179                    // will be processed later on.
1180                    if (!mBound) {
1181                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1182                                System.identityHashCode(mHandler));
1183                        // If this is the only one pending we might
1184                        // have to bind to the service again.
1185                        if (!connectToService()) {
1186                            Slog.e(TAG, "Failed to bind to media container service");
1187                            params.serviceError();
1188                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1189                                    System.identityHashCode(mHandler));
1190                            if (params.traceMethod != null) {
1191                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1192                                        params.traceCookie);
1193                            }
1194                            return;
1195                        } else {
1196                            // Once we bind to the service, the first
1197                            // pending request will be processed.
1198                            mPendingInstalls.add(idx, params);
1199                        }
1200                    } else {
1201                        mPendingInstalls.add(idx, params);
1202                        // Already bound to the service. Just make
1203                        // sure we trigger off processing the first request.
1204                        if (idx == 0) {
1205                            mHandler.sendEmptyMessage(MCS_BOUND);
1206                        }
1207                    }
1208                    break;
1209                }
1210                case MCS_BOUND: {
1211                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1212                    if (msg.obj != null) {
1213                        mContainerService = (IMediaContainerService) msg.obj;
1214                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1215                                System.identityHashCode(mHandler));
1216                    }
1217                    if (mContainerService == null) {
1218                        if (!mBound) {
1219                            // Something seriously wrong since we are not bound and we are not
1220                            // waiting for connection. Bail out.
1221                            Slog.e(TAG, "Cannot bind to media container service");
1222                            for (HandlerParams params : mPendingInstalls) {
1223                                // Indicate service bind error
1224                                params.serviceError();
1225                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1226                                        System.identityHashCode(params));
1227                                if (params.traceMethod != null) {
1228                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1229                                            params.traceMethod, params.traceCookie);
1230                                }
1231                                return;
1232                            }
1233                            mPendingInstalls.clear();
1234                        } else {
1235                            Slog.w(TAG, "Waiting to connect to media container service");
1236                        }
1237                    } else if (mPendingInstalls.size() > 0) {
1238                        HandlerParams params = mPendingInstalls.get(0);
1239                        if (params != null) {
1240                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1241                                    System.identityHashCode(params));
1242                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1243                            if (params.startCopy()) {
1244                                // We are done...  look for more work or to
1245                                // go idle.
1246                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1247                                        "Checking for more work or unbind...");
1248                                // Delete pending install
1249                                if (mPendingInstalls.size() > 0) {
1250                                    mPendingInstalls.remove(0);
1251                                }
1252                                if (mPendingInstalls.size() == 0) {
1253                                    if (mBound) {
1254                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1255                                                "Posting delayed MCS_UNBIND");
1256                                        removeMessages(MCS_UNBIND);
1257                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1258                                        // Unbind after a little delay, to avoid
1259                                        // continual thrashing.
1260                                        sendMessageDelayed(ubmsg, 10000);
1261                                    }
1262                                } else {
1263                                    // There are more pending requests in queue.
1264                                    // Just post MCS_BOUND message to trigger processing
1265                                    // of next pending install.
1266                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1267                                            "Posting MCS_BOUND for next work");
1268                                    mHandler.sendEmptyMessage(MCS_BOUND);
1269                                }
1270                            }
1271                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1272                        }
1273                    } else {
1274                        // Should never happen ideally.
1275                        Slog.w(TAG, "Empty queue");
1276                    }
1277                    break;
1278                }
1279                case MCS_RECONNECT: {
1280                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1281                    if (mPendingInstalls.size() > 0) {
1282                        if (mBound) {
1283                            disconnectService();
1284                        }
1285                        if (!connectToService()) {
1286                            Slog.e(TAG, "Failed to bind to media container service");
1287                            for (HandlerParams params : mPendingInstalls) {
1288                                // Indicate service bind error
1289                                params.serviceError();
1290                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1291                                        System.identityHashCode(params));
1292                            }
1293                            mPendingInstalls.clear();
1294                        }
1295                    }
1296                    break;
1297                }
1298                case MCS_UNBIND: {
1299                    // If there is no actual work left, then time to unbind.
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1301
1302                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1303                        if (mBound) {
1304                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1305
1306                            disconnectService();
1307                        }
1308                    } else if (mPendingInstalls.size() > 0) {
1309                        // There are more pending requests in queue.
1310                        // Just post MCS_BOUND message to trigger processing
1311                        // of next pending install.
1312                        mHandler.sendEmptyMessage(MCS_BOUND);
1313                    }
1314
1315                    break;
1316                }
1317                case MCS_GIVE_UP: {
1318                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1319                    HandlerParams params = mPendingInstalls.remove(0);
1320                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1321                            System.identityHashCode(params));
1322                    break;
1323                }
1324                case SEND_PENDING_BROADCAST: {
1325                    String packages[];
1326                    ArrayList<String> components[];
1327                    int size = 0;
1328                    int uids[];
1329                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1330                    synchronized (mPackages) {
1331                        if (mPendingBroadcasts == null) {
1332                            return;
1333                        }
1334                        size = mPendingBroadcasts.size();
1335                        if (size <= 0) {
1336                            // Nothing to be done. Just return
1337                            return;
1338                        }
1339                        packages = new String[size];
1340                        components = new ArrayList[size];
1341                        uids = new int[size];
1342                        int i = 0;  // filling out the above arrays
1343
1344                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1345                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1346                            Iterator<Map.Entry<String, ArrayList<String>>> it
1347                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1348                                            .entrySet().iterator();
1349                            while (it.hasNext() && i < size) {
1350                                Map.Entry<String, ArrayList<String>> ent = it.next();
1351                                packages[i] = ent.getKey();
1352                                components[i] = ent.getValue();
1353                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1354                                uids[i] = (ps != null)
1355                                        ? UserHandle.getUid(packageUserId, ps.appId)
1356                                        : -1;
1357                                i++;
1358                            }
1359                        }
1360                        size = i;
1361                        mPendingBroadcasts.clear();
1362                    }
1363                    // Send broadcasts
1364                    for (int i = 0; i < size; i++) {
1365                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1366                    }
1367                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1368                    break;
1369                }
1370                case START_CLEANING_PACKAGE: {
1371                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1372                    final String packageName = (String)msg.obj;
1373                    final int userId = msg.arg1;
1374                    final boolean andCode = msg.arg2 != 0;
1375                    synchronized (mPackages) {
1376                        if (userId == UserHandle.USER_ALL) {
1377                            int[] users = sUserManager.getUserIds();
1378                            for (int user : users) {
1379                                mSettings.addPackageToCleanLPw(
1380                                        new PackageCleanItem(user, packageName, andCode));
1381                            }
1382                        } else {
1383                            mSettings.addPackageToCleanLPw(
1384                                    new PackageCleanItem(userId, packageName, andCode));
1385                        }
1386                    }
1387                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1388                    startCleaningPackages();
1389                } break;
1390                case POST_INSTALL: {
1391                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1392
1393                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1394                    final boolean didRestore = (msg.arg2 != 0);
1395                    mRunningInstalls.delete(msg.arg1);
1396
1397                    if (data != null) {
1398                        InstallArgs args = data.args;
1399                        PackageInstalledInfo parentRes = data.res;
1400
1401                        final boolean grantPermissions = (args.installFlags
1402                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1403                        final boolean killApp = (args.installFlags
1404                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1405                        final String[] grantedPermissions = args.installGrantPermissions;
1406
1407                        // Handle the parent package
1408                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1409                                grantedPermissions, didRestore, args.installerPackageName,
1410                                args.observer);
1411
1412                        // Handle the child packages
1413                        final int childCount = (parentRes.addedChildPackages != null)
1414                                ? parentRes.addedChildPackages.size() : 0;
1415                        for (int i = 0; i < childCount; i++) {
1416                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1417                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1418                                    grantedPermissions, false, args.installerPackageName,
1419                                    args.observer);
1420                        }
1421
1422                        // Log tracing if needed
1423                        if (args.traceMethod != null) {
1424                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1425                                    args.traceCookie);
1426                        }
1427                    } else {
1428                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1429                    }
1430
1431                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1432                } break;
1433                case UPDATED_MEDIA_STATUS: {
1434                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1435                    boolean reportStatus = msg.arg1 == 1;
1436                    boolean doGc = msg.arg2 == 1;
1437                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1438                    if (doGc) {
1439                        // Force a gc to clear up stale containers.
1440                        Runtime.getRuntime().gc();
1441                    }
1442                    if (msg.obj != null) {
1443                        @SuppressWarnings("unchecked")
1444                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1445                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1446                        // Unload containers
1447                        unloadAllContainers(args);
1448                    }
1449                    if (reportStatus) {
1450                        try {
1451                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1452                            PackageHelper.getMountService().finishMediaUpdate();
1453                        } catch (RemoteException e) {
1454                            Log.e(TAG, "MountService not running?");
1455                        }
1456                    }
1457                } break;
1458                case WRITE_SETTINGS: {
1459                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1460                    synchronized (mPackages) {
1461                        removeMessages(WRITE_SETTINGS);
1462                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1463                        mSettings.writeLPr();
1464                        mDirtyUsers.clear();
1465                    }
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1467                } break;
1468                case WRITE_PACKAGE_RESTRICTIONS: {
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470                    synchronized (mPackages) {
1471                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1472                        for (int userId : mDirtyUsers) {
1473                            mSettings.writePackageRestrictionsLPr(userId);
1474                        }
1475                        mDirtyUsers.clear();
1476                    }
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478                } break;
1479                case WRITE_PACKAGE_LIST: {
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1481                    synchronized (mPackages) {
1482                        removeMessages(WRITE_PACKAGE_LIST);
1483                        mSettings.writePackageListLPr(msg.arg1);
1484                    }
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1486                } break;
1487                case CHECK_PENDING_VERIFICATION: {
1488                    final int verificationId = msg.arg1;
1489                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1490
1491                    if ((state != null) && !state.timeoutExtended()) {
1492                        final InstallArgs args = state.getInstallArgs();
1493                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1494
1495                        Slog.i(TAG, "Verification timed out for " + originUri);
1496                        mPendingVerification.remove(verificationId);
1497
1498                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1499
1500                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1501                            Slog.i(TAG, "Continuing with installation of " + originUri);
1502                            state.setVerifierResponse(Binder.getCallingUid(),
1503                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1504                            broadcastPackageVerified(verificationId, originUri,
1505                                    PackageManager.VERIFICATION_ALLOW,
1506                                    state.getInstallArgs().getUser());
1507                            try {
1508                                ret = args.copyApk(mContainerService, true);
1509                            } catch (RemoteException e) {
1510                                Slog.e(TAG, "Could not contact the ContainerService");
1511                            }
1512                        } else {
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    PackageManager.VERIFICATION_REJECT,
1515                                    state.getInstallArgs().getUser());
1516                        }
1517
1518                        Trace.asyncTraceEnd(
1519                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1520
1521                        processPendingInstall(args, ret);
1522                        mHandler.sendEmptyMessage(MCS_UNBIND);
1523                    }
1524                    break;
1525                }
1526                case PACKAGE_VERIFIED: {
1527                    final int verificationId = msg.arg1;
1528
1529                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1530                    if (state == null) {
1531                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1532                        break;
1533                    }
1534
1535                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1536
1537                    state.setVerifierResponse(response.callerUid, response.code);
1538
1539                    if (state.isVerificationComplete()) {
1540                        mPendingVerification.remove(verificationId);
1541
1542                        final InstallArgs args = state.getInstallArgs();
1543                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1544
1545                        int ret;
1546                        if (state.isInstallAllowed()) {
1547                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1548                            broadcastPackageVerified(verificationId, originUri,
1549                                    response.code, state.getInstallArgs().getUser());
1550                            try {
1551                                ret = args.copyApk(mContainerService, true);
1552                            } catch (RemoteException e) {
1553                                Slog.e(TAG, "Could not contact the ContainerService");
1554                            }
1555                        } else {
1556                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1557                        }
1558
1559                        Trace.asyncTraceEnd(
1560                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1561
1562                        processPendingInstall(args, ret);
1563                        mHandler.sendEmptyMessage(MCS_UNBIND);
1564                    }
1565
1566                    break;
1567                }
1568                case START_INTENT_FILTER_VERIFICATIONS: {
1569                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1570                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1571                            params.replacing, params.pkg);
1572                    break;
1573                }
1574                case INTENT_FILTER_VERIFIED: {
1575                    final int verificationId = msg.arg1;
1576
1577                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1578                            verificationId);
1579                    if (state == null) {
1580                        Slog.w(TAG, "Invalid IntentFilter verification token "
1581                                + verificationId + " received");
1582                        break;
1583                    }
1584
1585                    final int userId = state.getUserId();
1586
1587                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1588                            "Processing IntentFilter verification with token:"
1589                            + verificationId + " and userId:" + userId);
1590
1591                    final IntentFilterVerificationResponse response =
1592                            (IntentFilterVerificationResponse) msg.obj;
1593
1594                    state.setVerifierResponse(response.callerUid, response.code);
1595
1596                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1597                            "IntentFilter verification with token:" + verificationId
1598                            + " and userId:" + userId
1599                            + " is settings verifier response with response code:"
1600                            + response.code);
1601
1602                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1603                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1604                                + response.getFailedDomainsString());
1605                    }
1606
1607                    if (state.isVerificationComplete()) {
1608                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1609                    } else {
1610                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                                "IntentFilter verification with token:" + verificationId
1612                                + " was not said to be complete");
1613                    }
1614
1615                    break;
1616                }
1617            }
1618        }
1619    }
1620
1621    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1622            boolean killApp, String[] grantedPermissions,
1623            boolean launchedForRestore, String installerPackage,
1624            IPackageInstallObserver2 installObserver) {
1625        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1626            // Send the removed broadcasts
1627            if (res.removedInfo != null) {
1628                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1629            }
1630
1631            // Now that we successfully installed the package, grant runtime
1632            // permissions if requested before broadcasting the install.
1633            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1634                    >= Build.VERSION_CODES.M) {
1635                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1636            }
1637
1638            final boolean update = res.removedInfo != null
1639                    && res.removedInfo.removedPackage != null;
1640
1641            // If this is the first time we have child packages for a disabled privileged
1642            // app that had no children, we grant requested runtime permissions to the new
1643            // children if the parent on the system image had them already granted.
1644            if (res.pkg.parentPackage != null) {
1645                synchronized (mPackages) {
1646                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1647                }
1648            }
1649
1650            synchronized (mPackages) {
1651                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1652            }
1653
1654            final String packageName = res.pkg.applicationInfo.packageName;
1655            Bundle extras = new Bundle(1);
1656            extras.putInt(Intent.EXTRA_UID, res.uid);
1657
1658            // Determine the set of users who are adding this package for
1659            // the first time vs. those who are seeing an update.
1660            int[] firstUsers = EMPTY_INT_ARRAY;
1661            int[] updateUsers = EMPTY_INT_ARRAY;
1662            if (res.origUsers == null || res.origUsers.length == 0) {
1663                firstUsers = res.newUsers;
1664            } else {
1665                for (int newUser : res.newUsers) {
1666                    boolean isNew = true;
1667                    for (int origUser : res.origUsers) {
1668                        if (origUser == newUser) {
1669                            isNew = false;
1670                            break;
1671                        }
1672                    }
1673                    if (isNew) {
1674                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1675                    } else {
1676                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1677                    }
1678                }
1679            }
1680
1681            // Send installed broadcasts if the install/update is not ephemeral
1682            if (!isEphemeral(res.pkg)) {
1683                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1684
1685                // Send added for users that see the package for the first time
1686                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1687                        extras, 0 /*flags*/, null /*targetPackage*/,
1688                        null /*finishedReceiver*/, firstUsers);
1689
1690                // Send added for users that don't see the package for the first time
1691                if (update) {
1692                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1693                }
1694                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1695                        extras, 0 /*flags*/, null /*targetPackage*/,
1696                        null /*finishedReceiver*/, updateUsers);
1697
1698                // Send replaced for users that don't see the package for the first time
1699                if (update) {
1700                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1701                            packageName, extras, 0 /*flags*/,
1702                            null /*targetPackage*/, null /*finishedReceiver*/,
1703                            updateUsers);
1704                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1705                            null /*package*/, null /*extras*/, 0 /*flags*/,
1706                            packageName /*targetPackage*/,
1707                            null /*finishedReceiver*/, updateUsers);
1708                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1709                    // First-install and we did a restore, so we're responsible for the
1710                    // first-launch broadcast.
1711                    if (DEBUG_BACKUP) {
1712                        Slog.i(TAG, "Post-restore of " + packageName
1713                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1714                    }
1715                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1716                }
1717
1718                // Send broadcast package appeared if forward locked/external for all users
1719                // treat asec-hosted packages like removable media on upgrade
1720                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1721                    if (DEBUG_INSTALL) {
1722                        Slog.i(TAG, "upgrading pkg " + res.pkg
1723                                + " is ASEC-hosted -> AVAILABLE");
1724                    }
1725                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1726                    ArrayList<String> pkgList = new ArrayList<>(1);
1727                    pkgList.add(packageName);
1728                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1729                }
1730            }
1731
1732            // Work that needs to happen on first install within each user
1733            if (firstUsers != null && firstUsers.length > 0) {
1734                synchronized (mPackages) {
1735                    for (int userId : firstUsers) {
1736                        // If this app is a browser and it's newly-installed for some
1737                        // users, clear any default-browser state in those users. The
1738                        // app's nature doesn't depend on the user, so we can just check
1739                        // its browser nature in any user and generalize.
1740                        if (packageIsBrowser(packageName, userId)) {
1741                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1742                        }
1743
1744                        // We may also need to apply pending (restored) runtime
1745                        // permission grants within these users.
1746                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1747                    }
1748                }
1749            }
1750
1751            // Log current value of "unknown sources" setting
1752            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1753                    getUnknownSourcesSettings());
1754
1755            // Force a gc to clear up things
1756            Runtime.getRuntime().gc();
1757
1758            // Remove the replaced package's older resources safely now
1759            // We delete after a gc for applications  on sdcard.
1760            if (res.removedInfo != null && res.removedInfo.args != null) {
1761                synchronized (mInstallLock) {
1762                    res.removedInfo.args.doPostDeleteLI(true);
1763                }
1764            }
1765        }
1766
1767        // If someone is watching installs - notify them
1768        if (installObserver != null) {
1769            try {
1770                Bundle extras = extrasForInstallResult(res);
1771                installObserver.onPackageInstalled(res.name, res.returnCode,
1772                        res.returnMsg, extras);
1773            } catch (RemoteException e) {
1774                Slog.i(TAG, "Observer no longer exists.");
1775            }
1776        }
1777    }
1778
1779    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1780            PackageParser.Package pkg) {
1781        if (pkg.parentPackage == null) {
1782            return;
1783        }
1784        if (pkg.requestedPermissions == null) {
1785            return;
1786        }
1787        final PackageSetting disabledSysParentPs = mSettings
1788                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1789        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1790                || !disabledSysParentPs.isPrivileged()
1791                || (disabledSysParentPs.childPackageNames != null
1792                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1793            return;
1794        }
1795        final int[] allUserIds = sUserManager.getUserIds();
1796        final int permCount = pkg.requestedPermissions.size();
1797        for (int i = 0; i < permCount; i++) {
1798            String permission = pkg.requestedPermissions.get(i);
1799            BasePermission bp = mSettings.mPermissions.get(permission);
1800            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1801                continue;
1802            }
1803            for (int userId : allUserIds) {
1804                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1805                        permission, userId)) {
1806                    grantRuntimePermission(pkg.packageName, permission, userId);
1807                }
1808            }
1809        }
1810    }
1811
1812    private StorageEventListener mStorageListener = new StorageEventListener() {
1813        @Override
1814        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1815            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1816                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1817                    final String volumeUuid = vol.getFsUuid();
1818
1819                    // Clean up any users or apps that were removed or recreated
1820                    // while this volume was missing
1821                    reconcileUsers(volumeUuid);
1822                    reconcileApps(volumeUuid);
1823
1824                    // Clean up any install sessions that expired or were
1825                    // cancelled while this volume was missing
1826                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1827
1828                    loadPrivatePackages(vol);
1829
1830                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1831                    unloadPrivatePackages(vol);
1832                }
1833            }
1834
1835            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1836                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1837                    updateExternalMediaStatus(true, false);
1838                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1839                    updateExternalMediaStatus(false, false);
1840                }
1841            }
1842        }
1843
1844        @Override
1845        public void onVolumeForgotten(String fsUuid) {
1846            if (TextUtils.isEmpty(fsUuid)) {
1847                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1848                return;
1849            }
1850
1851            // Remove any apps installed on the forgotten volume
1852            synchronized (mPackages) {
1853                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1854                for (PackageSetting ps : packages) {
1855                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1856                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1857                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1858                }
1859
1860                mSettings.onVolumeForgotten(fsUuid);
1861                mSettings.writeLPr();
1862            }
1863        }
1864    };
1865
1866    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1867            String[] grantedPermissions) {
1868        for (int userId : userIds) {
1869            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1870        }
1871
1872        // We could have touched GID membership, so flush out packages.list
1873        synchronized (mPackages) {
1874            mSettings.writePackageListLPr();
1875        }
1876    }
1877
1878    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1879            String[] grantedPermissions) {
1880        SettingBase sb = (SettingBase) pkg.mExtras;
1881        if (sb == null) {
1882            return;
1883        }
1884
1885        PermissionsState permissionsState = sb.getPermissionsState();
1886
1887        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1888                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1889
1890        for (String permission : pkg.requestedPermissions) {
1891            final BasePermission bp;
1892            synchronized (mPackages) {
1893                bp = mSettings.mPermissions.get(permission);
1894            }
1895            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1896                    && (grantedPermissions == null
1897                           || ArrayUtils.contains(grantedPermissions, permission))) {
1898                final int flags = permissionsState.getPermissionFlags(permission, userId);
1899                // Installer cannot change immutable permissions.
1900                if ((flags & immutableFlags) == 0) {
1901                    grantRuntimePermission(pkg.packageName, permission, userId);
1902                }
1903            }
1904        }
1905    }
1906
1907    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1908        Bundle extras = null;
1909        switch (res.returnCode) {
1910            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1911                extras = new Bundle();
1912                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1913                        res.origPermission);
1914                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1915                        res.origPackage);
1916                break;
1917            }
1918            case PackageManager.INSTALL_SUCCEEDED: {
1919                extras = new Bundle();
1920                extras.putBoolean(Intent.EXTRA_REPLACING,
1921                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1922                break;
1923            }
1924        }
1925        return extras;
1926    }
1927
1928    void scheduleWriteSettingsLocked() {
1929        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1930            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1931        }
1932    }
1933
1934    void scheduleWritePackageListLocked(int userId) {
1935        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1936            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1937            msg.arg1 = userId;
1938            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1939        }
1940    }
1941
1942    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1943        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1944        scheduleWritePackageRestrictionsLocked(userId);
1945    }
1946
1947    void scheduleWritePackageRestrictionsLocked(int userId) {
1948        final int[] userIds = (userId == UserHandle.USER_ALL)
1949                ? sUserManager.getUserIds() : new int[]{userId};
1950        for (int nextUserId : userIds) {
1951            if (!sUserManager.exists(nextUserId)) return;
1952            mDirtyUsers.add(nextUserId);
1953            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1954                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1955            }
1956        }
1957    }
1958
1959    public static PackageManagerService main(Context context, Installer installer,
1960            boolean factoryTest, boolean onlyCore) {
1961        // Self-check for initial settings.
1962        PackageManagerServiceCompilerMapping.checkProperties();
1963
1964        PackageManagerService m = new PackageManagerService(context, installer,
1965                factoryTest, onlyCore);
1966        m.enableSystemUserPackages();
1967        ServiceManager.addService("package", m);
1968        return m;
1969    }
1970
1971    private void enableSystemUserPackages() {
1972        if (!UserManager.isSplitSystemUser()) {
1973            return;
1974        }
1975        // For system user, enable apps based on the following conditions:
1976        // - app is whitelisted or belong to one of these groups:
1977        //   -- system app which has no launcher icons
1978        //   -- system app which has INTERACT_ACROSS_USERS permission
1979        //   -- system IME app
1980        // - app is not in the blacklist
1981        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1982        Set<String> enableApps = new ArraySet<>();
1983        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1984                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1985                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1986        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1987        enableApps.addAll(wlApps);
1988        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1989                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1990        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1991        enableApps.removeAll(blApps);
1992        Log.i(TAG, "Applications installed for system user: " + enableApps);
1993        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1994                UserHandle.SYSTEM);
1995        final int allAppsSize = allAps.size();
1996        synchronized (mPackages) {
1997            for (int i = 0; i < allAppsSize; i++) {
1998                String pName = allAps.get(i);
1999                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2000                // Should not happen, but we shouldn't be failing if it does
2001                if (pkgSetting == null) {
2002                    continue;
2003                }
2004                boolean install = enableApps.contains(pName);
2005                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2006                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2007                            + " for system user");
2008                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2009                }
2010            }
2011        }
2012    }
2013
2014    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2015        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2016                Context.DISPLAY_SERVICE);
2017        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2018    }
2019
2020    /**
2021     * Requests that files preopted on a secondary system partition be copied to the data partition
2022     * if possible.  Note that the actual copying of the files is accomplished by init for security
2023     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2024     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2025     */
2026    private static void requestCopyPreoptedFiles() {
2027        final int WAIT_TIME_MS = 100;
2028        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2029        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2030            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2031            // We will wait for up to 100 seconds.
2032            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2033            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2034                try {
2035                    Thread.sleep(WAIT_TIME_MS);
2036                } catch (InterruptedException e) {
2037                    // Do nothing
2038                }
2039                if (SystemClock.uptimeMillis() > timeEnd) {
2040                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2041                    Slog.wtf(TAG, "cppreopt did not finish!");
2042                    break;
2043                }
2044            }
2045        }
2046    }
2047
2048    public PackageManagerService(Context context, Installer installer,
2049            boolean factoryTest, boolean onlyCore) {
2050        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2051                SystemClock.uptimeMillis());
2052
2053        if (mSdkVersion <= 0) {
2054            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2055        }
2056
2057        mContext = context;
2058        mFactoryTest = factoryTest;
2059        mOnlyCore = onlyCore;
2060        mMetrics = new DisplayMetrics();
2061        mSettings = new Settings(mPackages);
2062        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2063                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2064        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2065                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2066        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2067                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2068        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2069                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2070        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2071                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2072        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2073                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2074
2075        String separateProcesses = SystemProperties.get("debug.separate_processes");
2076        if (separateProcesses != null && separateProcesses.length() > 0) {
2077            if ("*".equals(separateProcesses)) {
2078                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2079                mSeparateProcesses = null;
2080                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2081            } else {
2082                mDefParseFlags = 0;
2083                mSeparateProcesses = separateProcesses.split(",");
2084                Slog.w(TAG, "Running with debug.separate_processes: "
2085                        + separateProcesses);
2086            }
2087        } else {
2088            mDefParseFlags = 0;
2089            mSeparateProcesses = null;
2090        }
2091
2092        mInstaller = installer;
2093        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2094                "*dexopt*");
2095        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2096
2097        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2098                FgThread.get().getLooper());
2099
2100        getDefaultDisplayMetrics(context, mMetrics);
2101
2102        SystemConfig systemConfig = SystemConfig.getInstance();
2103        mGlobalGids = systemConfig.getGlobalGids();
2104        mSystemPermissions = systemConfig.getSystemPermissions();
2105        mAvailableFeatures = systemConfig.getAvailableFeatures();
2106
2107        mProtectedPackages = new ProtectedPackages(mContext);
2108
2109        synchronized (mInstallLock) {
2110        // writer
2111        synchronized (mPackages) {
2112            mHandlerThread = new ServiceThread(TAG,
2113                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2114            mHandlerThread.start();
2115            mHandler = new PackageHandler(mHandlerThread.getLooper());
2116            mProcessLoggingHandler = new ProcessLoggingHandler();
2117            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2118
2119            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2120
2121            File dataDir = Environment.getDataDirectory();
2122            mAppInstallDir = new File(dataDir, "app");
2123            mAppLib32InstallDir = new File(dataDir, "app-lib");
2124            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2125            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2126            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2127
2128            sUserManager = new UserManagerService(context, this, mPackages);
2129
2130            // Propagate permission configuration in to package manager.
2131            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2132                    = systemConfig.getPermissions();
2133            for (int i=0; i<permConfig.size(); i++) {
2134                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2135                BasePermission bp = mSettings.mPermissions.get(perm.name);
2136                if (bp == null) {
2137                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2138                    mSettings.mPermissions.put(perm.name, bp);
2139                }
2140                if (perm.gids != null) {
2141                    bp.setGids(perm.gids, perm.perUser);
2142                }
2143            }
2144
2145            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2146            for (int i=0; i<libConfig.size(); i++) {
2147                mSharedLibraries.put(libConfig.keyAt(i),
2148                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2149            }
2150
2151            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2152
2153            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2154
2155            if (mFirstBoot) {
2156                requestCopyPreoptedFiles();
2157            }
2158
2159            String customResolverActivity = Resources.getSystem().getString(
2160                    R.string.config_customResolverActivity);
2161            if (TextUtils.isEmpty(customResolverActivity)) {
2162                customResolverActivity = null;
2163            } else {
2164                mCustomResolverComponentName = ComponentName.unflattenFromString(
2165                        customResolverActivity);
2166            }
2167
2168            long startTime = SystemClock.uptimeMillis();
2169
2170            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2171                    startTime);
2172
2173            // Set flag to monitor and not change apk file paths when
2174            // scanning install directories.
2175            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2176
2177            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2178            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2179
2180            if (bootClassPath == null) {
2181                Slog.w(TAG, "No BOOTCLASSPATH found!");
2182            }
2183
2184            if (systemServerClassPath == null) {
2185                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2186            }
2187
2188            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2189            final String[] dexCodeInstructionSets =
2190                    getDexCodeInstructionSets(
2191                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2192
2193            /**
2194             * Ensure all external libraries have had dexopt run on them.
2195             */
2196            if (mSharedLibraries.size() > 0) {
2197                // NOTE: For now, we're compiling these system "shared libraries"
2198                // (and framework jars) into all available architectures. It's possible
2199                // to compile them only when we come across an app that uses them (there's
2200                // already logic for that in scanPackageLI) but that adds some complexity.
2201                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2202                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2203                        final String lib = libEntry.path;
2204                        if (lib == null) {
2205                            continue;
2206                        }
2207
2208                        try {
2209                            // Shared libraries do not have profiles so we perform a full
2210                            // AOT compilation (if needed).
2211                            int dexoptNeeded = DexFile.getDexOptNeeded(
2212                                    lib, dexCodeInstructionSet,
2213                                    getCompilerFilterForReason(REASON_SHARED_APK),
2214                                    false /* newProfile */);
2215                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2216                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2217                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2218                                        getCompilerFilterForReason(REASON_SHARED_APK),
2219                                        StorageManager.UUID_PRIVATE_INTERNAL,
2220                                        SKIP_SHARED_LIBRARY_CHECK);
2221                            }
2222                        } catch (FileNotFoundException e) {
2223                            Slog.w(TAG, "Library not found: " + lib);
2224                        } catch (IOException | InstallerException e) {
2225                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2226                                    + e.getMessage());
2227                        }
2228                    }
2229                }
2230            }
2231
2232            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2233
2234            final VersionInfo ver = mSettings.getInternalVersion();
2235            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2236
2237            // when upgrading from pre-M, promote system app permissions from install to runtime
2238            mPromoteSystemApps =
2239                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2240
2241            // When upgrading from pre-N, we need to handle package extraction like first boot,
2242            // as there is no profiling data available.
2243            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2244
2245            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2246
2247            // save off the names of pre-existing system packages prior to scanning; we don't
2248            // want to automatically grant runtime permissions for new system apps
2249            if (mPromoteSystemApps) {
2250                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2251                while (pkgSettingIter.hasNext()) {
2252                    PackageSetting ps = pkgSettingIter.next();
2253                    if (isSystemApp(ps)) {
2254                        mExistingSystemPackages.add(ps.name);
2255                    }
2256                }
2257            }
2258
2259            // Collect vendor overlay packages.
2260            // (Do this before scanning any apps.)
2261            // For security and version matching reason, only consider
2262            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2263            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2264            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2265                    | PackageParser.PARSE_IS_SYSTEM
2266                    | PackageParser.PARSE_IS_SYSTEM_DIR
2267                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2268
2269            // Find base frameworks (resource packages without code).
2270            scanDirTracedLI(frameworkDir, mDefParseFlags
2271                    | PackageParser.PARSE_IS_SYSTEM
2272                    | PackageParser.PARSE_IS_SYSTEM_DIR
2273                    | PackageParser.PARSE_IS_PRIVILEGED,
2274                    scanFlags | SCAN_NO_DEX, 0);
2275
2276            // Collected privileged system packages.
2277            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2278            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2279                    | PackageParser.PARSE_IS_SYSTEM
2280                    | PackageParser.PARSE_IS_SYSTEM_DIR
2281                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2282
2283            // Collect ordinary system packages.
2284            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2285            scanDirTracedLI(systemAppDir, mDefParseFlags
2286                    | PackageParser.PARSE_IS_SYSTEM
2287                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2288
2289            // Collect all vendor packages.
2290            File vendorAppDir = new File("/vendor/app");
2291            try {
2292                vendorAppDir = vendorAppDir.getCanonicalFile();
2293            } catch (IOException e) {
2294                // failed to look up canonical path, continue with original one
2295            }
2296            scanDirTracedLI(vendorAppDir, mDefParseFlags
2297                    | PackageParser.PARSE_IS_SYSTEM
2298                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2299
2300            // Collect all OEM packages.
2301            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2302            scanDirTracedLI(oemAppDir, mDefParseFlags
2303                    | PackageParser.PARSE_IS_SYSTEM
2304                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2305
2306            // Prune any system packages that no longer exist.
2307            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2308            if (!mOnlyCore) {
2309                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2310                while (psit.hasNext()) {
2311                    PackageSetting ps = psit.next();
2312
2313                    /*
2314                     * If this is not a system app, it can't be a
2315                     * disable system app.
2316                     */
2317                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2318                        continue;
2319                    }
2320
2321                    /*
2322                     * If the package is scanned, it's not erased.
2323                     */
2324                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2325                    if (scannedPkg != null) {
2326                        /*
2327                         * If the system app is both scanned and in the
2328                         * disabled packages list, then it must have been
2329                         * added via OTA. Remove it from the currently
2330                         * scanned package so the previously user-installed
2331                         * application can be scanned.
2332                         */
2333                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2334                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2335                                    + ps.name + "; removing system app.  Last known codePath="
2336                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2337                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2338                                    + scannedPkg.mVersionCode);
2339                            removePackageLI(scannedPkg, true);
2340                            mExpectingBetter.put(ps.name, ps.codePath);
2341                        }
2342
2343                        continue;
2344                    }
2345
2346                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2347                        psit.remove();
2348                        logCriticalInfo(Log.WARN, "System package " + ps.name
2349                                + " no longer exists; it's data will be wiped");
2350                        // Actual deletion of code and data will be handled by later
2351                        // reconciliation step
2352                    } else {
2353                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2354                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2355                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2356                        }
2357                    }
2358                }
2359            }
2360
2361            //look for any incomplete package installations
2362            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2363            for (int i = 0; i < deletePkgsList.size(); i++) {
2364                // Actual deletion of code and data will be handled by later
2365                // reconciliation step
2366                final String packageName = deletePkgsList.get(i).name;
2367                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2368                synchronized (mPackages) {
2369                    mSettings.removePackageLPw(packageName);
2370                }
2371            }
2372
2373            //delete tmp files
2374            deleteTempPackageFiles();
2375
2376            // Remove any shared userIDs that have no associated packages
2377            mSettings.pruneSharedUsersLPw();
2378
2379            if (!mOnlyCore) {
2380                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2381                        SystemClock.uptimeMillis());
2382                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2383
2384                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2385                        | PackageParser.PARSE_FORWARD_LOCK,
2386                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2387
2388                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2389                        | PackageParser.PARSE_IS_EPHEMERAL,
2390                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2391
2392                /**
2393                 * Remove disable package settings for any updated system
2394                 * apps that were removed via an OTA. If they're not a
2395                 * previously-updated app, remove them completely.
2396                 * Otherwise, just revoke their system-level permissions.
2397                 */
2398                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2399                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2400                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2401
2402                    String msg;
2403                    if (deletedPkg == null) {
2404                        msg = "Updated system package " + deletedAppName
2405                                + " no longer exists; it's data will be wiped";
2406                        // Actual deletion of code and data will be handled by later
2407                        // reconciliation step
2408                    } else {
2409                        msg = "Updated system app + " + deletedAppName
2410                                + " no longer present; removing system privileges for "
2411                                + deletedAppName;
2412
2413                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2414
2415                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2416                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2417                    }
2418                    logCriticalInfo(Log.WARN, msg);
2419                }
2420
2421                /**
2422                 * Make sure all system apps that we expected to appear on
2423                 * the userdata partition actually showed up. If they never
2424                 * appeared, crawl back and revive the system version.
2425                 */
2426                for (int i = 0; i < mExpectingBetter.size(); i++) {
2427                    final String packageName = mExpectingBetter.keyAt(i);
2428                    if (!mPackages.containsKey(packageName)) {
2429                        final File scanFile = mExpectingBetter.valueAt(i);
2430
2431                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2432                                + " but never showed up; reverting to system");
2433
2434                        int reparseFlags = mDefParseFlags;
2435                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2436                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2437                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2438                                    | PackageParser.PARSE_IS_PRIVILEGED;
2439                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2440                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2441                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2442                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2443                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2444                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2445                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2446                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2447                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2448                        } else {
2449                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2450                            continue;
2451                        }
2452
2453                        mSettings.enableSystemPackageLPw(packageName);
2454
2455                        try {
2456                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2457                        } catch (PackageManagerException e) {
2458                            Slog.e(TAG, "Failed to parse original system package: "
2459                                    + e.getMessage());
2460                        }
2461                    }
2462                }
2463            }
2464            mExpectingBetter.clear();
2465
2466            // Resolve protected action filters. Only the setup wizard is allowed to
2467            // have a high priority filter for these actions.
2468            mSetupWizardPackage = getSetupWizardPackageName();
2469            if (mProtectedFilters.size() > 0) {
2470                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2471                    Slog.i(TAG, "No setup wizard;"
2472                        + " All protected intents capped to priority 0");
2473                }
2474                for (ActivityIntentInfo filter : mProtectedFilters) {
2475                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2476                        if (DEBUG_FILTERS) {
2477                            Slog.i(TAG, "Found setup wizard;"
2478                                + " allow priority " + filter.getPriority() + ";"
2479                                + " package: " + filter.activity.info.packageName
2480                                + " activity: " + filter.activity.className
2481                                + " priority: " + filter.getPriority());
2482                        }
2483                        // skip setup wizard; allow it to keep the high priority filter
2484                        continue;
2485                    }
2486                    Slog.w(TAG, "Protected action; cap priority to 0;"
2487                            + " package: " + filter.activity.info.packageName
2488                            + " activity: " + filter.activity.className
2489                            + " origPrio: " + filter.getPriority());
2490                    filter.setPriority(0);
2491                }
2492            }
2493            mDeferProtectedFilters = false;
2494            mProtectedFilters.clear();
2495
2496            // Now that we know all of the shared libraries, update all clients to have
2497            // the correct library paths.
2498            updateAllSharedLibrariesLPw();
2499
2500            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2501                // NOTE: We ignore potential failures here during a system scan (like
2502                // the rest of the commands above) because there's precious little we
2503                // can do about it. A settings error is reported, though.
2504                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2505                        false /* boot complete */);
2506            }
2507
2508            // Now that we know all the packages we are keeping,
2509            // read and update their last usage times.
2510            mPackageUsage.read(mPackages);
2511            mCompilerStats.read();
2512
2513            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2514                    SystemClock.uptimeMillis());
2515            Slog.i(TAG, "Time to scan packages: "
2516                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2517                    + " seconds");
2518
2519            // If the platform SDK has changed since the last time we booted,
2520            // we need to re-grant app permission to catch any new ones that
2521            // appear.  This is really a hack, and means that apps can in some
2522            // cases get permissions that the user didn't initially explicitly
2523            // allow...  it would be nice to have some better way to handle
2524            // this situation.
2525            int updateFlags = UPDATE_PERMISSIONS_ALL;
2526            if (ver.sdkVersion != mSdkVersion) {
2527                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2528                        + mSdkVersion + "; regranting permissions for internal storage");
2529                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2530            }
2531            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2532            ver.sdkVersion = mSdkVersion;
2533
2534            // If this is the first boot or an update from pre-M, and it is a normal
2535            // boot, then we need to initialize the default preferred apps across
2536            // all defined users.
2537            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2538                for (UserInfo user : sUserManager.getUsers(true)) {
2539                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2540                    applyFactoryDefaultBrowserLPw(user.id);
2541                    primeDomainVerificationsLPw(user.id);
2542                }
2543            }
2544
2545            // Prepare storage for system user really early during boot,
2546            // since core system apps like SettingsProvider and SystemUI
2547            // can't wait for user to start
2548            final int storageFlags;
2549            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2550                storageFlags = StorageManager.FLAG_STORAGE_DE;
2551            } else {
2552                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2553            }
2554            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2555                    storageFlags);
2556
2557            // If this is first boot after an OTA, and a normal boot, then
2558            // we need to clear code cache directories.
2559            // Note that we do *not* clear the application profiles. These remain valid
2560            // across OTAs and are used to drive profile verification (post OTA) and
2561            // profile compilation (without waiting to collect a fresh set of profiles).
2562            if (mIsUpgrade && !onlyCore) {
2563                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2564                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2565                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2566                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2567                        // No apps are running this early, so no need to freeze
2568                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2569                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2570                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2571                    }
2572                }
2573                ver.fingerprint = Build.FINGERPRINT;
2574            }
2575
2576            checkDefaultBrowser();
2577
2578            // clear only after permissions and other defaults have been updated
2579            mExistingSystemPackages.clear();
2580            mPromoteSystemApps = false;
2581
2582            // All the changes are done during package scanning.
2583            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2584
2585            // can downgrade to reader
2586            mSettings.writeLPr();
2587
2588            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2589            // early on (before the package manager declares itself as early) because other
2590            // components in the system server might ask for package contexts for these apps.
2591            //
2592            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2593            // (i.e, that the data partition is unavailable).
2594            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2595                long start = System.nanoTime();
2596                List<PackageParser.Package> coreApps = new ArrayList<>();
2597                for (PackageParser.Package pkg : mPackages.values()) {
2598                    if (pkg.coreApp) {
2599                        coreApps.add(pkg);
2600                    }
2601                }
2602
2603                int[] stats = performDexOptUpgrade(coreApps, false,
2604                        getCompilerFilterForReason(REASON_CORE_APP));
2605
2606                final int elapsedTimeSeconds =
2607                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2608                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2609
2610                if (DEBUG_DEXOPT) {
2611                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2612                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2613                }
2614
2615
2616                // TODO: Should we log these stats to tron too ?
2617                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2618                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2619                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2620                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2621            }
2622
2623            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2624                    SystemClock.uptimeMillis());
2625
2626            if (!mOnlyCore) {
2627                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2628                mRequiredInstallerPackage = getRequiredInstallerLPr();
2629                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2630                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2631                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2632                        mIntentFilterVerifierComponent);
2633                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2634                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2635                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2636                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2637            } else {
2638                mRequiredVerifierPackage = null;
2639                mRequiredInstallerPackage = null;
2640                mRequiredUninstallerPackage = null;
2641                mIntentFilterVerifierComponent = null;
2642                mIntentFilterVerifier = null;
2643                mServicesSystemSharedLibraryPackageName = null;
2644                mSharedSystemSharedLibraryPackageName = null;
2645            }
2646
2647            mInstallerService = new PackageInstallerService(context, this);
2648
2649            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2650            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2651            // both the installer and resolver must be present to enable ephemeral
2652            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2653                if (DEBUG_EPHEMERAL) {
2654                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2655                            + " installer:" + ephemeralInstallerComponent);
2656                }
2657                mEphemeralResolverComponent = ephemeralResolverComponent;
2658                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2659                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2660                mEphemeralResolverConnection =
2661                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2662            } else {
2663                if (DEBUG_EPHEMERAL) {
2664                    final String missingComponent =
2665                            (ephemeralResolverComponent == null)
2666                            ? (ephemeralInstallerComponent == null)
2667                                    ? "resolver and installer"
2668                                    : "resolver"
2669                            : "installer";
2670                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2671                }
2672                mEphemeralResolverComponent = null;
2673                mEphemeralInstallerComponent = null;
2674                mEphemeralResolverConnection = null;
2675            }
2676
2677            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2678        } // synchronized (mPackages)
2679        } // synchronized (mInstallLock)
2680
2681        // Now after opening every single application zip, make sure they
2682        // are all flushed.  Not really needed, but keeps things nice and
2683        // tidy.
2684        Runtime.getRuntime().gc();
2685
2686        // The initial scanning above does many calls into installd while
2687        // holding the mPackages lock, but we're mostly interested in yelling
2688        // once we have a booted system.
2689        mInstaller.setWarnIfHeld(mPackages);
2690
2691        // Expose private service for system components to use.
2692        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2693    }
2694
2695    @Override
2696    public boolean isFirstBoot() {
2697        return mFirstBoot;
2698    }
2699
2700    @Override
2701    public boolean isOnlyCoreApps() {
2702        return mOnlyCore;
2703    }
2704
2705    @Override
2706    public boolean isUpgrade() {
2707        return mIsUpgrade;
2708    }
2709
2710    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2711        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2712
2713        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2714                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2715                UserHandle.USER_SYSTEM);
2716        if (matches.size() == 1) {
2717            return matches.get(0).getComponentInfo().packageName;
2718        } else {
2719            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2720            return null;
2721        }
2722    }
2723
2724    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2725        synchronized (mPackages) {
2726            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2727            if (libraryEntry == null) {
2728                throw new IllegalStateException("Missing required shared library:" + libraryName);
2729            }
2730            return libraryEntry.apk;
2731        }
2732    }
2733
2734    private @NonNull String getRequiredInstallerLPr() {
2735        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2736        intent.addCategory(Intent.CATEGORY_DEFAULT);
2737        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2738
2739        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2740                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2741                UserHandle.USER_SYSTEM);
2742        if (matches.size() == 1) {
2743            ResolveInfo resolveInfo = matches.get(0);
2744            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2745                throw new RuntimeException("The installer must be a privileged app");
2746            }
2747            return matches.get(0).getComponentInfo().packageName;
2748        } else {
2749            throw new RuntimeException("There must be exactly one installer; found " + matches);
2750        }
2751    }
2752
2753    private @NonNull String getRequiredUninstallerLPr() {
2754        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2755        intent.addCategory(Intent.CATEGORY_DEFAULT);
2756        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2757
2758        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2759                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2760                UserHandle.USER_SYSTEM);
2761        if (resolveInfo == null ||
2762                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2763            throw new RuntimeException("There must be exactly one uninstaller; found "
2764                    + resolveInfo);
2765        }
2766        return resolveInfo.getComponentInfo().packageName;
2767    }
2768
2769    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2770        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2771
2772        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2773                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2774                UserHandle.USER_SYSTEM);
2775        ResolveInfo best = null;
2776        final int N = matches.size();
2777        for (int i = 0; i < N; i++) {
2778            final ResolveInfo cur = matches.get(i);
2779            final String packageName = cur.getComponentInfo().packageName;
2780            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2781                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2782                continue;
2783            }
2784
2785            if (best == null || cur.priority > best.priority) {
2786                best = cur;
2787            }
2788        }
2789
2790        if (best != null) {
2791            return best.getComponentInfo().getComponentName();
2792        } else {
2793            throw new RuntimeException("There must be at least one intent filter verifier");
2794        }
2795    }
2796
2797    private @Nullable ComponentName getEphemeralResolverLPr() {
2798        final String[] packageArray =
2799                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2800        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2801            if (DEBUG_EPHEMERAL) {
2802                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2803            }
2804            return null;
2805        }
2806
2807        final int resolveFlags =
2808                MATCH_DIRECT_BOOT_AWARE
2809                | MATCH_DIRECT_BOOT_UNAWARE
2810                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2811        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2812        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2813                resolveFlags, UserHandle.USER_SYSTEM);
2814
2815        final int N = resolvers.size();
2816        if (N == 0) {
2817            if (DEBUG_EPHEMERAL) {
2818                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2819            }
2820            return null;
2821        }
2822
2823        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2824        for (int i = 0; i < N; i++) {
2825            final ResolveInfo info = resolvers.get(i);
2826
2827            if (info.serviceInfo == null) {
2828                continue;
2829            }
2830
2831            final String packageName = info.serviceInfo.packageName;
2832            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2833                if (DEBUG_EPHEMERAL) {
2834                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2835                            + " pkg: " + packageName + ", info:" + info);
2836                }
2837                continue;
2838            }
2839
2840            if (DEBUG_EPHEMERAL) {
2841                Slog.v(TAG, "Ephemeral resolver found;"
2842                        + " pkg: " + packageName + ", info:" + info);
2843            }
2844            return new ComponentName(packageName, info.serviceInfo.name);
2845        }
2846        if (DEBUG_EPHEMERAL) {
2847            Slog.v(TAG, "Ephemeral resolver NOT found");
2848        }
2849        return null;
2850    }
2851
2852    private @Nullable ComponentName getEphemeralInstallerLPr() {
2853        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2854        intent.addCategory(Intent.CATEGORY_DEFAULT);
2855        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2856
2857        final int resolveFlags =
2858                MATCH_DIRECT_BOOT_AWARE
2859                | MATCH_DIRECT_BOOT_UNAWARE
2860                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2861        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2862                resolveFlags, UserHandle.USER_SYSTEM);
2863        if (matches.size() == 0) {
2864            return null;
2865        } else if (matches.size() == 1) {
2866            return matches.get(0).getComponentInfo().getComponentName();
2867        } else {
2868            throw new RuntimeException(
2869                    "There must be at most one ephemeral installer; found " + matches);
2870        }
2871    }
2872
2873    private void primeDomainVerificationsLPw(int userId) {
2874        if (DEBUG_DOMAIN_VERIFICATION) {
2875            Slog.d(TAG, "Priming domain verifications in user " + userId);
2876        }
2877
2878        SystemConfig systemConfig = SystemConfig.getInstance();
2879        ArraySet<String> packages = systemConfig.getLinkedApps();
2880        ArraySet<String> domains = new ArraySet<String>();
2881
2882        for (String packageName : packages) {
2883            PackageParser.Package pkg = mPackages.get(packageName);
2884            if (pkg != null) {
2885                if (!pkg.isSystemApp()) {
2886                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2887                    continue;
2888                }
2889
2890                domains.clear();
2891                for (PackageParser.Activity a : pkg.activities) {
2892                    for (ActivityIntentInfo filter : a.intents) {
2893                        if (hasValidDomains(filter)) {
2894                            domains.addAll(filter.getHostsList());
2895                        }
2896                    }
2897                }
2898
2899                if (domains.size() > 0) {
2900                    if (DEBUG_DOMAIN_VERIFICATION) {
2901                        Slog.v(TAG, "      + " + packageName);
2902                    }
2903                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2904                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2905                    // and then 'always' in the per-user state actually used for intent resolution.
2906                    final IntentFilterVerificationInfo ivi;
2907                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2908                            new ArrayList<String>(domains));
2909                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2910                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2911                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2912                } else {
2913                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2914                            + "' does not handle web links");
2915                }
2916            } else {
2917                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2918            }
2919        }
2920
2921        scheduleWritePackageRestrictionsLocked(userId);
2922        scheduleWriteSettingsLocked();
2923    }
2924
2925    private void applyFactoryDefaultBrowserLPw(int userId) {
2926        // The default browser app's package name is stored in a string resource,
2927        // with a product-specific overlay used for vendor customization.
2928        String browserPkg = mContext.getResources().getString(
2929                com.android.internal.R.string.default_browser);
2930        if (!TextUtils.isEmpty(browserPkg)) {
2931            // non-empty string => required to be a known package
2932            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2933            if (ps == null) {
2934                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2935                browserPkg = null;
2936            } else {
2937                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2938            }
2939        }
2940
2941        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2942        // default.  If there's more than one, just leave everything alone.
2943        if (browserPkg == null) {
2944            calculateDefaultBrowserLPw(userId);
2945        }
2946    }
2947
2948    private void calculateDefaultBrowserLPw(int userId) {
2949        List<String> allBrowsers = resolveAllBrowserApps(userId);
2950        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2951        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2952    }
2953
2954    private List<String> resolveAllBrowserApps(int userId) {
2955        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2956        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2957                PackageManager.MATCH_ALL, userId);
2958
2959        final int count = list.size();
2960        List<String> result = new ArrayList<String>(count);
2961        for (int i=0; i<count; i++) {
2962            ResolveInfo info = list.get(i);
2963            if (info.activityInfo == null
2964                    || !info.handleAllWebDataURI
2965                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2966                    || result.contains(info.activityInfo.packageName)) {
2967                continue;
2968            }
2969            result.add(info.activityInfo.packageName);
2970        }
2971
2972        return result;
2973    }
2974
2975    private boolean packageIsBrowser(String packageName, int userId) {
2976        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2977                PackageManager.MATCH_ALL, userId);
2978        final int N = list.size();
2979        for (int i = 0; i < N; i++) {
2980            ResolveInfo info = list.get(i);
2981            if (packageName.equals(info.activityInfo.packageName)) {
2982                return true;
2983            }
2984        }
2985        return false;
2986    }
2987
2988    private void checkDefaultBrowser() {
2989        final int myUserId = UserHandle.myUserId();
2990        final String packageName = getDefaultBrowserPackageName(myUserId);
2991        if (packageName != null) {
2992            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2993            if (info == null) {
2994                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2995                synchronized (mPackages) {
2996                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2997                }
2998            }
2999        }
3000    }
3001
3002    @Override
3003    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3004            throws RemoteException {
3005        try {
3006            return super.onTransact(code, data, reply, flags);
3007        } catch (RuntimeException e) {
3008            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3009                Slog.wtf(TAG, "Package Manager Crash", e);
3010            }
3011            throw e;
3012        }
3013    }
3014
3015    static int[] appendInts(int[] cur, int[] add) {
3016        if (add == null) return cur;
3017        if (cur == null) return add;
3018        final int N = add.length;
3019        for (int i=0; i<N; i++) {
3020            cur = appendInt(cur, add[i]);
3021        }
3022        return cur;
3023    }
3024
3025    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3026        if (!sUserManager.exists(userId)) return null;
3027        if (ps == null) {
3028            return null;
3029        }
3030        final PackageParser.Package p = ps.pkg;
3031        if (p == null) {
3032            return null;
3033        }
3034
3035        final PermissionsState permissionsState = ps.getPermissionsState();
3036
3037        // Compute GIDs only if requested
3038        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3039                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3040        // Compute granted permissions only if package has requested permissions
3041        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3042                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3043        final PackageUserState state = ps.readUserState(userId);
3044
3045        return PackageParser.generatePackageInfo(p, gids, flags,
3046                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3047    }
3048
3049    @Override
3050    public void checkPackageStartable(String packageName, int userId) {
3051        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3052
3053        synchronized (mPackages) {
3054            final PackageSetting ps = mSettings.mPackages.get(packageName);
3055            if (ps == null) {
3056                throw new SecurityException("Package " + packageName + " was not found!");
3057            }
3058
3059            if (!ps.getInstalled(userId)) {
3060                throw new SecurityException(
3061                        "Package " + packageName + " was not installed for user " + userId + "!");
3062            }
3063
3064            if (mSafeMode && !ps.isSystem()) {
3065                throw new SecurityException("Package " + packageName + " not a system app!");
3066            }
3067
3068            if (mFrozenPackages.contains(packageName)) {
3069                throw new SecurityException("Package " + packageName + " is currently frozen!");
3070            }
3071
3072            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3073                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3074                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3075            }
3076        }
3077    }
3078
3079    @Override
3080    public boolean isPackageAvailable(String packageName, int userId) {
3081        if (!sUserManager.exists(userId)) return false;
3082        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3083                false /* requireFullPermission */, false /* checkShell */, "is package available");
3084        synchronized (mPackages) {
3085            PackageParser.Package p = mPackages.get(packageName);
3086            if (p != null) {
3087                final PackageSetting ps = (PackageSetting) p.mExtras;
3088                if (ps != null) {
3089                    final PackageUserState state = ps.readUserState(userId);
3090                    if (state != null) {
3091                        return PackageParser.isAvailable(state);
3092                    }
3093                }
3094            }
3095        }
3096        return false;
3097    }
3098
3099    @Override
3100    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3101        if (!sUserManager.exists(userId)) return null;
3102        flags = updateFlagsForPackage(flags, userId, packageName);
3103        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3104                false /* requireFullPermission */, false /* checkShell */, "get package info");
3105        // reader
3106        synchronized (mPackages) {
3107            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3108            PackageParser.Package p = null;
3109            if (matchFactoryOnly) {
3110                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3111                if (ps != null) {
3112                    return generatePackageInfo(ps, flags, userId);
3113                }
3114            }
3115            if (p == null) {
3116                p = mPackages.get(packageName);
3117                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3118                    return null;
3119                }
3120            }
3121            if (DEBUG_PACKAGE_INFO)
3122                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3123            if (p != null) {
3124                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3125            }
3126            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3127                final PackageSetting ps = mSettings.mPackages.get(packageName);
3128                return generatePackageInfo(ps, flags, userId);
3129            }
3130        }
3131        return null;
3132    }
3133
3134    @Override
3135    public String[] currentToCanonicalPackageNames(String[] names) {
3136        String[] out = new String[names.length];
3137        // reader
3138        synchronized (mPackages) {
3139            for (int i=names.length-1; i>=0; i--) {
3140                PackageSetting ps = mSettings.mPackages.get(names[i]);
3141                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3142            }
3143        }
3144        return out;
3145    }
3146
3147    @Override
3148    public String[] canonicalToCurrentPackageNames(String[] names) {
3149        String[] out = new String[names.length];
3150        // reader
3151        synchronized (mPackages) {
3152            for (int i=names.length-1; i>=0; i--) {
3153                String cur = mSettings.mRenamedPackages.get(names[i]);
3154                out[i] = cur != null ? cur : names[i];
3155            }
3156        }
3157        return out;
3158    }
3159
3160    @Override
3161    public int getPackageUid(String packageName, int flags, int userId) {
3162        if (!sUserManager.exists(userId)) return -1;
3163        flags = updateFlagsForPackage(flags, userId, packageName);
3164        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3165                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3166
3167        // reader
3168        synchronized (mPackages) {
3169            final PackageParser.Package p = mPackages.get(packageName);
3170            if (p != null && p.isMatch(flags)) {
3171                return UserHandle.getUid(userId, p.applicationInfo.uid);
3172            }
3173            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3174                final PackageSetting ps = mSettings.mPackages.get(packageName);
3175                if (ps != null && ps.isMatch(flags)) {
3176                    return UserHandle.getUid(userId, ps.appId);
3177                }
3178            }
3179        }
3180
3181        return -1;
3182    }
3183
3184    @Override
3185    public int[] getPackageGids(String packageName, int flags, int userId) {
3186        if (!sUserManager.exists(userId)) return null;
3187        flags = updateFlagsForPackage(flags, userId, packageName);
3188        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3189                false /* requireFullPermission */, false /* checkShell */,
3190                "getPackageGids");
3191
3192        // reader
3193        synchronized (mPackages) {
3194            final PackageParser.Package p = mPackages.get(packageName);
3195            if (p != null && p.isMatch(flags)) {
3196                PackageSetting ps = (PackageSetting) p.mExtras;
3197                return ps.getPermissionsState().computeGids(userId);
3198            }
3199            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3200                final PackageSetting ps = mSettings.mPackages.get(packageName);
3201                if (ps != null && ps.isMatch(flags)) {
3202                    return ps.getPermissionsState().computeGids(userId);
3203                }
3204            }
3205        }
3206
3207        return null;
3208    }
3209
3210    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3211        if (bp.perm != null) {
3212            return PackageParser.generatePermissionInfo(bp.perm, flags);
3213        }
3214        PermissionInfo pi = new PermissionInfo();
3215        pi.name = bp.name;
3216        pi.packageName = bp.sourcePackage;
3217        pi.nonLocalizedLabel = bp.name;
3218        pi.protectionLevel = bp.protectionLevel;
3219        return pi;
3220    }
3221
3222    @Override
3223    public PermissionInfo getPermissionInfo(String name, int flags) {
3224        // reader
3225        synchronized (mPackages) {
3226            final BasePermission p = mSettings.mPermissions.get(name);
3227            if (p != null) {
3228                return generatePermissionInfo(p, flags);
3229            }
3230            return null;
3231        }
3232    }
3233
3234    @Override
3235    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3236            int flags) {
3237        // reader
3238        synchronized (mPackages) {
3239            if (group != null && !mPermissionGroups.containsKey(group)) {
3240                // This is thrown as NameNotFoundException
3241                return null;
3242            }
3243
3244            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3245            for (BasePermission p : mSettings.mPermissions.values()) {
3246                if (group == null) {
3247                    if (p.perm == null || p.perm.info.group == null) {
3248                        out.add(generatePermissionInfo(p, flags));
3249                    }
3250                } else {
3251                    if (p.perm != null && group.equals(p.perm.info.group)) {
3252                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3253                    }
3254                }
3255            }
3256            return new ParceledListSlice<>(out);
3257        }
3258    }
3259
3260    @Override
3261    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3262        // reader
3263        synchronized (mPackages) {
3264            return PackageParser.generatePermissionGroupInfo(
3265                    mPermissionGroups.get(name), flags);
3266        }
3267    }
3268
3269    @Override
3270    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3271        // reader
3272        synchronized (mPackages) {
3273            final int N = mPermissionGroups.size();
3274            ArrayList<PermissionGroupInfo> out
3275                    = new ArrayList<PermissionGroupInfo>(N);
3276            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3277                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3278            }
3279            return new ParceledListSlice<>(out);
3280        }
3281    }
3282
3283    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3284            int userId) {
3285        if (!sUserManager.exists(userId)) return null;
3286        PackageSetting ps = mSettings.mPackages.get(packageName);
3287        if (ps != null) {
3288            if (ps.pkg == null) {
3289                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3290                if (pInfo != null) {
3291                    return pInfo.applicationInfo;
3292                }
3293                return null;
3294            }
3295            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3296                    ps.readUserState(userId), userId);
3297        }
3298        return null;
3299    }
3300
3301    @Override
3302    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3303        if (!sUserManager.exists(userId)) return null;
3304        flags = updateFlagsForApplication(flags, userId, packageName);
3305        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3306                false /* requireFullPermission */, false /* checkShell */, "get application info");
3307        // writer
3308        synchronized (mPackages) {
3309            PackageParser.Package p = mPackages.get(packageName);
3310            if (DEBUG_PACKAGE_INFO) Log.v(
3311                    TAG, "getApplicationInfo " + packageName
3312                    + ": " + p);
3313            if (p != null) {
3314                PackageSetting ps = mSettings.mPackages.get(packageName);
3315                if (ps == null) return null;
3316                // Note: isEnabledLP() does not apply here - always return info
3317                return PackageParser.generateApplicationInfo(
3318                        p, flags, ps.readUserState(userId), userId);
3319            }
3320            if ("android".equals(packageName)||"system".equals(packageName)) {
3321                return mAndroidApplication;
3322            }
3323            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3324                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3325            }
3326        }
3327        return null;
3328    }
3329
3330    @Override
3331    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3332            final IPackageDataObserver observer) {
3333        mContext.enforceCallingOrSelfPermission(
3334                android.Manifest.permission.CLEAR_APP_CACHE, null);
3335        // Queue up an async operation since clearing cache may take a little while.
3336        mHandler.post(new Runnable() {
3337            public void run() {
3338                mHandler.removeCallbacks(this);
3339                boolean success = true;
3340                synchronized (mInstallLock) {
3341                    try {
3342                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3343                    } catch (InstallerException e) {
3344                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3345                        success = false;
3346                    }
3347                }
3348                if (observer != null) {
3349                    try {
3350                        observer.onRemoveCompleted(null, success);
3351                    } catch (RemoteException e) {
3352                        Slog.w(TAG, "RemoveException when invoking call back");
3353                    }
3354                }
3355            }
3356        });
3357    }
3358
3359    @Override
3360    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3361            final IntentSender pi) {
3362        mContext.enforceCallingOrSelfPermission(
3363                android.Manifest.permission.CLEAR_APP_CACHE, null);
3364        // Queue up an async operation since clearing cache may take a little while.
3365        mHandler.post(new Runnable() {
3366            public void run() {
3367                mHandler.removeCallbacks(this);
3368                boolean success = true;
3369                synchronized (mInstallLock) {
3370                    try {
3371                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3372                    } catch (InstallerException e) {
3373                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3374                        success = false;
3375                    }
3376                }
3377                if(pi != null) {
3378                    try {
3379                        // Callback via pending intent
3380                        int code = success ? 1 : 0;
3381                        pi.sendIntent(null, code, null,
3382                                null, null);
3383                    } catch (SendIntentException e1) {
3384                        Slog.i(TAG, "Failed to send pending intent");
3385                    }
3386                }
3387            }
3388        });
3389    }
3390
3391    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3392        synchronized (mInstallLock) {
3393            try {
3394                mInstaller.freeCache(volumeUuid, freeStorageSize);
3395            } catch (InstallerException e) {
3396                throw new IOException("Failed to free enough space", e);
3397            }
3398        }
3399    }
3400
3401    /**
3402     * Update given flags based on encryption status of current user.
3403     */
3404    private int updateFlags(int flags, int userId) {
3405        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3406                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3407            // Caller expressed an explicit opinion about what encryption
3408            // aware/unaware components they want to see, so fall through and
3409            // give them what they want
3410        } else {
3411            // Caller expressed no opinion, so match based on user state
3412            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3413                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3414            } else {
3415                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3416            }
3417        }
3418        return flags;
3419    }
3420
3421    private UserManagerInternal getUserManagerInternal() {
3422        if (mUserManagerInternal == null) {
3423            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3424        }
3425        return mUserManagerInternal;
3426    }
3427
3428    /**
3429     * Update given flags when being used to request {@link PackageInfo}.
3430     */
3431    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3432        boolean triaged = true;
3433        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3434                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3435            // Caller is asking for component details, so they'd better be
3436            // asking for specific encryption matching behavior, or be triaged
3437            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3438                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3439                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3440                triaged = false;
3441            }
3442        }
3443        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3444                | PackageManager.MATCH_SYSTEM_ONLY
3445                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3446            triaged = false;
3447        }
3448        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3449            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3450                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3451        }
3452        return updateFlags(flags, userId);
3453    }
3454
3455    /**
3456     * Update given flags when being used to request {@link ApplicationInfo}.
3457     */
3458    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3459        return updateFlagsForPackage(flags, userId, cookie);
3460    }
3461
3462    /**
3463     * Update given flags when being used to request {@link ComponentInfo}.
3464     */
3465    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3466        if (cookie instanceof Intent) {
3467            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3468                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3469            }
3470        }
3471
3472        boolean triaged = true;
3473        // Caller is asking for component details, so they'd better be
3474        // asking for specific encryption matching behavior, or be triaged
3475        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3476                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3477                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3478            triaged = false;
3479        }
3480        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3481            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3482                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3483        }
3484
3485        return updateFlags(flags, userId);
3486    }
3487
3488    /**
3489     * Update given flags when being used to request {@link ResolveInfo}.
3490     */
3491    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3492        // Safe mode means we shouldn't match any third-party components
3493        if (mSafeMode) {
3494            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3495        }
3496
3497        return updateFlagsForComponent(flags, userId, cookie);
3498    }
3499
3500    @Override
3501    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3502        if (!sUserManager.exists(userId)) return null;
3503        flags = updateFlagsForComponent(flags, userId, component);
3504        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3505                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3506        synchronized (mPackages) {
3507            PackageParser.Activity a = mActivities.mActivities.get(component);
3508
3509            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3510            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3511                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3512                if (ps == null) return null;
3513                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3514                        userId);
3515            }
3516            if (mResolveComponentName.equals(component)) {
3517                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3518                        new PackageUserState(), userId);
3519            }
3520        }
3521        return null;
3522    }
3523
3524    @Override
3525    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3526            String resolvedType) {
3527        synchronized (mPackages) {
3528            if (component.equals(mResolveComponentName)) {
3529                // The resolver supports EVERYTHING!
3530                return true;
3531            }
3532            PackageParser.Activity a = mActivities.mActivities.get(component);
3533            if (a == null) {
3534                return false;
3535            }
3536            for (int i=0; i<a.intents.size(); i++) {
3537                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3538                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3539                    return true;
3540                }
3541            }
3542            return false;
3543        }
3544    }
3545
3546    @Override
3547    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3548        if (!sUserManager.exists(userId)) return null;
3549        flags = updateFlagsForComponent(flags, userId, component);
3550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3551                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3552        synchronized (mPackages) {
3553            PackageParser.Activity a = mReceivers.mActivities.get(component);
3554            if (DEBUG_PACKAGE_INFO) Log.v(
3555                TAG, "getReceiverInfo " + component + ": " + a);
3556            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3557                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3558                if (ps == null) return null;
3559                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3560                        userId);
3561            }
3562        }
3563        return null;
3564    }
3565
3566    @Override
3567    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3568        if (!sUserManager.exists(userId)) return null;
3569        flags = updateFlagsForComponent(flags, userId, component);
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3571                false /* requireFullPermission */, false /* checkShell */, "get service info");
3572        synchronized (mPackages) {
3573            PackageParser.Service s = mServices.mServices.get(component);
3574            if (DEBUG_PACKAGE_INFO) Log.v(
3575                TAG, "getServiceInfo " + component + ": " + s);
3576            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3577                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3578                if (ps == null) return null;
3579                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3580                        userId);
3581            }
3582        }
3583        return null;
3584    }
3585
3586    @Override
3587    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3588        if (!sUserManager.exists(userId)) return null;
3589        flags = updateFlagsForComponent(flags, userId, component);
3590        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3591                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3592        synchronized (mPackages) {
3593            PackageParser.Provider p = mProviders.mProviders.get(component);
3594            if (DEBUG_PACKAGE_INFO) Log.v(
3595                TAG, "getProviderInfo " + component + ": " + p);
3596            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3597                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3598                if (ps == null) return null;
3599                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3600                        userId);
3601            }
3602        }
3603        return null;
3604    }
3605
3606    @Override
3607    public String[] getSystemSharedLibraryNames() {
3608        Set<String> libSet;
3609        synchronized (mPackages) {
3610            libSet = mSharedLibraries.keySet();
3611            int size = libSet.size();
3612            if (size > 0) {
3613                String[] libs = new String[size];
3614                libSet.toArray(libs);
3615                return libs;
3616            }
3617        }
3618        return null;
3619    }
3620
3621    @Override
3622    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3623        synchronized (mPackages) {
3624            return mServicesSystemSharedLibraryPackageName;
3625        }
3626    }
3627
3628    @Override
3629    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3630        synchronized (mPackages) {
3631            return mSharedSystemSharedLibraryPackageName;
3632        }
3633    }
3634
3635    @Override
3636    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3637        synchronized (mPackages) {
3638            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3639
3640            final FeatureInfo fi = new FeatureInfo();
3641            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3642                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3643            res.add(fi);
3644
3645            return new ParceledListSlice<>(res);
3646        }
3647    }
3648
3649    @Override
3650    public boolean hasSystemFeature(String name, int version) {
3651        synchronized (mPackages) {
3652            final FeatureInfo feat = mAvailableFeatures.get(name);
3653            if (feat == null) {
3654                return false;
3655            } else {
3656                return feat.version >= version;
3657            }
3658        }
3659    }
3660
3661    @Override
3662    public int checkPermission(String permName, String pkgName, int userId) {
3663        if (!sUserManager.exists(userId)) {
3664            return PackageManager.PERMISSION_DENIED;
3665        }
3666
3667        synchronized (mPackages) {
3668            final PackageParser.Package p = mPackages.get(pkgName);
3669            if (p != null && p.mExtras != null) {
3670                final PackageSetting ps = (PackageSetting) p.mExtras;
3671                final PermissionsState permissionsState = ps.getPermissionsState();
3672                if (permissionsState.hasPermission(permName, userId)) {
3673                    return PackageManager.PERMISSION_GRANTED;
3674                }
3675                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3676                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3677                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3678                    return PackageManager.PERMISSION_GRANTED;
3679                }
3680            }
3681        }
3682
3683        return PackageManager.PERMISSION_DENIED;
3684    }
3685
3686    @Override
3687    public int checkUidPermission(String permName, int uid) {
3688        final int userId = UserHandle.getUserId(uid);
3689
3690        if (!sUserManager.exists(userId)) {
3691            return PackageManager.PERMISSION_DENIED;
3692        }
3693
3694        synchronized (mPackages) {
3695            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3696            if (obj != null) {
3697                final SettingBase ps = (SettingBase) obj;
3698                final PermissionsState permissionsState = ps.getPermissionsState();
3699                if (permissionsState.hasPermission(permName, userId)) {
3700                    return PackageManager.PERMISSION_GRANTED;
3701                }
3702                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3703                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3704                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3705                    return PackageManager.PERMISSION_GRANTED;
3706                }
3707            } else {
3708                ArraySet<String> perms = mSystemPermissions.get(uid);
3709                if (perms != null) {
3710                    if (perms.contains(permName)) {
3711                        return PackageManager.PERMISSION_GRANTED;
3712                    }
3713                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3714                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3715                        return PackageManager.PERMISSION_GRANTED;
3716                    }
3717                }
3718            }
3719        }
3720
3721        return PackageManager.PERMISSION_DENIED;
3722    }
3723
3724    @Override
3725    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3726        if (UserHandle.getCallingUserId() != userId) {
3727            mContext.enforceCallingPermission(
3728                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3729                    "isPermissionRevokedByPolicy for user " + userId);
3730        }
3731
3732        if (checkPermission(permission, packageName, userId)
3733                == PackageManager.PERMISSION_GRANTED) {
3734            return false;
3735        }
3736
3737        final long identity = Binder.clearCallingIdentity();
3738        try {
3739            final int flags = getPermissionFlags(permission, packageName, userId);
3740            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3741        } finally {
3742            Binder.restoreCallingIdentity(identity);
3743        }
3744    }
3745
3746    @Override
3747    public String getPermissionControllerPackageName() {
3748        synchronized (mPackages) {
3749            return mRequiredInstallerPackage;
3750        }
3751    }
3752
3753    /**
3754     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3755     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3756     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3757     * @param message the message to log on security exception
3758     */
3759    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3760            boolean checkShell, String message) {
3761        if (userId < 0) {
3762            throw new IllegalArgumentException("Invalid userId " + userId);
3763        }
3764        if (checkShell) {
3765            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3766        }
3767        if (userId == UserHandle.getUserId(callingUid)) return;
3768        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3769            if (requireFullPermission) {
3770                mContext.enforceCallingOrSelfPermission(
3771                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3772            } else {
3773                try {
3774                    mContext.enforceCallingOrSelfPermission(
3775                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3776                } catch (SecurityException se) {
3777                    mContext.enforceCallingOrSelfPermission(
3778                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3779                }
3780            }
3781        }
3782    }
3783
3784    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3785        if (callingUid == Process.SHELL_UID) {
3786            if (userHandle >= 0
3787                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3788                throw new SecurityException("Shell does not have permission to access user "
3789                        + userHandle);
3790            } else if (userHandle < 0) {
3791                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3792                        + Debug.getCallers(3));
3793            }
3794        }
3795    }
3796
3797    private BasePermission findPermissionTreeLP(String permName) {
3798        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3799            if (permName.startsWith(bp.name) &&
3800                    permName.length() > bp.name.length() &&
3801                    permName.charAt(bp.name.length()) == '.') {
3802                return bp;
3803            }
3804        }
3805        return null;
3806    }
3807
3808    private BasePermission checkPermissionTreeLP(String permName) {
3809        if (permName != null) {
3810            BasePermission bp = findPermissionTreeLP(permName);
3811            if (bp != null) {
3812                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3813                    return bp;
3814                }
3815                throw new SecurityException("Calling uid "
3816                        + Binder.getCallingUid()
3817                        + " is not allowed to add to permission tree "
3818                        + bp.name + " owned by uid " + bp.uid);
3819            }
3820        }
3821        throw new SecurityException("No permission tree found for " + permName);
3822    }
3823
3824    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3825        if (s1 == null) {
3826            return s2 == null;
3827        }
3828        if (s2 == null) {
3829            return false;
3830        }
3831        if (s1.getClass() != s2.getClass()) {
3832            return false;
3833        }
3834        return s1.equals(s2);
3835    }
3836
3837    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3838        if (pi1.icon != pi2.icon) return false;
3839        if (pi1.logo != pi2.logo) return false;
3840        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3841        if (!compareStrings(pi1.name, pi2.name)) return false;
3842        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3843        // We'll take care of setting this one.
3844        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3845        // These are not currently stored in settings.
3846        //if (!compareStrings(pi1.group, pi2.group)) return false;
3847        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3848        //if (pi1.labelRes != pi2.labelRes) return false;
3849        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3850        return true;
3851    }
3852
3853    int permissionInfoFootprint(PermissionInfo info) {
3854        int size = info.name.length();
3855        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3856        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3857        return size;
3858    }
3859
3860    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3861        int size = 0;
3862        for (BasePermission perm : mSettings.mPermissions.values()) {
3863            if (perm.uid == tree.uid) {
3864                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3865            }
3866        }
3867        return size;
3868    }
3869
3870    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3871        // We calculate the max size of permissions defined by this uid and throw
3872        // if that plus the size of 'info' would exceed our stated maximum.
3873        if (tree.uid != Process.SYSTEM_UID) {
3874            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3875            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3876                throw new SecurityException("Permission tree size cap exceeded");
3877            }
3878        }
3879    }
3880
3881    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3882        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3883            throw new SecurityException("Label must be specified in permission");
3884        }
3885        BasePermission tree = checkPermissionTreeLP(info.name);
3886        BasePermission bp = mSettings.mPermissions.get(info.name);
3887        boolean added = bp == null;
3888        boolean changed = true;
3889        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3890        if (added) {
3891            enforcePermissionCapLocked(info, tree);
3892            bp = new BasePermission(info.name, tree.sourcePackage,
3893                    BasePermission.TYPE_DYNAMIC);
3894        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3895            throw new SecurityException(
3896                    "Not allowed to modify non-dynamic permission "
3897                    + info.name);
3898        } else {
3899            if (bp.protectionLevel == fixedLevel
3900                    && bp.perm.owner.equals(tree.perm.owner)
3901                    && bp.uid == tree.uid
3902                    && comparePermissionInfos(bp.perm.info, info)) {
3903                changed = false;
3904            }
3905        }
3906        bp.protectionLevel = fixedLevel;
3907        info = new PermissionInfo(info);
3908        info.protectionLevel = fixedLevel;
3909        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3910        bp.perm.info.packageName = tree.perm.info.packageName;
3911        bp.uid = tree.uid;
3912        if (added) {
3913            mSettings.mPermissions.put(info.name, bp);
3914        }
3915        if (changed) {
3916            if (!async) {
3917                mSettings.writeLPr();
3918            } else {
3919                scheduleWriteSettingsLocked();
3920            }
3921        }
3922        return added;
3923    }
3924
3925    @Override
3926    public boolean addPermission(PermissionInfo info) {
3927        synchronized (mPackages) {
3928            return addPermissionLocked(info, false);
3929        }
3930    }
3931
3932    @Override
3933    public boolean addPermissionAsync(PermissionInfo info) {
3934        synchronized (mPackages) {
3935            return addPermissionLocked(info, true);
3936        }
3937    }
3938
3939    @Override
3940    public void removePermission(String name) {
3941        synchronized (mPackages) {
3942            checkPermissionTreeLP(name);
3943            BasePermission bp = mSettings.mPermissions.get(name);
3944            if (bp != null) {
3945                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3946                    throw new SecurityException(
3947                            "Not allowed to modify non-dynamic permission "
3948                            + name);
3949                }
3950                mSettings.mPermissions.remove(name);
3951                mSettings.writeLPr();
3952            }
3953        }
3954    }
3955
3956    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3957            BasePermission bp) {
3958        int index = pkg.requestedPermissions.indexOf(bp.name);
3959        if (index == -1) {
3960            throw new SecurityException("Package " + pkg.packageName
3961                    + " has not requested permission " + bp.name);
3962        }
3963        if (!bp.isRuntime() && !bp.isDevelopment()) {
3964            throw new SecurityException("Permission " + bp.name
3965                    + " is not a changeable permission type");
3966        }
3967    }
3968
3969    @Override
3970    public void grantRuntimePermission(String packageName, String name, final int userId) {
3971        if (!sUserManager.exists(userId)) {
3972            Log.e(TAG, "No such user:" + userId);
3973            return;
3974        }
3975
3976        mContext.enforceCallingOrSelfPermission(
3977                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3978                "grantRuntimePermission");
3979
3980        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3981                true /* requireFullPermission */, true /* checkShell */,
3982                "grantRuntimePermission");
3983
3984        final int uid;
3985        final SettingBase sb;
3986
3987        synchronized (mPackages) {
3988            final PackageParser.Package pkg = mPackages.get(packageName);
3989            if (pkg == null) {
3990                throw new IllegalArgumentException("Unknown package: " + packageName);
3991            }
3992
3993            final BasePermission bp = mSettings.mPermissions.get(name);
3994            if (bp == null) {
3995                throw new IllegalArgumentException("Unknown permission: " + name);
3996            }
3997
3998            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3999
4000            // If a permission review is required for legacy apps we represent
4001            // their permissions as always granted runtime ones since we need
4002            // to keep the review required permission flag per user while an
4003            // install permission's state is shared across all users.
4004            if (Build.PERMISSIONS_REVIEW_REQUIRED
4005                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4006                    && bp.isRuntime()) {
4007                return;
4008            }
4009
4010            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4011            sb = (SettingBase) pkg.mExtras;
4012            if (sb == null) {
4013                throw new IllegalArgumentException("Unknown package: " + packageName);
4014            }
4015
4016            final PermissionsState permissionsState = sb.getPermissionsState();
4017
4018            final int flags = permissionsState.getPermissionFlags(name, userId);
4019            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4020                throw new SecurityException("Cannot grant system fixed permission "
4021                        + name + " for package " + packageName);
4022            }
4023
4024            if (bp.isDevelopment()) {
4025                // Development permissions must be handled specially, since they are not
4026                // normal runtime permissions.  For now they apply to all users.
4027                if (permissionsState.grantInstallPermission(bp) !=
4028                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4029                    scheduleWriteSettingsLocked();
4030                }
4031                return;
4032            }
4033
4034            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4035                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4036                return;
4037            }
4038
4039            final int result = permissionsState.grantRuntimePermission(bp, userId);
4040            switch (result) {
4041                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4042                    return;
4043                }
4044
4045                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4046                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4047                    mHandler.post(new Runnable() {
4048                        @Override
4049                        public void run() {
4050                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4051                        }
4052                    });
4053                }
4054                break;
4055            }
4056
4057            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4058
4059            // Not critical if that is lost - app has to request again.
4060            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4061        }
4062
4063        // Only need to do this if user is initialized. Otherwise it's a new user
4064        // and there are no processes running as the user yet and there's no need
4065        // to make an expensive call to remount processes for the changed permissions.
4066        if (READ_EXTERNAL_STORAGE.equals(name)
4067                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4068            final long token = Binder.clearCallingIdentity();
4069            try {
4070                if (sUserManager.isInitialized(userId)) {
4071                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4072                            MountServiceInternal.class);
4073                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4074                }
4075            } finally {
4076                Binder.restoreCallingIdentity(token);
4077            }
4078        }
4079    }
4080
4081    @Override
4082    public void revokeRuntimePermission(String packageName, String name, int userId) {
4083        if (!sUserManager.exists(userId)) {
4084            Log.e(TAG, "No such user:" + userId);
4085            return;
4086        }
4087
4088        mContext.enforceCallingOrSelfPermission(
4089                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4090                "revokeRuntimePermission");
4091
4092        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4093                true /* requireFullPermission */, true /* checkShell */,
4094                "revokeRuntimePermission");
4095
4096        final int appId;
4097
4098        synchronized (mPackages) {
4099            final PackageParser.Package pkg = mPackages.get(packageName);
4100            if (pkg == null) {
4101                throw new IllegalArgumentException("Unknown package: " + packageName);
4102            }
4103
4104            final BasePermission bp = mSettings.mPermissions.get(name);
4105            if (bp == null) {
4106                throw new IllegalArgumentException("Unknown permission: " + name);
4107            }
4108
4109            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4110
4111            // If a permission review is required for legacy apps we represent
4112            // their permissions as always granted runtime ones since we need
4113            // to keep the review required permission flag per user while an
4114            // install permission's state is shared across all users.
4115            if (Build.PERMISSIONS_REVIEW_REQUIRED
4116                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4117                    && bp.isRuntime()) {
4118                return;
4119            }
4120
4121            SettingBase sb = (SettingBase) pkg.mExtras;
4122            if (sb == null) {
4123                throw new IllegalArgumentException("Unknown package: " + packageName);
4124            }
4125
4126            final PermissionsState permissionsState = sb.getPermissionsState();
4127
4128            final int flags = permissionsState.getPermissionFlags(name, userId);
4129            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4130                throw new SecurityException("Cannot revoke system fixed permission "
4131                        + name + " for package " + packageName);
4132            }
4133
4134            if (bp.isDevelopment()) {
4135                // Development permissions must be handled specially, since they are not
4136                // normal runtime permissions.  For now they apply to all users.
4137                if (permissionsState.revokeInstallPermission(bp) !=
4138                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4139                    scheduleWriteSettingsLocked();
4140                }
4141                return;
4142            }
4143
4144            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4145                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4146                return;
4147            }
4148
4149            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4150
4151            // Critical, after this call app should never have the permission.
4152            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4153
4154            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4155        }
4156
4157        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4158    }
4159
4160    @Override
4161    public void resetRuntimePermissions() {
4162        mContext.enforceCallingOrSelfPermission(
4163                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4164                "revokeRuntimePermission");
4165
4166        int callingUid = Binder.getCallingUid();
4167        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4168            mContext.enforceCallingOrSelfPermission(
4169                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4170                    "resetRuntimePermissions");
4171        }
4172
4173        synchronized (mPackages) {
4174            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4175            for (int userId : UserManagerService.getInstance().getUserIds()) {
4176                final int packageCount = mPackages.size();
4177                for (int i = 0; i < packageCount; i++) {
4178                    PackageParser.Package pkg = mPackages.valueAt(i);
4179                    if (!(pkg.mExtras instanceof PackageSetting)) {
4180                        continue;
4181                    }
4182                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4183                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4184                }
4185            }
4186        }
4187    }
4188
4189    @Override
4190    public int getPermissionFlags(String name, String packageName, int userId) {
4191        if (!sUserManager.exists(userId)) {
4192            return 0;
4193        }
4194
4195        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4196
4197        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4198                true /* requireFullPermission */, false /* checkShell */,
4199                "getPermissionFlags");
4200
4201        synchronized (mPackages) {
4202            final PackageParser.Package pkg = mPackages.get(packageName);
4203            if (pkg == null) {
4204                return 0;
4205            }
4206
4207            final BasePermission bp = mSettings.mPermissions.get(name);
4208            if (bp == null) {
4209                return 0;
4210            }
4211
4212            SettingBase sb = (SettingBase) pkg.mExtras;
4213            if (sb == null) {
4214                return 0;
4215            }
4216
4217            PermissionsState permissionsState = sb.getPermissionsState();
4218            return permissionsState.getPermissionFlags(name, userId);
4219        }
4220    }
4221
4222    @Override
4223    public void updatePermissionFlags(String name, String packageName, int flagMask,
4224            int flagValues, int userId) {
4225        if (!sUserManager.exists(userId)) {
4226            return;
4227        }
4228
4229        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4230
4231        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4232                true /* requireFullPermission */, true /* checkShell */,
4233                "updatePermissionFlags");
4234
4235        // Only the system can change these flags and nothing else.
4236        if (getCallingUid() != Process.SYSTEM_UID) {
4237            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4238            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4239            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4240            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4241            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4242        }
4243
4244        synchronized (mPackages) {
4245            final PackageParser.Package pkg = mPackages.get(packageName);
4246            if (pkg == null) {
4247                throw new IllegalArgumentException("Unknown package: " + packageName);
4248            }
4249
4250            final BasePermission bp = mSettings.mPermissions.get(name);
4251            if (bp == null) {
4252                throw new IllegalArgumentException("Unknown permission: " + name);
4253            }
4254
4255            SettingBase sb = (SettingBase) pkg.mExtras;
4256            if (sb == null) {
4257                throw new IllegalArgumentException("Unknown package: " + packageName);
4258            }
4259
4260            PermissionsState permissionsState = sb.getPermissionsState();
4261
4262            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4263
4264            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4265                // Install and runtime permissions are stored in different places,
4266                // so figure out what permission changed and persist the change.
4267                if (permissionsState.getInstallPermissionState(name) != null) {
4268                    scheduleWriteSettingsLocked();
4269                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4270                        || hadState) {
4271                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4272                }
4273            }
4274        }
4275    }
4276
4277    /**
4278     * Update the permission flags for all packages and runtime permissions of a user in order
4279     * to allow device or profile owner to remove POLICY_FIXED.
4280     */
4281    @Override
4282    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4283        if (!sUserManager.exists(userId)) {
4284            return;
4285        }
4286
4287        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4288
4289        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4290                true /* requireFullPermission */, true /* checkShell */,
4291                "updatePermissionFlagsForAllApps");
4292
4293        // Only the system can change system fixed flags.
4294        if (getCallingUid() != Process.SYSTEM_UID) {
4295            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4296            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4297        }
4298
4299        synchronized (mPackages) {
4300            boolean changed = false;
4301            final int packageCount = mPackages.size();
4302            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4303                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4304                SettingBase sb = (SettingBase) pkg.mExtras;
4305                if (sb == null) {
4306                    continue;
4307                }
4308                PermissionsState permissionsState = sb.getPermissionsState();
4309                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4310                        userId, flagMask, flagValues);
4311            }
4312            if (changed) {
4313                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4314            }
4315        }
4316    }
4317
4318    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4319        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4320                != PackageManager.PERMISSION_GRANTED
4321            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4322                != PackageManager.PERMISSION_GRANTED) {
4323            throw new SecurityException(message + " requires "
4324                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4325                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4326        }
4327    }
4328
4329    @Override
4330    public boolean shouldShowRequestPermissionRationale(String permissionName,
4331            String packageName, int userId) {
4332        if (UserHandle.getCallingUserId() != userId) {
4333            mContext.enforceCallingPermission(
4334                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4335                    "canShowRequestPermissionRationale for user " + userId);
4336        }
4337
4338        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4339        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4340            return false;
4341        }
4342
4343        if (checkPermission(permissionName, packageName, userId)
4344                == PackageManager.PERMISSION_GRANTED) {
4345            return false;
4346        }
4347
4348        final int flags;
4349
4350        final long identity = Binder.clearCallingIdentity();
4351        try {
4352            flags = getPermissionFlags(permissionName,
4353                    packageName, userId);
4354        } finally {
4355            Binder.restoreCallingIdentity(identity);
4356        }
4357
4358        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4359                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4360                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4361
4362        if ((flags & fixedFlags) != 0) {
4363            return false;
4364        }
4365
4366        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4367    }
4368
4369    @Override
4370    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4371        mContext.enforceCallingOrSelfPermission(
4372                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4373                "addOnPermissionsChangeListener");
4374
4375        synchronized (mPackages) {
4376            mOnPermissionChangeListeners.addListenerLocked(listener);
4377        }
4378    }
4379
4380    @Override
4381    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4382        synchronized (mPackages) {
4383            mOnPermissionChangeListeners.removeListenerLocked(listener);
4384        }
4385    }
4386
4387    @Override
4388    public boolean isProtectedBroadcast(String actionName) {
4389        synchronized (mPackages) {
4390            if (mProtectedBroadcasts.contains(actionName)) {
4391                return true;
4392            } else if (actionName != null) {
4393                // TODO: remove these terrible hacks
4394                if (actionName.startsWith("android.net.netmon.lingerExpired")
4395                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4396                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4397                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4398                    return true;
4399                }
4400            }
4401        }
4402        return false;
4403    }
4404
4405    @Override
4406    public int checkSignatures(String pkg1, String pkg2) {
4407        synchronized (mPackages) {
4408            final PackageParser.Package p1 = mPackages.get(pkg1);
4409            final PackageParser.Package p2 = mPackages.get(pkg2);
4410            if (p1 == null || p1.mExtras == null
4411                    || p2 == null || p2.mExtras == null) {
4412                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4413            }
4414            return compareSignatures(p1.mSignatures, p2.mSignatures);
4415        }
4416    }
4417
4418    @Override
4419    public int checkUidSignatures(int uid1, int uid2) {
4420        // Map to base uids.
4421        uid1 = UserHandle.getAppId(uid1);
4422        uid2 = UserHandle.getAppId(uid2);
4423        // reader
4424        synchronized (mPackages) {
4425            Signature[] s1;
4426            Signature[] s2;
4427            Object obj = mSettings.getUserIdLPr(uid1);
4428            if (obj != null) {
4429                if (obj instanceof SharedUserSetting) {
4430                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4431                } else if (obj instanceof PackageSetting) {
4432                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4433                } else {
4434                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4435                }
4436            } else {
4437                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4438            }
4439            obj = mSettings.getUserIdLPr(uid2);
4440            if (obj != null) {
4441                if (obj instanceof SharedUserSetting) {
4442                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4443                } else if (obj instanceof PackageSetting) {
4444                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4445                } else {
4446                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4447                }
4448            } else {
4449                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4450            }
4451            return compareSignatures(s1, s2);
4452        }
4453    }
4454
4455    /**
4456     * This method should typically only be used when granting or revoking
4457     * permissions, since the app may immediately restart after this call.
4458     * <p>
4459     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4460     * guard your work against the app being relaunched.
4461     */
4462    private void killUid(int appId, int userId, String reason) {
4463        final long identity = Binder.clearCallingIdentity();
4464        try {
4465            IActivityManager am = ActivityManagerNative.getDefault();
4466            if (am != null) {
4467                try {
4468                    am.killUid(appId, userId, reason);
4469                } catch (RemoteException e) {
4470                    /* ignore - same process */
4471                }
4472            }
4473        } finally {
4474            Binder.restoreCallingIdentity(identity);
4475        }
4476    }
4477
4478    /**
4479     * Compares two sets of signatures. Returns:
4480     * <br />
4481     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4482     * <br />
4483     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4484     * <br />
4485     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4486     * <br />
4487     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4488     * <br />
4489     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4490     */
4491    static int compareSignatures(Signature[] s1, Signature[] s2) {
4492        if (s1 == null) {
4493            return s2 == null
4494                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4495                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4496        }
4497
4498        if (s2 == null) {
4499            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4500        }
4501
4502        if (s1.length != s2.length) {
4503            return PackageManager.SIGNATURE_NO_MATCH;
4504        }
4505
4506        // Since both signature sets are of size 1, we can compare without HashSets.
4507        if (s1.length == 1) {
4508            return s1[0].equals(s2[0]) ?
4509                    PackageManager.SIGNATURE_MATCH :
4510                    PackageManager.SIGNATURE_NO_MATCH;
4511        }
4512
4513        ArraySet<Signature> set1 = new ArraySet<Signature>();
4514        for (Signature sig : s1) {
4515            set1.add(sig);
4516        }
4517        ArraySet<Signature> set2 = new ArraySet<Signature>();
4518        for (Signature sig : s2) {
4519            set2.add(sig);
4520        }
4521        // Make sure s2 contains all signatures in s1.
4522        if (set1.equals(set2)) {
4523            return PackageManager.SIGNATURE_MATCH;
4524        }
4525        return PackageManager.SIGNATURE_NO_MATCH;
4526    }
4527
4528    /**
4529     * If the database version for this type of package (internal storage or
4530     * external storage) is less than the version where package signatures
4531     * were updated, return true.
4532     */
4533    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4534        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4535        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4536    }
4537
4538    /**
4539     * Used for backward compatibility to make sure any packages with
4540     * certificate chains get upgraded to the new style. {@code existingSigs}
4541     * will be in the old format (since they were stored on disk from before the
4542     * system upgrade) and {@code scannedSigs} will be in the newer format.
4543     */
4544    private int compareSignaturesCompat(PackageSignatures existingSigs,
4545            PackageParser.Package scannedPkg) {
4546        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4547            return PackageManager.SIGNATURE_NO_MATCH;
4548        }
4549
4550        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4551        for (Signature sig : existingSigs.mSignatures) {
4552            existingSet.add(sig);
4553        }
4554        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4555        for (Signature sig : scannedPkg.mSignatures) {
4556            try {
4557                Signature[] chainSignatures = sig.getChainSignatures();
4558                for (Signature chainSig : chainSignatures) {
4559                    scannedCompatSet.add(chainSig);
4560                }
4561            } catch (CertificateEncodingException e) {
4562                scannedCompatSet.add(sig);
4563            }
4564        }
4565        /*
4566         * Make sure the expanded scanned set contains all signatures in the
4567         * existing one.
4568         */
4569        if (scannedCompatSet.equals(existingSet)) {
4570            // Migrate the old signatures to the new scheme.
4571            existingSigs.assignSignatures(scannedPkg.mSignatures);
4572            // The new KeySets will be re-added later in the scanning process.
4573            synchronized (mPackages) {
4574                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4575            }
4576            return PackageManager.SIGNATURE_MATCH;
4577        }
4578        return PackageManager.SIGNATURE_NO_MATCH;
4579    }
4580
4581    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4582        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4583        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4584    }
4585
4586    private int compareSignaturesRecover(PackageSignatures existingSigs,
4587            PackageParser.Package scannedPkg) {
4588        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4589            return PackageManager.SIGNATURE_NO_MATCH;
4590        }
4591
4592        String msg = null;
4593        try {
4594            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4595                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4596                        + scannedPkg.packageName);
4597                return PackageManager.SIGNATURE_MATCH;
4598            }
4599        } catch (CertificateException e) {
4600            msg = e.getMessage();
4601        }
4602
4603        logCriticalInfo(Log.INFO,
4604                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4605        return PackageManager.SIGNATURE_NO_MATCH;
4606    }
4607
4608    @Override
4609    public List<String> getAllPackages() {
4610        synchronized (mPackages) {
4611            return new ArrayList<String>(mPackages.keySet());
4612        }
4613    }
4614
4615    @Override
4616    public String[] getPackagesForUid(int uid) {
4617        uid = UserHandle.getAppId(uid);
4618        // reader
4619        synchronized (mPackages) {
4620            Object obj = mSettings.getUserIdLPr(uid);
4621            if (obj instanceof SharedUserSetting) {
4622                final SharedUserSetting sus = (SharedUserSetting) obj;
4623                final int N = sus.packages.size();
4624                final String[] res = new String[N];
4625                for (int i = 0; i < N; i++) {
4626                    res[i] = sus.packages.valueAt(i).name;
4627                }
4628                return res;
4629            } else if (obj instanceof PackageSetting) {
4630                final PackageSetting ps = (PackageSetting) obj;
4631                return new String[] { ps.name };
4632            }
4633        }
4634        return null;
4635    }
4636
4637    @Override
4638    public String getNameForUid(int uid) {
4639        // reader
4640        synchronized (mPackages) {
4641            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4642            if (obj instanceof SharedUserSetting) {
4643                final SharedUserSetting sus = (SharedUserSetting) obj;
4644                return sus.name + ":" + sus.userId;
4645            } else if (obj instanceof PackageSetting) {
4646                final PackageSetting ps = (PackageSetting) obj;
4647                return ps.name;
4648            }
4649        }
4650        return null;
4651    }
4652
4653    @Override
4654    public int getUidForSharedUser(String sharedUserName) {
4655        if(sharedUserName == null) {
4656            return -1;
4657        }
4658        // reader
4659        synchronized (mPackages) {
4660            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4661            if (suid == null) {
4662                return -1;
4663            }
4664            return suid.userId;
4665        }
4666    }
4667
4668    @Override
4669    public int getFlagsForUid(int uid) {
4670        synchronized (mPackages) {
4671            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4672            if (obj instanceof SharedUserSetting) {
4673                final SharedUserSetting sus = (SharedUserSetting) obj;
4674                return sus.pkgFlags;
4675            } else if (obj instanceof PackageSetting) {
4676                final PackageSetting ps = (PackageSetting) obj;
4677                return ps.pkgFlags;
4678            }
4679        }
4680        return 0;
4681    }
4682
4683    @Override
4684    public int getPrivateFlagsForUid(int uid) {
4685        synchronized (mPackages) {
4686            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4687            if (obj instanceof SharedUserSetting) {
4688                final SharedUserSetting sus = (SharedUserSetting) obj;
4689                return sus.pkgPrivateFlags;
4690            } else if (obj instanceof PackageSetting) {
4691                final PackageSetting ps = (PackageSetting) obj;
4692                return ps.pkgPrivateFlags;
4693            }
4694        }
4695        return 0;
4696    }
4697
4698    @Override
4699    public boolean isUidPrivileged(int uid) {
4700        uid = UserHandle.getAppId(uid);
4701        // reader
4702        synchronized (mPackages) {
4703            Object obj = mSettings.getUserIdLPr(uid);
4704            if (obj instanceof SharedUserSetting) {
4705                final SharedUserSetting sus = (SharedUserSetting) obj;
4706                final Iterator<PackageSetting> it = sus.packages.iterator();
4707                while (it.hasNext()) {
4708                    if (it.next().isPrivileged()) {
4709                        return true;
4710                    }
4711                }
4712            } else if (obj instanceof PackageSetting) {
4713                final PackageSetting ps = (PackageSetting) obj;
4714                return ps.isPrivileged();
4715            }
4716        }
4717        return false;
4718    }
4719
4720    @Override
4721    public String[] getAppOpPermissionPackages(String permissionName) {
4722        synchronized (mPackages) {
4723            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4724            if (pkgs == null) {
4725                return null;
4726            }
4727            return pkgs.toArray(new String[pkgs.size()]);
4728        }
4729    }
4730
4731    @Override
4732    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4733            int flags, int userId) {
4734        try {
4735            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4736
4737            if (!sUserManager.exists(userId)) return null;
4738            flags = updateFlagsForResolve(flags, userId, intent);
4739            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4740                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4741
4742            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4743            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4744                    flags, userId);
4745            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4746
4747            final ResolveInfo bestChoice =
4748                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4749
4750            if (isEphemeralAllowed(intent, query, userId)) {
4751                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4752                final EphemeralResolveInfo ai =
4753                        getEphemeralResolveInfo(intent, resolvedType, userId);
4754                if (ai != null) {
4755                    if (DEBUG_EPHEMERAL) {
4756                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4757                    }
4758                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4759                    bestChoice.ephemeralResolveInfo = ai;
4760                }
4761                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4762            }
4763            return bestChoice;
4764        } finally {
4765            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4766        }
4767    }
4768
4769    @Override
4770    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4771            IntentFilter filter, int match, ComponentName activity) {
4772        final int userId = UserHandle.getCallingUserId();
4773        if (DEBUG_PREFERRED) {
4774            Log.v(TAG, "setLastChosenActivity intent=" + intent
4775                + " resolvedType=" + resolvedType
4776                + " flags=" + flags
4777                + " filter=" + filter
4778                + " match=" + match
4779                + " activity=" + activity);
4780            filter.dump(new PrintStreamPrinter(System.out), "    ");
4781        }
4782        intent.setComponent(null);
4783        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4784                userId);
4785        // Find any earlier preferred or last chosen entries and nuke them
4786        findPreferredActivity(intent, resolvedType,
4787                flags, query, 0, false, true, false, userId);
4788        // Add the new activity as the last chosen for this filter
4789        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4790                "Setting last chosen");
4791    }
4792
4793    @Override
4794    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4795        final int userId = UserHandle.getCallingUserId();
4796        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4797        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4798                userId);
4799        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4800                false, false, false, userId);
4801    }
4802
4803
4804    private boolean isEphemeralAllowed(
4805            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4806        // Short circuit and return early if possible.
4807        if (DISABLE_EPHEMERAL_APPS) {
4808            return false;
4809        }
4810        final int callingUser = UserHandle.getCallingUserId();
4811        if (callingUser != UserHandle.USER_SYSTEM) {
4812            return false;
4813        }
4814        if (mEphemeralResolverConnection == null) {
4815            return false;
4816        }
4817        if (intent.getComponent() != null) {
4818            return false;
4819        }
4820        if (intent.getPackage() != null) {
4821            return false;
4822        }
4823        final boolean isWebUri = hasWebURI(intent);
4824        if (!isWebUri) {
4825            return false;
4826        }
4827        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4828        synchronized (mPackages) {
4829            final int count = resolvedActivites.size();
4830            for (int n = 0; n < count; n++) {
4831                ResolveInfo info = resolvedActivites.get(n);
4832                String packageName = info.activityInfo.packageName;
4833                PackageSetting ps = mSettings.mPackages.get(packageName);
4834                if (ps != null) {
4835                    // Try to get the status from User settings first
4836                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4837                    int status = (int) (packedStatus >> 32);
4838                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4839                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4840                        if (DEBUG_EPHEMERAL) {
4841                            Slog.v(TAG, "DENY ephemeral apps;"
4842                                + " pkg: " + packageName + ", status: " + status);
4843                        }
4844                        return false;
4845                    }
4846                }
4847            }
4848        }
4849        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4850        return true;
4851    }
4852
4853    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4854            int userId) {
4855        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
4856                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4857        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
4858                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4859        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4860                ephemeralPrefixCount);
4861        final int[] shaPrefix = digest.getDigestPrefix();
4862        final byte[][] digestBytes = digest.getDigestBytes();
4863        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4864                mEphemeralResolverConnection.getEphemeralResolveInfoList(
4865                        shaPrefix, ephemeralPrefixMask);
4866        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4867            // No hash prefix match; there are no ephemeral apps for this domain.
4868            return null;
4869        }
4870
4871        // Go in reverse order so we match the narrowest scope first.
4872        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4873            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4874                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4875                    continue;
4876                }
4877                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4878                // No filters; this should never happen.
4879                if (filters.isEmpty()) {
4880                    continue;
4881                }
4882                // We have a domain match; resolve the filters to see if anything matches.
4883                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4884                for (int j = filters.size() - 1; j >= 0; --j) {
4885                    final EphemeralResolveIntentInfo intentInfo =
4886                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4887                    ephemeralResolver.addFilter(intentInfo);
4888                }
4889                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4890                        intent, resolvedType, false /*defaultOnly*/, userId);
4891                if (!matchedResolveInfoList.isEmpty()) {
4892                    return matchedResolveInfoList.get(0);
4893                }
4894            }
4895        }
4896        // Hash or filter mis-match; no ephemeral apps for this domain.
4897        return null;
4898    }
4899
4900    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4901            int flags, List<ResolveInfo> query, int userId) {
4902        if (query != null) {
4903            final int N = query.size();
4904            if (N == 1) {
4905                return query.get(0);
4906            } else if (N > 1) {
4907                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4908                // If there is more than one activity with the same priority,
4909                // then let the user decide between them.
4910                ResolveInfo r0 = query.get(0);
4911                ResolveInfo r1 = query.get(1);
4912                if (DEBUG_INTENT_MATCHING || debug) {
4913                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4914                            + r1.activityInfo.name + "=" + r1.priority);
4915                }
4916                // If the first activity has a higher priority, or a different
4917                // default, then it is always desirable to pick it.
4918                if (r0.priority != r1.priority
4919                        || r0.preferredOrder != r1.preferredOrder
4920                        || r0.isDefault != r1.isDefault) {
4921                    return query.get(0);
4922                }
4923                // If we have saved a preference for a preferred activity for
4924                // this Intent, use that.
4925                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4926                        flags, query, r0.priority, true, false, debug, userId);
4927                if (ri != null) {
4928                    return ri;
4929                }
4930                ri = new ResolveInfo(mResolveInfo);
4931                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4932                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4933                // If all of the options come from the same package, show the application's
4934                // label and icon instead of the generic resolver's.
4935                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4936                // and then throw away the ResolveInfo itself, meaning that the caller loses
4937                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4938                // a fallback for this case; we only set the target package's resources on
4939                // the ResolveInfo, not the ActivityInfo.
4940                final String intentPackage = intent.getPackage();
4941                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4942                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4943                    ri.resolvePackageName = intentPackage;
4944                    if (userNeedsBadging(userId)) {
4945                        ri.noResourceId = true;
4946                    } else {
4947                        ri.icon = appi.icon;
4948                    }
4949                    ri.iconResourceId = appi.icon;
4950                    ri.labelRes = appi.labelRes;
4951                }
4952                ri.activityInfo.applicationInfo = new ApplicationInfo(
4953                        ri.activityInfo.applicationInfo);
4954                if (userId != 0) {
4955                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4956                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4957                }
4958                // Make sure that the resolver is displayable in car mode
4959                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4960                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4961                return ri;
4962            }
4963        }
4964        return null;
4965    }
4966
4967    /**
4968     * Return true if the given list is not empty and all of its contents have
4969     * an activityInfo with the given package name.
4970     */
4971    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4972        if (ArrayUtils.isEmpty(list)) {
4973            return false;
4974        }
4975        for (int i = 0, N = list.size(); i < N; i++) {
4976            final ResolveInfo ri = list.get(i);
4977            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4978            if (ai == null || !packageName.equals(ai.packageName)) {
4979                return false;
4980            }
4981        }
4982        return true;
4983    }
4984
4985    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4986            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4987        final int N = query.size();
4988        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4989                .get(userId);
4990        // Get the list of persistent preferred activities that handle the intent
4991        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4992        List<PersistentPreferredActivity> pprefs = ppir != null
4993                ? ppir.queryIntent(intent, resolvedType,
4994                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4995                : null;
4996        if (pprefs != null && pprefs.size() > 0) {
4997            final int M = pprefs.size();
4998            for (int i=0; i<M; i++) {
4999                final PersistentPreferredActivity ppa = pprefs.get(i);
5000                if (DEBUG_PREFERRED || debug) {
5001                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5002                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5003                            + "\n  component=" + ppa.mComponent);
5004                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5005                }
5006                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5007                        flags | MATCH_DISABLED_COMPONENTS, userId);
5008                if (DEBUG_PREFERRED || debug) {
5009                    Slog.v(TAG, "Found persistent preferred activity:");
5010                    if (ai != null) {
5011                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5012                    } else {
5013                        Slog.v(TAG, "  null");
5014                    }
5015                }
5016                if (ai == null) {
5017                    // This previously registered persistent preferred activity
5018                    // component is no longer known. Ignore it and do NOT remove it.
5019                    continue;
5020                }
5021                for (int j=0; j<N; j++) {
5022                    final ResolveInfo ri = query.get(j);
5023                    if (!ri.activityInfo.applicationInfo.packageName
5024                            .equals(ai.applicationInfo.packageName)) {
5025                        continue;
5026                    }
5027                    if (!ri.activityInfo.name.equals(ai.name)) {
5028                        continue;
5029                    }
5030                    //  Found a persistent preference that can handle the intent.
5031                    if (DEBUG_PREFERRED || debug) {
5032                        Slog.v(TAG, "Returning persistent preferred activity: " +
5033                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5034                    }
5035                    return ri;
5036                }
5037            }
5038        }
5039        return null;
5040    }
5041
5042    // TODO: handle preferred activities missing while user has amnesia
5043    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5044            List<ResolveInfo> query, int priority, boolean always,
5045            boolean removeMatches, boolean debug, int userId) {
5046        if (!sUserManager.exists(userId)) return null;
5047        flags = updateFlagsForResolve(flags, userId, intent);
5048        // writer
5049        synchronized (mPackages) {
5050            if (intent.getSelector() != null) {
5051                intent = intent.getSelector();
5052            }
5053            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5054
5055            // Try to find a matching persistent preferred activity.
5056            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5057                    debug, userId);
5058
5059            // If a persistent preferred activity matched, use it.
5060            if (pri != null) {
5061                return pri;
5062            }
5063
5064            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5065            // Get the list of preferred activities that handle the intent
5066            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5067            List<PreferredActivity> prefs = pir != null
5068                    ? pir.queryIntent(intent, resolvedType,
5069                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5070                    : null;
5071            if (prefs != null && prefs.size() > 0) {
5072                boolean changed = false;
5073                try {
5074                    // First figure out how good the original match set is.
5075                    // We will only allow preferred activities that came
5076                    // from the same match quality.
5077                    int match = 0;
5078
5079                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5080
5081                    final int N = query.size();
5082                    for (int j=0; j<N; j++) {
5083                        final ResolveInfo ri = query.get(j);
5084                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5085                                + ": 0x" + Integer.toHexString(match));
5086                        if (ri.match > match) {
5087                            match = ri.match;
5088                        }
5089                    }
5090
5091                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5092                            + Integer.toHexString(match));
5093
5094                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5095                    final int M = prefs.size();
5096                    for (int i=0; i<M; i++) {
5097                        final PreferredActivity pa = prefs.get(i);
5098                        if (DEBUG_PREFERRED || debug) {
5099                            Slog.v(TAG, "Checking PreferredActivity ds="
5100                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5101                                    + "\n  component=" + pa.mPref.mComponent);
5102                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5103                        }
5104                        if (pa.mPref.mMatch != match) {
5105                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5106                                    + Integer.toHexString(pa.mPref.mMatch));
5107                            continue;
5108                        }
5109                        // If it's not an "always" type preferred activity and that's what we're
5110                        // looking for, skip it.
5111                        if (always && !pa.mPref.mAlways) {
5112                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5113                            continue;
5114                        }
5115                        final ActivityInfo ai = getActivityInfo(
5116                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5117                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5118                                userId);
5119                        if (DEBUG_PREFERRED || debug) {
5120                            Slog.v(TAG, "Found preferred activity:");
5121                            if (ai != null) {
5122                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5123                            } else {
5124                                Slog.v(TAG, "  null");
5125                            }
5126                        }
5127                        if (ai == null) {
5128                            // This previously registered preferred activity
5129                            // component is no longer known.  Most likely an update
5130                            // to the app was installed and in the new version this
5131                            // component no longer exists.  Clean it up by removing
5132                            // it from the preferred activities list, and skip it.
5133                            Slog.w(TAG, "Removing dangling preferred activity: "
5134                                    + pa.mPref.mComponent);
5135                            pir.removeFilter(pa);
5136                            changed = true;
5137                            continue;
5138                        }
5139                        for (int j=0; j<N; j++) {
5140                            final ResolveInfo ri = query.get(j);
5141                            if (!ri.activityInfo.applicationInfo.packageName
5142                                    .equals(ai.applicationInfo.packageName)) {
5143                                continue;
5144                            }
5145                            if (!ri.activityInfo.name.equals(ai.name)) {
5146                                continue;
5147                            }
5148
5149                            if (removeMatches) {
5150                                pir.removeFilter(pa);
5151                                changed = true;
5152                                if (DEBUG_PREFERRED) {
5153                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5154                                }
5155                                break;
5156                            }
5157
5158                            // Okay we found a previously set preferred or last chosen app.
5159                            // If the result set is different from when this
5160                            // was created, we need to clear it and re-ask the
5161                            // user their preference, if we're looking for an "always" type entry.
5162                            if (always && !pa.mPref.sameSet(query)) {
5163                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5164                                        + intent + " type " + resolvedType);
5165                                if (DEBUG_PREFERRED) {
5166                                    Slog.v(TAG, "Removing preferred activity since set changed "
5167                                            + pa.mPref.mComponent);
5168                                }
5169                                pir.removeFilter(pa);
5170                                // Re-add the filter as a "last chosen" entry (!always)
5171                                PreferredActivity lastChosen = new PreferredActivity(
5172                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5173                                pir.addFilter(lastChosen);
5174                                changed = true;
5175                                return null;
5176                            }
5177
5178                            // Yay! Either the set matched or we're looking for the last chosen
5179                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5180                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5181                            return ri;
5182                        }
5183                    }
5184                } finally {
5185                    if (changed) {
5186                        if (DEBUG_PREFERRED) {
5187                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5188                        }
5189                        scheduleWritePackageRestrictionsLocked(userId);
5190                    }
5191                }
5192            }
5193        }
5194        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5195        return null;
5196    }
5197
5198    /*
5199     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5200     */
5201    @Override
5202    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5203            int targetUserId) {
5204        mContext.enforceCallingOrSelfPermission(
5205                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5206        List<CrossProfileIntentFilter> matches =
5207                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5208        if (matches != null) {
5209            int size = matches.size();
5210            for (int i = 0; i < size; i++) {
5211                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5212            }
5213        }
5214        if (hasWebURI(intent)) {
5215            // cross-profile app linking works only towards the parent.
5216            final UserInfo parent = getProfileParent(sourceUserId);
5217            synchronized(mPackages) {
5218                int flags = updateFlagsForResolve(0, parent.id, intent);
5219                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5220                        intent, resolvedType, flags, sourceUserId, parent.id);
5221                return xpDomainInfo != null;
5222            }
5223        }
5224        return false;
5225    }
5226
5227    private UserInfo getProfileParent(int userId) {
5228        final long identity = Binder.clearCallingIdentity();
5229        try {
5230            return sUserManager.getProfileParent(userId);
5231        } finally {
5232            Binder.restoreCallingIdentity(identity);
5233        }
5234    }
5235
5236    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5237            String resolvedType, int userId) {
5238        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5239        if (resolver != null) {
5240            return resolver.queryIntent(intent, resolvedType, false, userId);
5241        }
5242        return null;
5243    }
5244
5245    @Override
5246    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5247            String resolvedType, int flags, int userId) {
5248        try {
5249            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5250
5251            return new ParceledListSlice<>(
5252                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5253        } finally {
5254            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5255        }
5256    }
5257
5258    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5259            String resolvedType, int flags, int userId) {
5260        if (!sUserManager.exists(userId)) return Collections.emptyList();
5261        flags = updateFlagsForResolve(flags, userId, intent);
5262        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5263                false /* requireFullPermission */, false /* checkShell */,
5264                "query intent activities");
5265        ComponentName comp = intent.getComponent();
5266        if (comp == null) {
5267            if (intent.getSelector() != null) {
5268                intent = intent.getSelector();
5269                comp = intent.getComponent();
5270            }
5271        }
5272
5273        if (comp != null) {
5274            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5275            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5276            if (ai != null) {
5277                final ResolveInfo ri = new ResolveInfo();
5278                ri.activityInfo = ai;
5279                list.add(ri);
5280            }
5281            return list;
5282        }
5283
5284        // reader
5285        synchronized (mPackages) {
5286            final String pkgName = intent.getPackage();
5287            if (pkgName == null) {
5288                List<CrossProfileIntentFilter> matchingFilters =
5289                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5290                // Check for results that need to skip the current profile.
5291                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5292                        resolvedType, flags, userId);
5293                if (xpResolveInfo != null) {
5294                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5295                    result.add(xpResolveInfo);
5296                    return filterIfNotSystemUser(result, userId);
5297                }
5298
5299                // Check for results in the current profile.
5300                List<ResolveInfo> result = mActivities.queryIntent(
5301                        intent, resolvedType, flags, userId);
5302                result = filterIfNotSystemUser(result, userId);
5303
5304                // Check for cross profile results.
5305                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5306                xpResolveInfo = queryCrossProfileIntents(
5307                        matchingFilters, intent, resolvedType, flags, userId,
5308                        hasNonNegativePriorityResult);
5309                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5310                    boolean isVisibleToUser = filterIfNotSystemUser(
5311                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5312                    if (isVisibleToUser) {
5313                        result.add(xpResolveInfo);
5314                        Collections.sort(result, mResolvePrioritySorter);
5315                    }
5316                }
5317                if (hasWebURI(intent)) {
5318                    CrossProfileDomainInfo xpDomainInfo = null;
5319                    final UserInfo parent = getProfileParent(userId);
5320                    if (parent != null) {
5321                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5322                                flags, userId, parent.id);
5323                    }
5324                    if (xpDomainInfo != null) {
5325                        if (xpResolveInfo != null) {
5326                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5327                            // in the result.
5328                            result.remove(xpResolveInfo);
5329                        }
5330                        if (result.size() == 0) {
5331                            result.add(xpDomainInfo.resolveInfo);
5332                            return result;
5333                        }
5334                    } else if (result.size() <= 1) {
5335                        return result;
5336                    }
5337                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5338                            xpDomainInfo, userId);
5339                    Collections.sort(result, mResolvePrioritySorter);
5340                }
5341                return result;
5342            }
5343            final PackageParser.Package pkg = mPackages.get(pkgName);
5344            if (pkg != null) {
5345                return filterIfNotSystemUser(
5346                        mActivities.queryIntentForPackage(
5347                                intent, resolvedType, flags, pkg.activities, userId),
5348                        userId);
5349            }
5350            return new ArrayList<ResolveInfo>();
5351        }
5352    }
5353
5354    private static class CrossProfileDomainInfo {
5355        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5356        ResolveInfo resolveInfo;
5357        /* Best domain verification status of the activities found in the other profile */
5358        int bestDomainVerificationStatus;
5359    }
5360
5361    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5362            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5363        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5364                sourceUserId)) {
5365            return null;
5366        }
5367        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5368                resolvedType, flags, parentUserId);
5369
5370        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5371            return null;
5372        }
5373        CrossProfileDomainInfo result = null;
5374        int size = resultTargetUser.size();
5375        for (int i = 0; i < size; i++) {
5376            ResolveInfo riTargetUser = resultTargetUser.get(i);
5377            // Intent filter verification is only for filters that specify a host. So don't return
5378            // those that handle all web uris.
5379            if (riTargetUser.handleAllWebDataURI) {
5380                continue;
5381            }
5382            String packageName = riTargetUser.activityInfo.packageName;
5383            PackageSetting ps = mSettings.mPackages.get(packageName);
5384            if (ps == null) {
5385                continue;
5386            }
5387            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5388            int status = (int)(verificationState >> 32);
5389            if (result == null) {
5390                result = new CrossProfileDomainInfo();
5391                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5392                        sourceUserId, parentUserId);
5393                result.bestDomainVerificationStatus = status;
5394            } else {
5395                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5396                        result.bestDomainVerificationStatus);
5397            }
5398        }
5399        // Don't consider matches with status NEVER across profiles.
5400        if (result != null && result.bestDomainVerificationStatus
5401                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5402            return null;
5403        }
5404        return result;
5405    }
5406
5407    /**
5408     * Verification statuses are ordered from the worse to the best, except for
5409     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5410     */
5411    private int bestDomainVerificationStatus(int status1, int status2) {
5412        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5413            return status2;
5414        }
5415        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5416            return status1;
5417        }
5418        return (int) MathUtils.max(status1, status2);
5419    }
5420
5421    private boolean isUserEnabled(int userId) {
5422        long callingId = Binder.clearCallingIdentity();
5423        try {
5424            UserInfo userInfo = sUserManager.getUserInfo(userId);
5425            return userInfo != null && userInfo.isEnabled();
5426        } finally {
5427            Binder.restoreCallingIdentity(callingId);
5428        }
5429    }
5430
5431    /**
5432     * Filter out activities with systemUserOnly flag set, when current user is not System.
5433     *
5434     * @return filtered list
5435     */
5436    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5437        if (userId == UserHandle.USER_SYSTEM) {
5438            return resolveInfos;
5439        }
5440        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5441            ResolveInfo info = resolveInfos.get(i);
5442            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5443                resolveInfos.remove(i);
5444            }
5445        }
5446        return resolveInfos;
5447    }
5448
5449    /**
5450     * @param resolveInfos list of resolve infos in descending priority order
5451     * @return if the list contains a resolve info with non-negative priority
5452     */
5453    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5454        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5455    }
5456
5457    private static boolean hasWebURI(Intent intent) {
5458        if (intent.getData() == null) {
5459            return false;
5460        }
5461        final String scheme = intent.getScheme();
5462        if (TextUtils.isEmpty(scheme)) {
5463            return false;
5464        }
5465        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5466    }
5467
5468    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5469            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5470            int userId) {
5471        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5472
5473        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5474            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5475                    candidates.size());
5476        }
5477
5478        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5479        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5480        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5481        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5482        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5483        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5484
5485        synchronized (mPackages) {
5486            final int count = candidates.size();
5487            // First, try to use linked apps. Partition the candidates into four lists:
5488            // one for the final results, one for the "do not use ever", one for "undefined status"
5489            // and finally one for "browser app type".
5490            for (int n=0; n<count; n++) {
5491                ResolveInfo info = candidates.get(n);
5492                String packageName = info.activityInfo.packageName;
5493                PackageSetting ps = mSettings.mPackages.get(packageName);
5494                if (ps != null) {
5495                    // Add to the special match all list (Browser use case)
5496                    if (info.handleAllWebDataURI) {
5497                        matchAllList.add(info);
5498                        continue;
5499                    }
5500                    // Try to get the status from User settings first
5501                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5502                    int status = (int)(packedStatus >> 32);
5503                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5504                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5505                        if (DEBUG_DOMAIN_VERIFICATION) {
5506                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5507                                    + " : linkgen=" + linkGeneration);
5508                        }
5509                        // Use link-enabled generation as preferredOrder, i.e.
5510                        // prefer newly-enabled over earlier-enabled.
5511                        info.preferredOrder = linkGeneration;
5512                        alwaysList.add(info);
5513                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5514                        if (DEBUG_DOMAIN_VERIFICATION) {
5515                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5516                        }
5517                        neverList.add(info);
5518                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5519                        if (DEBUG_DOMAIN_VERIFICATION) {
5520                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5521                        }
5522                        alwaysAskList.add(info);
5523                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5524                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5525                        if (DEBUG_DOMAIN_VERIFICATION) {
5526                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5527                        }
5528                        undefinedList.add(info);
5529                    }
5530                }
5531            }
5532
5533            // We'll want to include browser possibilities in a few cases
5534            boolean includeBrowser = false;
5535
5536            // First try to add the "always" resolution(s) for the current user, if any
5537            if (alwaysList.size() > 0) {
5538                result.addAll(alwaysList);
5539            } else {
5540                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5541                result.addAll(undefinedList);
5542                // Maybe add one for the other profile.
5543                if (xpDomainInfo != null && (
5544                        xpDomainInfo.bestDomainVerificationStatus
5545                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5546                    result.add(xpDomainInfo.resolveInfo);
5547                }
5548                includeBrowser = true;
5549            }
5550
5551            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5552            // If there were 'always' entries their preferred order has been set, so we also
5553            // back that off to make the alternatives equivalent
5554            if (alwaysAskList.size() > 0) {
5555                for (ResolveInfo i : result) {
5556                    i.preferredOrder = 0;
5557                }
5558                result.addAll(alwaysAskList);
5559                includeBrowser = true;
5560            }
5561
5562            if (includeBrowser) {
5563                // Also add browsers (all of them or only the default one)
5564                if (DEBUG_DOMAIN_VERIFICATION) {
5565                    Slog.v(TAG, "   ...including browsers in candidate set");
5566                }
5567                if ((matchFlags & MATCH_ALL) != 0) {
5568                    result.addAll(matchAllList);
5569                } else {
5570                    // Browser/generic handling case.  If there's a default browser, go straight
5571                    // to that (but only if there is no other higher-priority match).
5572                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5573                    int maxMatchPrio = 0;
5574                    ResolveInfo defaultBrowserMatch = null;
5575                    final int numCandidates = matchAllList.size();
5576                    for (int n = 0; n < numCandidates; n++) {
5577                        ResolveInfo info = matchAllList.get(n);
5578                        // track the highest overall match priority...
5579                        if (info.priority > maxMatchPrio) {
5580                            maxMatchPrio = info.priority;
5581                        }
5582                        // ...and the highest-priority default browser match
5583                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5584                            if (defaultBrowserMatch == null
5585                                    || (defaultBrowserMatch.priority < info.priority)) {
5586                                if (debug) {
5587                                    Slog.v(TAG, "Considering default browser match " + info);
5588                                }
5589                                defaultBrowserMatch = info;
5590                            }
5591                        }
5592                    }
5593                    if (defaultBrowserMatch != null
5594                            && defaultBrowserMatch.priority >= maxMatchPrio
5595                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5596                    {
5597                        if (debug) {
5598                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5599                        }
5600                        result.add(defaultBrowserMatch);
5601                    } else {
5602                        result.addAll(matchAllList);
5603                    }
5604                }
5605
5606                // If there is nothing selected, add all candidates and remove the ones that the user
5607                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5608                if (result.size() == 0) {
5609                    result.addAll(candidates);
5610                    result.removeAll(neverList);
5611                }
5612            }
5613        }
5614        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5615            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5616                    result.size());
5617            for (ResolveInfo info : result) {
5618                Slog.v(TAG, "  + " + info.activityInfo);
5619            }
5620        }
5621        return result;
5622    }
5623
5624    // Returns a packed value as a long:
5625    //
5626    // high 'int'-sized word: link status: undefined/ask/never/always.
5627    // low 'int'-sized word: relative priority among 'always' results.
5628    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5629        long result = ps.getDomainVerificationStatusForUser(userId);
5630        // if none available, get the master status
5631        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5632            if (ps.getIntentFilterVerificationInfo() != null) {
5633                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5634            }
5635        }
5636        return result;
5637    }
5638
5639    private ResolveInfo querySkipCurrentProfileIntents(
5640            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5641            int flags, int sourceUserId) {
5642        if (matchingFilters != null) {
5643            int size = matchingFilters.size();
5644            for (int i = 0; i < size; i ++) {
5645                CrossProfileIntentFilter filter = matchingFilters.get(i);
5646                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5647                    // Checking if there are activities in the target user that can handle the
5648                    // intent.
5649                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5650                            resolvedType, flags, sourceUserId);
5651                    if (resolveInfo != null) {
5652                        return resolveInfo;
5653                    }
5654                }
5655            }
5656        }
5657        return null;
5658    }
5659
5660    // Return matching ResolveInfo in target user if any.
5661    private ResolveInfo queryCrossProfileIntents(
5662            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5663            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5664        if (matchingFilters != null) {
5665            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5666            // match the same intent. For performance reasons, it is better not to
5667            // run queryIntent twice for the same userId
5668            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5669            int size = matchingFilters.size();
5670            for (int i = 0; i < size; i++) {
5671                CrossProfileIntentFilter filter = matchingFilters.get(i);
5672                int targetUserId = filter.getTargetUserId();
5673                boolean skipCurrentProfile =
5674                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5675                boolean skipCurrentProfileIfNoMatchFound =
5676                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5677                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5678                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5679                    // Checking if there are activities in the target user that can handle the
5680                    // intent.
5681                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5682                            resolvedType, flags, sourceUserId);
5683                    if (resolveInfo != null) return resolveInfo;
5684                    alreadyTriedUserIds.put(targetUserId, true);
5685                }
5686            }
5687        }
5688        return null;
5689    }
5690
5691    /**
5692     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5693     * will forward the intent to the filter's target user.
5694     * Otherwise, returns null.
5695     */
5696    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5697            String resolvedType, int flags, int sourceUserId) {
5698        int targetUserId = filter.getTargetUserId();
5699        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5700                resolvedType, flags, targetUserId);
5701        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5702            // If all the matches in the target profile are suspended, return null.
5703            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5704                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5705                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5706                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5707                            targetUserId);
5708                }
5709            }
5710        }
5711        return null;
5712    }
5713
5714    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5715            int sourceUserId, int targetUserId) {
5716        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5717        long ident = Binder.clearCallingIdentity();
5718        boolean targetIsProfile;
5719        try {
5720            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5721        } finally {
5722            Binder.restoreCallingIdentity(ident);
5723        }
5724        String className;
5725        if (targetIsProfile) {
5726            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5727        } else {
5728            className = FORWARD_INTENT_TO_PARENT;
5729        }
5730        ComponentName forwardingActivityComponentName = new ComponentName(
5731                mAndroidApplication.packageName, className);
5732        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5733                sourceUserId);
5734        if (!targetIsProfile) {
5735            forwardingActivityInfo.showUserIcon = targetUserId;
5736            forwardingResolveInfo.noResourceId = true;
5737        }
5738        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5739        forwardingResolveInfo.priority = 0;
5740        forwardingResolveInfo.preferredOrder = 0;
5741        forwardingResolveInfo.match = 0;
5742        forwardingResolveInfo.isDefault = true;
5743        forwardingResolveInfo.filter = filter;
5744        forwardingResolveInfo.targetUserId = targetUserId;
5745        return forwardingResolveInfo;
5746    }
5747
5748    @Override
5749    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5750            Intent[] specifics, String[] specificTypes, Intent intent,
5751            String resolvedType, int flags, int userId) {
5752        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5753                specificTypes, intent, resolvedType, flags, userId));
5754    }
5755
5756    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5757            Intent[] specifics, String[] specificTypes, Intent intent,
5758            String resolvedType, int flags, int userId) {
5759        if (!sUserManager.exists(userId)) return Collections.emptyList();
5760        flags = updateFlagsForResolve(flags, userId, intent);
5761        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5762                false /* requireFullPermission */, false /* checkShell */,
5763                "query intent activity options");
5764        final String resultsAction = intent.getAction();
5765
5766        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5767                | PackageManager.GET_RESOLVED_FILTER, userId);
5768
5769        if (DEBUG_INTENT_MATCHING) {
5770            Log.v(TAG, "Query " + intent + ": " + results);
5771        }
5772
5773        int specificsPos = 0;
5774        int N;
5775
5776        // todo: note that the algorithm used here is O(N^2).  This
5777        // isn't a problem in our current environment, but if we start running
5778        // into situations where we have more than 5 or 10 matches then this
5779        // should probably be changed to something smarter...
5780
5781        // First we go through and resolve each of the specific items
5782        // that were supplied, taking care of removing any corresponding
5783        // duplicate items in the generic resolve list.
5784        if (specifics != null) {
5785            for (int i=0; i<specifics.length; i++) {
5786                final Intent sintent = specifics[i];
5787                if (sintent == null) {
5788                    continue;
5789                }
5790
5791                if (DEBUG_INTENT_MATCHING) {
5792                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5793                }
5794
5795                String action = sintent.getAction();
5796                if (resultsAction != null && resultsAction.equals(action)) {
5797                    // If this action was explicitly requested, then don't
5798                    // remove things that have it.
5799                    action = null;
5800                }
5801
5802                ResolveInfo ri = null;
5803                ActivityInfo ai = null;
5804
5805                ComponentName comp = sintent.getComponent();
5806                if (comp == null) {
5807                    ri = resolveIntent(
5808                        sintent,
5809                        specificTypes != null ? specificTypes[i] : null,
5810                            flags, userId);
5811                    if (ri == null) {
5812                        continue;
5813                    }
5814                    if (ri == mResolveInfo) {
5815                        // ACK!  Must do something better with this.
5816                    }
5817                    ai = ri.activityInfo;
5818                    comp = new ComponentName(ai.applicationInfo.packageName,
5819                            ai.name);
5820                } else {
5821                    ai = getActivityInfo(comp, flags, userId);
5822                    if (ai == null) {
5823                        continue;
5824                    }
5825                }
5826
5827                // Look for any generic query activities that are duplicates
5828                // of this specific one, and remove them from the results.
5829                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5830                N = results.size();
5831                int j;
5832                for (j=specificsPos; j<N; j++) {
5833                    ResolveInfo sri = results.get(j);
5834                    if ((sri.activityInfo.name.equals(comp.getClassName())
5835                            && sri.activityInfo.applicationInfo.packageName.equals(
5836                                    comp.getPackageName()))
5837                        || (action != null && sri.filter.matchAction(action))) {
5838                        results.remove(j);
5839                        if (DEBUG_INTENT_MATCHING) Log.v(
5840                            TAG, "Removing duplicate item from " + j
5841                            + " due to specific " + specificsPos);
5842                        if (ri == null) {
5843                            ri = sri;
5844                        }
5845                        j--;
5846                        N--;
5847                    }
5848                }
5849
5850                // Add this specific item to its proper place.
5851                if (ri == null) {
5852                    ri = new ResolveInfo();
5853                    ri.activityInfo = ai;
5854                }
5855                results.add(specificsPos, ri);
5856                ri.specificIndex = i;
5857                specificsPos++;
5858            }
5859        }
5860
5861        // Now we go through the remaining generic results and remove any
5862        // duplicate actions that are found here.
5863        N = results.size();
5864        for (int i=specificsPos; i<N-1; i++) {
5865            final ResolveInfo rii = results.get(i);
5866            if (rii.filter == null) {
5867                continue;
5868            }
5869
5870            // Iterate over all of the actions of this result's intent
5871            // filter...  typically this should be just one.
5872            final Iterator<String> it = rii.filter.actionsIterator();
5873            if (it == null) {
5874                continue;
5875            }
5876            while (it.hasNext()) {
5877                final String action = it.next();
5878                if (resultsAction != null && resultsAction.equals(action)) {
5879                    // If this action was explicitly requested, then don't
5880                    // remove things that have it.
5881                    continue;
5882                }
5883                for (int j=i+1; j<N; j++) {
5884                    final ResolveInfo rij = results.get(j);
5885                    if (rij.filter != null && rij.filter.hasAction(action)) {
5886                        results.remove(j);
5887                        if (DEBUG_INTENT_MATCHING) Log.v(
5888                            TAG, "Removing duplicate item from " + j
5889                            + " due to action " + action + " at " + i);
5890                        j--;
5891                        N--;
5892                    }
5893                }
5894            }
5895
5896            // If the caller didn't request filter information, drop it now
5897            // so we don't have to marshall/unmarshall it.
5898            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5899                rii.filter = null;
5900            }
5901        }
5902
5903        // Filter out the caller activity if so requested.
5904        if (caller != null) {
5905            N = results.size();
5906            for (int i=0; i<N; i++) {
5907                ActivityInfo ainfo = results.get(i).activityInfo;
5908                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5909                        && caller.getClassName().equals(ainfo.name)) {
5910                    results.remove(i);
5911                    break;
5912                }
5913            }
5914        }
5915
5916        // If the caller didn't request filter information,
5917        // drop them now so we don't have to
5918        // marshall/unmarshall it.
5919        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5920            N = results.size();
5921            for (int i=0; i<N; i++) {
5922                results.get(i).filter = null;
5923            }
5924        }
5925
5926        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5927        return results;
5928    }
5929
5930    @Override
5931    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5932            String resolvedType, int flags, int userId) {
5933        return new ParceledListSlice<>(
5934                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5935    }
5936
5937    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5938            String resolvedType, int flags, int userId) {
5939        if (!sUserManager.exists(userId)) return Collections.emptyList();
5940        flags = updateFlagsForResolve(flags, userId, intent);
5941        ComponentName comp = intent.getComponent();
5942        if (comp == null) {
5943            if (intent.getSelector() != null) {
5944                intent = intent.getSelector();
5945                comp = intent.getComponent();
5946            }
5947        }
5948        if (comp != null) {
5949            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5950            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5951            if (ai != null) {
5952                ResolveInfo ri = new ResolveInfo();
5953                ri.activityInfo = ai;
5954                list.add(ri);
5955            }
5956            return list;
5957        }
5958
5959        // reader
5960        synchronized (mPackages) {
5961            String pkgName = intent.getPackage();
5962            if (pkgName == null) {
5963                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5964            }
5965            final PackageParser.Package pkg = mPackages.get(pkgName);
5966            if (pkg != null) {
5967                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5968                        userId);
5969            }
5970            return Collections.emptyList();
5971        }
5972    }
5973
5974    @Override
5975    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5976        if (!sUserManager.exists(userId)) return null;
5977        flags = updateFlagsForResolve(flags, userId, intent);
5978        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5979        if (query != null) {
5980            if (query.size() >= 1) {
5981                // If there is more than one service with the same priority,
5982                // just arbitrarily pick the first one.
5983                return query.get(0);
5984            }
5985        }
5986        return null;
5987    }
5988
5989    @Override
5990    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5991            String resolvedType, int flags, int userId) {
5992        return new ParceledListSlice<>(
5993                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5994    }
5995
5996    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5997            String resolvedType, int flags, int userId) {
5998        if (!sUserManager.exists(userId)) return Collections.emptyList();
5999        flags = updateFlagsForResolve(flags, userId, intent);
6000        ComponentName comp = intent.getComponent();
6001        if (comp == null) {
6002            if (intent.getSelector() != null) {
6003                intent = intent.getSelector();
6004                comp = intent.getComponent();
6005            }
6006        }
6007        if (comp != null) {
6008            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6009            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6010            if (si != null) {
6011                final ResolveInfo ri = new ResolveInfo();
6012                ri.serviceInfo = si;
6013                list.add(ri);
6014            }
6015            return list;
6016        }
6017
6018        // reader
6019        synchronized (mPackages) {
6020            String pkgName = intent.getPackage();
6021            if (pkgName == null) {
6022                return mServices.queryIntent(intent, resolvedType, flags, userId);
6023            }
6024            final PackageParser.Package pkg = mPackages.get(pkgName);
6025            if (pkg != null) {
6026                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6027                        userId);
6028            }
6029            return Collections.emptyList();
6030        }
6031    }
6032
6033    @Override
6034    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6035            String resolvedType, int flags, int userId) {
6036        return new ParceledListSlice<>(
6037                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6038    }
6039
6040    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6041            Intent intent, String resolvedType, int flags, int userId) {
6042        if (!sUserManager.exists(userId)) return Collections.emptyList();
6043        flags = updateFlagsForResolve(flags, userId, intent);
6044        ComponentName comp = intent.getComponent();
6045        if (comp == null) {
6046            if (intent.getSelector() != null) {
6047                intent = intent.getSelector();
6048                comp = intent.getComponent();
6049            }
6050        }
6051        if (comp != null) {
6052            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6053            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6054            if (pi != null) {
6055                final ResolveInfo ri = new ResolveInfo();
6056                ri.providerInfo = pi;
6057                list.add(ri);
6058            }
6059            return list;
6060        }
6061
6062        // reader
6063        synchronized (mPackages) {
6064            String pkgName = intent.getPackage();
6065            if (pkgName == null) {
6066                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6067            }
6068            final PackageParser.Package pkg = mPackages.get(pkgName);
6069            if (pkg != null) {
6070                return mProviders.queryIntentForPackage(
6071                        intent, resolvedType, flags, pkg.providers, userId);
6072            }
6073            return Collections.emptyList();
6074        }
6075    }
6076
6077    @Override
6078    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6079        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6080        flags = updateFlagsForPackage(flags, userId, null);
6081        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6082        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6083                true /* requireFullPermission */, false /* checkShell */,
6084                "get installed packages");
6085
6086        // writer
6087        synchronized (mPackages) {
6088            ArrayList<PackageInfo> list;
6089            if (listUninstalled) {
6090                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6091                for (PackageSetting ps : mSettings.mPackages.values()) {
6092                    final PackageInfo pi;
6093                    if (ps.pkg != null) {
6094                        pi = generatePackageInfo(ps, flags, userId);
6095                    } else {
6096                        pi = generatePackageInfo(ps, flags, userId);
6097                    }
6098                    if (pi != null) {
6099                        list.add(pi);
6100                    }
6101                }
6102            } else {
6103                list = new ArrayList<PackageInfo>(mPackages.size());
6104                for (PackageParser.Package p : mPackages.values()) {
6105                    final PackageInfo pi =
6106                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6107                    if (pi != null) {
6108                        list.add(pi);
6109                    }
6110                }
6111            }
6112
6113            return new ParceledListSlice<PackageInfo>(list);
6114        }
6115    }
6116
6117    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6118            String[] permissions, boolean[] tmp, int flags, int userId) {
6119        int numMatch = 0;
6120        final PermissionsState permissionsState = ps.getPermissionsState();
6121        for (int i=0; i<permissions.length; i++) {
6122            final String permission = permissions[i];
6123            if (permissionsState.hasPermission(permission, userId)) {
6124                tmp[i] = true;
6125                numMatch++;
6126            } else {
6127                tmp[i] = false;
6128            }
6129        }
6130        if (numMatch == 0) {
6131            return;
6132        }
6133        final PackageInfo pi;
6134        if (ps.pkg != null) {
6135            pi = generatePackageInfo(ps, flags, userId);
6136        } else {
6137            pi = generatePackageInfo(ps, flags, userId);
6138        }
6139        // The above might return null in cases of uninstalled apps or install-state
6140        // skew across users/profiles.
6141        if (pi != null) {
6142            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6143                if (numMatch == permissions.length) {
6144                    pi.requestedPermissions = permissions;
6145                } else {
6146                    pi.requestedPermissions = new String[numMatch];
6147                    numMatch = 0;
6148                    for (int i=0; i<permissions.length; i++) {
6149                        if (tmp[i]) {
6150                            pi.requestedPermissions[numMatch] = permissions[i];
6151                            numMatch++;
6152                        }
6153                    }
6154                }
6155            }
6156            list.add(pi);
6157        }
6158    }
6159
6160    @Override
6161    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6162            String[] permissions, int flags, int userId) {
6163        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6164        flags = updateFlagsForPackage(flags, userId, permissions);
6165        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6166
6167        // writer
6168        synchronized (mPackages) {
6169            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6170            boolean[] tmpBools = new boolean[permissions.length];
6171            if (listUninstalled) {
6172                for (PackageSetting ps : mSettings.mPackages.values()) {
6173                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6174                }
6175            } else {
6176                for (PackageParser.Package pkg : mPackages.values()) {
6177                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6178                    if (ps != null) {
6179                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6180                                userId);
6181                    }
6182                }
6183            }
6184
6185            return new ParceledListSlice<PackageInfo>(list);
6186        }
6187    }
6188
6189    @Override
6190    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6191        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6192        flags = updateFlagsForApplication(flags, userId, null);
6193        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6194
6195        // writer
6196        synchronized (mPackages) {
6197            ArrayList<ApplicationInfo> list;
6198            if (listUninstalled) {
6199                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6200                for (PackageSetting ps : mSettings.mPackages.values()) {
6201                    ApplicationInfo ai;
6202                    if (ps.pkg != null) {
6203                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6204                                ps.readUserState(userId), userId);
6205                    } else {
6206                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6207                    }
6208                    if (ai != null) {
6209                        list.add(ai);
6210                    }
6211                }
6212            } else {
6213                list = new ArrayList<ApplicationInfo>(mPackages.size());
6214                for (PackageParser.Package p : mPackages.values()) {
6215                    if (p.mExtras != null) {
6216                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6217                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6218                        if (ai != null) {
6219                            list.add(ai);
6220                        }
6221                    }
6222                }
6223            }
6224
6225            return new ParceledListSlice<ApplicationInfo>(list);
6226        }
6227    }
6228
6229    @Override
6230    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6231        if (DISABLE_EPHEMERAL_APPS) {
6232            return null;
6233        }
6234
6235        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6236                "getEphemeralApplications");
6237        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6238                true /* requireFullPermission */, false /* checkShell */,
6239                "getEphemeralApplications");
6240        synchronized (mPackages) {
6241            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6242                    .getEphemeralApplicationsLPw(userId);
6243            if (ephemeralApps != null) {
6244                return new ParceledListSlice<>(ephemeralApps);
6245            }
6246        }
6247        return null;
6248    }
6249
6250    @Override
6251    public boolean isEphemeralApplication(String packageName, int userId) {
6252        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6253                true /* requireFullPermission */, false /* checkShell */,
6254                "isEphemeral");
6255        if (DISABLE_EPHEMERAL_APPS) {
6256            return false;
6257        }
6258
6259        if (!isCallerSameApp(packageName)) {
6260            return false;
6261        }
6262        synchronized (mPackages) {
6263            PackageParser.Package pkg = mPackages.get(packageName);
6264            if (pkg != null) {
6265                return pkg.applicationInfo.isEphemeralApp();
6266            }
6267        }
6268        return false;
6269    }
6270
6271    @Override
6272    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6273        if (DISABLE_EPHEMERAL_APPS) {
6274            return null;
6275        }
6276
6277        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6278                true /* requireFullPermission */, false /* checkShell */,
6279                "getCookie");
6280        if (!isCallerSameApp(packageName)) {
6281            return null;
6282        }
6283        synchronized (mPackages) {
6284            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6285                    packageName, userId);
6286        }
6287    }
6288
6289    @Override
6290    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6291        if (DISABLE_EPHEMERAL_APPS) {
6292            return true;
6293        }
6294
6295        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6296                true /* requireFullPermission */, true /* checkShell */,
6297                "setCookie");
6298        if (!isCallerSameApp(packageName)) {
6299            return false;
6300        }
6301        synchronized (mPackages) {
6302            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6303                    packageName, cookie, userId);
6304        }
6305    }
6306
6307    @Override
6308    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6309        if (DISABLE_EPHEMERAL_APPS) {
6310            return null;
6311        }
6312
6313        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6314                "getEphemeralApplicationIcon");
6315        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6316                true /* requireFullPermission */, false /* checkShell */,
6317                "getEphemeralApplicationIcon");
6318        synchronized (mPackages) {
6319            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6320                    packageName, userId);
6321        }
6322    }
6323
6324    private boolean isCallerSameApp(String packageName) {
6325        PackageParser.Package pkg = mPackages.get(packageName);
6326        return pkg != null
6327                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6328    }
6329
6330    @Override
6331    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6332        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6333    }
6334
6335    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6336        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6337
6338        // reader
6339        synchronized (mPackages) {
6340            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6341            final int userId = UserHandle.getCallingUserId();
6342            while (i.hasNext()) {
6343                final PackageParser.Package p = i.next();
6344                if (p.applicationInfo == null) continue;
6345
6346                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6347                        && !p.applicationInfo.isDirectBootAware();
6348                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6349                        && p.applicationInfo.isDirectBootAware();
6350
6351                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6352                        && (!mSafeMode || isSystemApp(p))
6353                        && (matchesUnaware || matchesAware)) {
6354                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6355                    if (ps != null) {
6356                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6357                                ps.readUserState(userId), userId);
6358                        if (ai != null) {
6359                            finalList.add(ai);
6360                        }
6361                    }
6362                }
6363            }
6364        }
6365
6366        return finalList;
6367    }
6368
6369    @Override
6370    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6371        if (!sUserManager.exists(userId)) return null;
6372        flags = updateFlagsForComponent(flags, userId, name);
6373        // reader
6374        synchronized (mPackages) {
6375            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6376            PackageSetting ps = provider != null
6377                    ? mSettings.mPackages.get(provider.owner.packageName)
6378                    : null;
6379            return ps != null
6380                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6381                    ? PackageParser.generateProviderInfo(provider, flags,
6382                            ps.readUserState(userId), userId)
6383                    : null;
6384        }
6385    }
6386
6387    /**
6388     * @deprecated
6389     */
6390    @Deprecated
6391    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6392        // reader
6393        synchronized (mPackages) {
6394            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6395                    .entrySet().iterator();
6396            final int userId = UserHandle.getCallingUserId();
6397            while (i.hasNext()) {
6398                Map.Entry<String, PackageParser.Provider> entry = i.next();
6399                PackageParser.Provider p = entry.getValue();
6400                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6401
6402                if (ps != null && p.syncable
6403                        && (!mSafeMode || (p.info.applicationInfo.flags
6404                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6405                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6406                            ps.readUserState(userId), userId);
6407                    if (info != null) {
6408                        outNames.add(entry.getKey());
6409                        outInfo.add(info);
6410                    }
6411                }
6412            }
6413        }
6414    }
6415
6416    @Override
6417    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6418            int uid, int flags) {
6419        final int userId = processName != null ? UserHandle.getUserId(uid)
6420                : UserHandle.getCallingUserId();
6421        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6422        flags = updateFlagsForComponent(flags, userId, processName);
6423
6424        ArrayList<ProviderInfo> finalList = null;
6425        // reader
6426        synchronized (mPackages) {
6427            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6428            while (i.hasNext()) {
6429                final PackageParser.Provider p = i.next();
6430                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6431                if (ps != null && p.info.authority != null
6432                        && (processName == null
6433                                || (p.info.processName.equals(processName)
6434                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6435                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6436                    if (finalList == null) {
6437                        finalList = new ArrayList<ProviderInfo>(3);
6438                    }
6439                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6440                            ps.readUserState(userId), userId);
6441                    if (info != null) {
6442                        finalList.add(info);
6443                    }
6444                }
6445            }
6446        }
6447
6448        if (finalList != null) {
6449            Collections.sort(finalList, mProviderInitOrderSorter);
6450            return new ParceledListSlice<ProviderInfo>(finalList);
6451        }
6452
6453        return ParceledListSlice.emptyList();
6454    }
6455
6456    @Override
6457    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6458        // reader
6459        synchronized (mPackages) {
6460            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6461            return PackageParser.generateInstrumentationInfo(i, flags);
6462        }
6463    }
6464
6465    @Override
6466    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6467            String targetPackage, int flags) {
6468        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6469    }
6470
6471    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6472            int flags) {
6473        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6474
6475        // reader
6476        synchronized (mPackages) {
6477            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6478            while (i.hasNext()) {
6479                final PackageParser.Instrumentation p = i.next();
6480                if (targetPackage == null
6481                        || targetPackage.equals(p.info.targetPackage)) {
6482                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6483                            flags);
6484                    if (ii != null) {
6485                        finalList.add(ii);
6486                    }
6487                }
6488            }
6489        }
6490
6491        return finalList;
6492    }
6493
6494    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6495        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6496        if (overlays == null) {
6497            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6498            return;
6499        }
6500        for (PackageParser.Package opkg : overlays.values()) {
6501            // Not much to do if idmap fails: we already logged the error
6502            // and we certainly don't want to abort installation of pkg simply
6503            // because an overlay didn't fit properly. For these reasons,
6504            // ignore the return value of createIdmapForPackagePairLI.
6505            createIdmapForPackagePairLI(pkg, opkg);
6506        }
6507    }
6508
6509    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6510            PackageParser.Package opkg) {
6511        if (!opkg.mTrustedOverlay) {
6512            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6513                    opkg.baseCodePath + ": overlay not trusted");
6514            return false;
6515        }
6516        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6517        if (overlaySet == null) {
6518            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6519                    opkg.baseCodePath + " but target package has no known overlays");
6520            return false;
6521        }
6522        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6523        // TODO: generate idmap for split APKs
6524        try {
6525            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6526        } catch (InstallerException e) {
6527            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6528                    + opkg.baseCodePath);
6529            return false;
6530        }
6531        PackageParser.Package[] overlayArray =
6532            overlaySet.values().toArray(new PackageParser.Package[0]);
6533        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6534            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6535                return p1.mOverlayPriority - p2.mOverlayPriority;
6536            }
6537        };
6538        Arrays.sort(overlayArray, cmp);
6539
6540        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6541        int i = 0;
6542        for (PackageParser.Package p : overlayArray) {
6543            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6544        }
6545        return true;
6546    }
6547
6548    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6549        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6550        try {
6551            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6552        } finally {
6553            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6554        }
6555    }
6556
6557    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6558        final File[] files = dir.listFiles();
6559        if (ArrayUtils.isEmpty(files)) {
6560            Log.d(TAG, "No files in app dir " + dir);
6561            return;
6562        }
6563
6564        if (DEBUG_PACKAGE_SCANNING) {
6565            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6566                    + " flags=0x" + Integer.toHexString(parseFlags));
6567        }
6568
6569        for (File file : files) {
6570            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6571                    && !PackageInstallerService.isStageName(file.getName());
6572            if (!isPackage) {
6573                // Ignore entries which are not packages
6574                continue;
6575            }
6576            try {
6577                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6578                        scanFlags, currentTime, null);
6579            } catch (PackageManagerException e) {
6580                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6581
6582                // Delete invalid userdata apps
6583                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6584                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6585                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6586                    removeCodePathLI(file);
6587                }
6588            }
6589        }
6590    }
6591
6592    private static File getSettingsProblemFile() {
6593        File dataDir = Environment.getDataDirectory();
6594        File systemDir = new File(dataDir, "system");
6595        File fname = new File(systemDir, "uiderrors.txt");
6596        return fname;
6597    }
6598
6599    static void reportSettingsProblem(int priority, String msg) {
6600        logCriticalInfo(priority, msg);
6601    }
6602
6603    static void logCriticalInfo(int priority, String msg) {
6604        Slog.println(priority, TAG, msg);
6605        EventLogTags.writePmCriticalInfo(msg);
6606        try {
6607            File fname = getSettingsProblemFile();
6608            FileOutputStream out = new FileOutputStream(fname, true);
6609            PrintWriter pw = new FastPrintWriter(out);
6610            SimpleDateFormat formatter = new SimpleDateFormat();
6611            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6612            pw.println(dateString + ": " + msg);
6613            pw.close();
6614            FileUtils.setPermissions(
6615                    fname.toString(),
6616                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6617                    -1, -1);
6618        } catch (java.io.IOException e) {
6619        }
6620    }
6621
6622    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6623        if (srcFile.isDirectory()) {
6624            final File baseFile = new File(pkg.baseCodePath);
6625            long maxModifiedTime = baseFile.lastModified();
6626            if (pkg.splitCodePaths != null) {
6627                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6628                    final File splitFile = new File(pkg.splitCodePaths[i]);
6629                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6630                }
6631            }
6632            return maxModifiedTime;
6633        }
6634        return srcFile.lastModified();
6635    }
6636
6637    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6638            final int policyFlags) throws PackageManagerException {
6639        // When upgrading from pre-N MR1, verify the package time stamp using the package
6640        // directory and not the APK file.
6641        final long lastModifiedTime = mIsPreNMR1Upgrade
6642                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6643        if (ps != null
6644                && ps.codePath.equals(srcFile)
6645                && ps.timeStamp == lastModifiedTime
6646                && !isCompatSignatureUpdateNeeded(pkg)
6647                && !isRecoverSignatureUpdateNeeded(pkg)) {
6648            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6649            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6650            ArraySet<PublicKey> signingKs;
6651            synchronized (mPackages) {
6652                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6653            }
6654            if (ps.signatures.mSignatures != null
6655                    && ps.signatures.mSignatures.length != 0
6656                    && signingKs != null) {
6657                // Optimization: reuse the existing cached certificates
6658                // if the package appears to be unchanged.
6659                pkg.mSignatures = ps.signatures.mSignatures;
6660                pkg.mSigningKeys = signingKs;
6661                return;
6662            }
6663
6664            Slog.w(TAG, "PackageSetting for " + ps.name
6665                    + " is missing signatures.  Collecting certs again to recover them.");
6666        } else {
6667            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6668        }
6669
6670        try {
6671            PackageParser.collectCertificates(pkg, policyFlags);
6672        } catch (PackageParserException e) {
6673            throw PackageManagerException.from(e);
6674        }
6675    }
6676
6677    /**
6678     *  Traces a package scan.
6679     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6680     */
6681    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6682            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6684        try {
6685            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6686        } finally {
6687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6688        }
6689    }
6690
6691    /**
6692     *  Scans a package and returns the newly parsed package.
6693     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6694     */
6695    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6696            long currentTime, UserHandle user) throws PackageManagerException {
6697        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6698        PackageParser pp = new PackageParser();
6699        pp.setSeparateProcesses(mSeparateProcesses);
6700        pp.setOnlyCoreApps(mOnlyCore);
6701        pp.setDisplayMetrics(mMetrics);
6702
6703        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6704            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6705        }
6706
6707        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6708        final PackageParser.Package pkg;
6709        try {
6710            pkg = pp.parsePackage(scanFile, parseFlags);
6711        } catch (PackageParserException e) {
6712            throw PackageManagerException.from(e);
6713        } finally {
6714            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6715        }
6716
6717        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6718    }
6719
6720    /**
6721     *  Scans a package and returns the newly parsed package.
6722     *  @throws PackageManagerException on a parse error.
6723     */
6724    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6725            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6726            throws PackageManagerException {
6727        // If the package has children and this is the first dive in the function
6728        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6729        // packages (parent and children) would be successfully scanned before the
6730        // actual scan since scanning mutates internal state and we want to atomically
6731        // install the package and its children.
6732        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6733            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6734                scanFlags |= SCAN_CHECK_ONLY;
6735            }
6736        } else {
6737            scanFlags &= ~SCAN_CHECK_ONLY;
6738        }
6739
6740        // Scan the parent
6741        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6742                scanFlags, currentTime, user);
6743
6744        // Scan the children
6745        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6746        for (int i = 0; i < childCount; i++) {
6747            PackageParser.Package childPackage = pkg.childPackages.get(i);
6748            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6749                    currentTime, user);
6750        }
6751
6752
6753        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6754            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6755        }
6756
6757        return scannedPkg;
6758    }
6759
6760    /**
6761     *  Scans a package and returns the newly parsed package.
6762     *  @throws PackageManagerException on a parse error.
6763     */
6764    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6765            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6766            throws PackageManagerException {
6767        PackageSetting ps = null;
6768        PackageSetting updatedPkg;
6769        // reader
6770        synchronized (mPackages) {
6771            // Look to see if we already know about this package.
6772            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6773            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6774                // This package has been renamed to its original name.  Let's
6775                // use that.
6776                ps = mSettings.peekPackageLPr(oldName);
6777            }
6778            // If there was no original package, see one for the real package name.
6779            if (ps == null) {
6780                ps = mSettings.peekPackageLPr(pkg.packageName);
6781            }
6782            // Check to see if this package could be hiding/updating a system
6783            // package.  Must look for it either under the original or real
6784            // package name depending on our state.
6785            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6786            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6787
6788            // If this is a package we don't know about on the system partition, we
6789            // may need to remove disabled child packages on the system partition
6790            // or may need to not add child packages if the parent apk is updated
6791            // on the data partition and no longer defines this child package.
6792            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6793                // If this is a parent package for an updated system app and this system
6794                // app got an OTA update which no longer defines some of the child packages
6795                // we have to prune them from the disabled system packages.
6796                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6797                if (disabledPs != null) {
6798                    final int scannedChildCount = (pkg.childPackages != null)
6799                            ? pkg.childPackages.size() : 0;
6800                    final int disabledChildCount = disabledPs.childPackageNames != null
6801                            ? disabledPs.childPackageNames.size() : 0;
6802                    for (int i = 0; i < disabledChildCount; i++) {
6803                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6804                        boolean disabledPackageAvailable = false;
6805                        for (int j = 0; j < scannedChildCount; j++) {
6806                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6807                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6808                                disabledPackageAvailable = true;
6809                                break;
6810                            }
6811                         }
6812                         if (!disabledPackageAvailable) {
6813                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6814                         }
6815                    }
6816                }
6817            }
6818        }
6819
6820        boolean updatedPkgBetter = false;
6821        // First check if this is a system package that may involve an update
6822        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6823            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6824            // it needs to drop FLAG_PRIVILEGED.
6825            if (locationIsPrivileged(scanFile)) {
6826                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6827            } else {
6828                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6829            }
6830
6831            if (ps != null && !ps.codePath.equals(scanFile)) {
6832                // The path has changed from what was last scanned...  check the
6833                // version of the new path against what we have stored to determine
6834                // what to do.
6835                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6836                if (pkg.mVersionCode <= ps.versionCode) {
6837                    // The system package has been updated and the code path does not match
6838                    // Ignore entry. Skip it.
6839                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6840                            + " ignored: updated version " + ps.versionCode
6841                            + " better than this " + pkg.mVersionCode);
6842                    if (!updatedPkg.codePath.equals(scanFile)) {
6843                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6844                                + ps.name + " changing from " + updatedPkg.codePathString
6845                                + " to " + scanFile);
6846                        updatedPkg.codePath = scanFile;
6847                        updatedPkg.codePathString = scanFile.toString();
6848                        updatedPkg.resourcePath = scanFile;
6849                        updatedPkg.resourcePathString = scanFile.toString();
6850                    }
6851                    updatedPkg.pkg = pkg;
6852                    updatedPkg.versionCode = pkg.mVersionCode;
6853
6854                    // Update the disabled system child packages to point to the package too.
6855                    final int childCount = updatedPkg.childPackageNames != null
6856                            ? updatedPkg.childPackageNames.size() : 0;
6857                    for (int i = 0; i < childCount; i++) {
6858                        String childPackageName = updatedPkg.childPackageNames.get(i);
6859                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6860                                childPackageName);
6861                        if (updatedChildPkg != null) {
6862                            updatedChildPkg.pkg = pkg;
6863                            updatedChildPkg.versionCode = pkg.mVersionCode;
6864                        }
6865                    }
6866
6867                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6868                            + scanFile + " ignored: updated version " + ps.versionCode
6869                            + " better than this " + pkg.mVersionCode);
6870                } else {
6871                    // The current app on the system partition is better than
6872                    // what we have updated to on the data partition; switch
6873                    // back to the system partition version.
6874                    // At this point, its safely assumed that package installation for
6875                    // apps in system partition will go through. If not there won't be a working
6876                    // version of the app
6877                    // writer
6878                    synchronized (mPackages) {
6879                        // Just remove the loaded entries from package lists.
6880                        mPackages.remove(ps.name);
6881                    }
6882
6883                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6884                            + " reverting from " + ps.codePathString
6885                            + ": new version " + pkg.mVersionCode
6886                            + " better than installed " + ps.versionCode);
6887
6888                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6889                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6890                    synchronized (mInstallLock) {
6891                        args.cleanUpResourcesLI();
6892                    }
6893                    synchronized (mPackages) {
6894                        mSettings.enableSystemPackageLPw(ps.name);
6895                    }
6896                    updatedPkgBetter = true;
6897                }
6898            }
6899        }
6900
6901        if (updatedPkg != null) {
6902            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6903            // initially
6904            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6905
6906            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6907            // flag set initially
6908            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6909                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6910            }
6911        }
6912
6913        // Verify certificates against what was last scanned
6914        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6915
6916        /*
6917         * A new system app appeared, but we already had a non-system one of the
6918         * same name installed earlier.
6919         */
6920        boolean shouldHideSystemApp = false;
6921        if (updatedPkg == null && ps != null
6922                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6923            /*
6924             * Check to make sure the signatures match first. If they don't,
6925             * wipe the installed application and its data.
6926             */
6927            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6928                    != PackageManager.SIGNATURE_MATCH) {
6929                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6930                        + " signatures don't match existing userdata copy; removing");
6931                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6932                        "scanPackageInternalLI")) {
6933                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6934                }
6935                ps = null;
6936            } else {
6937                /*
6938                 * If the newly-added system app is an older version than the
6939                 * already installed version, hide it. It will be scanned later
6940                 * and re-added like an update.
6941                 */
6942                if (pkg.mVersionCode <= ps.versionCode) {
6943                    shouldHideSystemApp = true;
6944                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6945                            + " but new version " + pkg.mVersionCode + " better than installed "
6946                            + ps.versionCode + "; hiding system");
6947                } else {
6948                    /*
6949                     * The newly found system app is a newer version that the
6950                     * one previously installed. Simply remove the
6951                     * already-installed application and replace it with our own
6952                     * while keeping the application data.
6953                     */
6954                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6955                            + " reverting from " + ps.codePathString + ": new version "
6956                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6957                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6958                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6959                    synchronized (mInstallLock) {
6960                        args.cleanUpResourcesLI();
6961                    }
6962                }
6963            }
6964        }
6965
6966        // The apk is forward locked (not public) if its code and resources
6967        // are kept in different files. (except for app in either system or
6968        // vendor path).
6969        // TODO grab this value from PackageSettings
6970        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6971            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6972                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6973            }
6974        }
6975
6976        // TODO: extend to support forward-locked splits
6977        String resourcePath = null;
6978        String baseResourcePath = null;
6979        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6980            if (ps != null && ps.resourcePathString != null) {
6981                resourcePath = ps.resourcePathString;
6982                baseResourcePath = ps.resourcePathString;
6983            } else {
6984                // Should not happen at all. Just log an error.
6985                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6986            }
6987        } else {
6988            resourcePath = pkg.codePath;
6989            baseResourcePath = pkg.baseCodePath;
6990        }
6991
6992        // Set application objects path explicitly.
6993        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6994        pkg.setApplicationInfoCodePath(pkg.codePath);
6995        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6996        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6997        pkg.setApplicationInfoResourcePath(resourcePath);
6998        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6999        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7000
7001        // Note that we invoke the following method only if we are about to unpack an application
7002        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7003                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7004
7005        /*
7006         * If the system app should be overridden by a previously installed
7007         * data, hide the system app now and let the /data/app scan pick it up
7008         * again.
7009         */
7010        if (shouldHideSystemApp) {
7011            synchronized (mPackages) {
7012                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7013            }
7014        }
7015
7016        return scannedPkg;
7017    }
7018
7019    private static String fixProcessName(String defProcessName,
7020            String processName, int uid) {
7021        if (processName == null) {
7022            return defProcessName;
7023        }
7024        return processName;
7025    }
7026
7027    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7028            throws PackageManagerException {
7029        if (pkgSetting.signatures.mSignatures != null) {
7030            // Already existing package. Make sure signatures match
7031            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7032                    == PackageManager.SIGNATURE_MATCH;
7033            if (!match) {
7034                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7035                        == PackageManager.SIGNATURE_MATCH;
7036            }
7037            if (!match) {
7038                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7039                        == PackageManager.SIGNATURE_MATCH;
7040            }
7041            if (!match) {
7042                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7043                        + pkg.packageName + " signatures do not match the "
7044                        + "previously installed version; ignoring!");
7045            }
7046        }
7047
7048        // Check for shared user signatures
7049        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7050            // Already existing package. Make sure signatures match
7051            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7052                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7053            if (!match) {
7054                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7055                        == PackageManager.SIGNATURE_MATCH;
7056            }
7057            if (!match) {
7058                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7059                        == PackageManager.SIGNATURE_MATCH;
7060            }
7061            if (!match) {
7062                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7063                        "Package " + pkg.packageName
7064                        + " has no signatures that match those in shared user "
7065                        + pkgSetting.sharedUser.name + "; ignoring!");
7066            }
7067        }
7068    }
7069
7070    /**
7071     * Enforces that only the system UID or root's UID can call a method exposed
7072     * via Binder.
7073     *
7074     * @param message used as message if SecurityException is thrown
7075     * @throws SecurityException if the caller is not system or root
7076     */
7077    private static final void enforceSystemOrRoot(String message) {
7078        final int uid = Binder.getCallingUid();
7079        if (uid != Process.SYSTEM_UID && uid != 0) {
7080            throw new SecurityException(message);
7081        }
7082    }
7083
7084    @Override
7085    public void performFstrimIfNeeded() {
7086        enforceSystemOrRoot("Only the system can request fstrim");
7087
7088        // Before everything else, see whether we need to fstrim.
7089        try {
7090            IMountService ms = PackageHelper.getMountService();
7091            if (ms != null) {
7092                boolean doTrim = false;
7093                final long interval = android.provider.Settings.Global.getLong(
7094                        mContext.getContentResolver(),
7095                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7096                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7097                if (interval > 0) {
7098                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7099                    if (timeSinceLast > interval) {
7100                        doTrim = true;
7101                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7102                                + "; running immediately");
7103                    }
7104                }
7105                if (doTrim) {
7106                    if (!isFirstBoot()) {
7107                        try {
7108                            ActivityManagerNative.getDefault().showBootMessage(
7109                                    mContext.getResources().getString(
7110                                            R.string.android_upgrading_fstrim), true);
7111                        } catch (RemoteException e) {
7112                        }
7113                    }
7114                    ms.runMaintenance();
7115                }
7116            } else {
7117                Slog.e(TAG, "Mount service unavailable!");
7118            }
7119        } catch (RemoteException e) {
7120            // Can't happen; MountService is local
7121        }
7122    }
7123
7124    @Override
7125    public void updatePackagesIfNeeded() {
7126        enforceSystemOrRoot("Only the system can request package update");
7127
7128        // We need to re-extract after an OTA.
7129        boolean causeUpgrade = isUpgrade();
7130
7131        // First boot or factory reset.
7132        // Note: we also handle devices that are upgrading to N right now as if it is their
7133        //       first boot, as they do not have profile data.
7134        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7135
7136        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7137        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7138
7139        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7140            return;
7141        }
7142
7143        List<PackageParser.Package> pkgs;
7144        synchronized (mPackages) {
7145            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7146        }
7147
7148        final long startTime = System.nanoTime();
7149        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7150                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7151
7152        final int elapsedTimeSeconds =
7153                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7154
7155        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7156        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7157        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7158        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7159        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7160    }
7161
7162    /**
7163     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7164     * containing statistics about the invocation. The array consists of three elements,
7165     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7166     * and {@code numberOfPackagesFailed}.
7167     */
7168    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7169            String compilerFilter) {
7170
7171        int numberOfPackagesVisited = 0;
7172        int numberOfPackagesOptimized = 0;
7173        int numberOfPackagesSkipped = 0;
7174        int numberOfPackagesFailed = 0;
7175        final int numberOfPackagesToDexopt = pkgs.size();
7176
7177        for (PackageParser.Package pkg : pkgs) {
7178            numberOfPackagesVisited++;
7179
7180            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7181                if (DEBUG_DEXOPT) {
7182                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7183                }
7184                numberOfPackagesSkipped++;
7185                continue;
7186            }
7187
7188            if (DEBUG_DEXOPT) {
7189                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7190                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7191            }
7192
7193            if (showDialog) {
7194                try {
7195                    ActivityManagerNative.getDefault().showBootMessage(
7196                            mContext.getResources().getString(R.string.android_upgrading_apk,
7197                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7198                } catch (RemoteException e) {
7199                }
7200            }
7201
7202            // If the OTA updates a system app which was previously preopted to a non-preopted state
7203            // the app might end up being verified at runtime. That's because by default the apps
7204            // are verify-profile but for preopted apps there's no profile.
7205            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7206            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7207            // filter (by default interpret-only).
7208            // Note that at this stage unused apps are already filtered.
7209            if (isSystemApp(pkg) &&
7210                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7211                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7212                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7213            }
7214
7215            // checkProfiles is false to avoid merging profiles during boot which
7216            // might interfere with background compilation (b/28612421).
7217            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7218            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7219            // trade-off worth doing to save boot time work.
7220            int dexOptStatus = performDexOptTraced(pkg.packageName,
7221                    false /* checkProfiles */,
7222                    compilerFilter,
7223                    false /* force */);
7224            switch (dexOptStatus) {
7225                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7226                    numberOfPackagesOptimized++;
7227                    break;
7228                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7229                    numberOfPackagesSkipped++;
7230                    break;
7231                case PackageDexOptimizer.DEX_OPT_FAILED:
7232                    numberOfPackagesFailed++;
7233                    break;
7234                default:
7235                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7236                    break;
7237            }
7238        }
7239
7240        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7241                numberOfPackagesFailed };
7242    }
7243
7244    @Override
7245    public void notifyPackageUse(String packageName, int reason) {
7246        synchronized (mPackages) {
7247            PackageParser.Package p = mPackages.get(packageName);
7248            if (p == null) {
7249                return;
7250            }
7251            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7252        }
7253    }
7254
7255    // TODO: this is not used nor needed. Delete it.
7256    @Override
7257    public boolean performDexOptIfNeeded(String packageName) {
7258        int dexOptStatus = performDexOptTraced(packageName,
7259                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7260        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7261    }
7262
7263    @Override
7264    public boolean performDexOpt(String packageName,
7265            boolean checkProfiles, int compileReason, boolean force) {
7266        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7267                getCompilerFilterForReason(compileReason), force);
7268        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7269    }
7270
7271    @Override
7272    public boolean performDexOptMode(String packageName,
7273            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7274        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7275                targetCompilerFilter, force);
7276        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7277    }
7278
7279    private int performDexOptTraced(String packageName,
7280                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7281        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7282        try {
7283            return performDexOptInternal(packageName, checkProfiles,
7284                    targetCompilerFilter, force);
7285        } finally {
7286            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7287        }
7288    }
7289
7290    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7291    // if the package can now be considered up to date for the given filter.
7292    private int performDexOptInternal(String packageName,
7293                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7294        PackageParser.Package p;
7295        synchronized (mPackages) {
7296            p = mPackages.get(packageName);
7297            if (p == null) {
7298                // Package could not be found. Report failure.
7299                return PackageDexOptimizer.DEX_OPT_FAILED;
7300            }
7301            mPackageUsage.maybeWriteAsync(mPackages);
7302            mCompilerStats.maybeWriteAsync();
7303        }
7304        long callingId = Binder.clearCallingIdentity();
7305        try {
7306            synchronized (mInstallLock) {
7307                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7308                        targetCompilerFilter, force);
7309            }
7310        } finally {
7311            Binder.restoreCallingIdentity(callingId);
7312        }
7313    }
7314
7315    public ArraySet<String> getOptimizablePackages() {
7316        ArraySet<String> pkgs = new ArraySet<String>();
7317        synchronized (mPackages) {
7318            for (PackageParser.Package p : mPackages.values()) {
7319                if (PackageDexOptimizer.canOptimizePackage(p)) {
7320                    pkgs.add(p.packageName);
7321                }
7322            }
7323        }
7324        return pkgs;
7325    }
7326
7327    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7328            boolean checkProfiles, String targetCompilerFilter,
7329            boolean force) {
7330        // Select the dex optimizer based on the force parameter.
7331        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7332        //       allocate an object here.
7333        PackageDexOptimizer pdo = force
7334                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7335                : mPackageDexOptimizer;
7336
7337        // Optimize all dependencies first. Note: we ignore the return value and march on
7338        // on errors.
7339        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7340        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7341        if (!deps.isEmpty()) {
7342            for (PackageParser.Package depPackage : deps) {
7343                // TODO: Analyze and investigate if we (should) profile libraries.
7344                // Currently this will do a full compilation of the library by default.
7345                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7346                        false /* checkProfiles */,
7347                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7348                        getOrCreateCompilerPackageStats(depPackage));
7349            }
7350        }
7351        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7352                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7353    }
7354
7355    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7356        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7357            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7358            Set<String> collectedNames = new HashSet<>();
7359            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7360
7361            retValue.remove(p);
7362
7363            return retValue;
7364        } else {
7365            return Collections.emptyList();
7366        }
7367    }
7368
7369    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7370            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7371        if (!collectedNames.contains(p.packageName)) {
7372            collectedNames.add(p.packageName);
7373            collected.add(p);
7374
7375            if (p.usesLibraries != null) {
7376                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7377            }
7378            if (p.usesOptionalLibraries != null) {
7379                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7380                        collectedNames);
7381            }
7382        }
7383    }
7384
7385    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7386            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7387        for (String libName : libs) {
7388            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7389            if (libPkg != null) {
7390                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7391            }
7392        }
7393    }
7394
7395    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7396        synchronized (mPackages) {
7397            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7398            if (lib != null && lib.apk != null) {
7399                return mPackages.get(lib.apk);
7400            }
7401        }
7402        return null;
7403    }
7404
7405    public void shutdown() {
7406        mPackageUsage.writeNow(mPackages);
7407        mCompilerStats.writeNow();
7408    }
7409
7410    @Override
7411    public void dumpProfiles(String packageName) {
7412        PackageParser.Package pkg;
7413        synchronized (mPackages) {
7414            pkg = mPackages.get(packageName);
7415            if (pkg == null) {
7416                throw new IllegalArgumentException("Unknown package: " + packageName);
7417            }
7418        }
7419        /* Only the shell, root, or the app user should be able to dump profiles. */
7420        int callingUid = Binder.getCallingUid();
7421        if (callingUid != Process.SHELL_UID &&
7422            callingUid != Process.ROOT_UID &&
7423            callingUid != pkg.applicationInfo.uid) {
7424            throw new SecurityException("dumpProfiles");
7425        }
7426
7427        synchronized (mInstallLock) {
7428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7429            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7430            try {
7431                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7432                String gid = Integer.toString(sharedGid);
7433                String codePaths = TextUtils.join(";", allCodePaths);
7434                mInstaller.dumpProfiles(gid, packageName, codePaths);
7435            } catch (InstallerException e) {
7436                Slog.w(TAG, "Failed to dump profiles", e);
7437            }
7438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7439        }
7440    }
7441
7442    @Override
7443    public void forceDexOpt(String packageName) {
7444        enforceSystemOrRoot("forceDexOpt");
7445
7446        PackageParser.Package pkg;
7447        synchronized (mPackages) {
7448            pkg = mPackages.get(packageName);
7449            if (pkg == null) {
7450                throw new IllegalArgumentException("Unknown package: " + packageName);
7451            }
7452        }
7453
7454        synchronized (mInstallLock) {
7455            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7456
7457            // Whoever is calling forceDexOpt wants a fully compiled package.
7458            // Don't use profiles since that may cause compilation to be skipped.
7459            final int res = performDexOptInternalWithDependenciesLI(pkg,
7460                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7461                    true /* force */);
7462
7463            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7464            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7465                throw new IllegalStateException("Failed to dexopt: " + res);
7466            }
7467        }
7468    }
7469
7470    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7471        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7472            Slog.w(TAG, "Unable to update from " + oldPkg.name
7473                    + " to " + newPkg.packageName
7474                    + ": old package not in system partition");
7475            return false;
7476        } else if (mPackages.get(oldPkg.name) != null) {
7477            Slog.w(TAG, "Unable to update from " + oldPkg.name
7478                    + " to " + newPkg.packageName
7479                    + ": old package still exists");
7480            return false;
7481        }
7482        return true;
7483    }
7484
7485    void removeCodePathLI(File codePath) {
7486        if (codePath.isDirectory()) {
7487            try {
7488                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7489            } catch (InstallerException e) {
7490                Slog.w(TAG, "Failed to remove code path", e);
7491            }
7492        } else {
7493            codePath.delete();
7494        }
7495    }
7496
7497    private int[] resolveUserIds(int userId) {
7498        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7499    }
7500
7501    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7502        if (pkg == null) {
7503            Slog.wtf(TAG, "Package was null!", new Throwable());
7504            return;
7505        }
7506        clearAppDataLeafLIF(pkg, userId, flags);
7507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7508        for (int i = 0; i < childCount; i++) {
7509            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7510        }
7511    }
7512
7513    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7514        final PackageSetting ps;
7515        synchronized (mPackages) {
7516            ps = mSettings.mPackages.get(pkg.packageName);
7517        }
7518        for (int realUserId : resolveUserIds(userId)) {
7519            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7520            try {
7521                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7522                        ceDataInode);
7523            } catch (InstallerException e) {
7524                Slog.w(TAG, String.valueOf(e));
7525            }
7526        }
7527    }
7528
7529    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7530        if (pkg == null) {
7531            Slog.wtf(TAG, "Package was null!", new Throwable());
7532            return;
7533        }
7534        destroyAppDataLeafLIF(pkg, userId, flags);
7535        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7536        for (int i = 0; i < childCount; i++) {
7537            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7538        }
7539    }
7540
7541    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7542        final PackageSetting ps;
7543        synchronized (mPackages) {
7544            ps = mSettings.mPackages.get(pkg.packageName);
7545        }
7546        for (int realUserId : resolveUserIds(userId)) {
7547            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7548            try {
7549                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7550                        ceDataInode);
7551            } catch (InstallerException e) {
7552                Slog.w(TAG, String.valueOf(e));
7553            }
7554        }
7555    }
7556
7557    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7558        if (pkg == null) {
7559            Slog.wtf(TAG, "Package was null!", new Throwable());
7560            return;
7561        }
7562        destroyAppProfilesLeafLIF(pkg);
7563        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7564        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7565        for (int i = 0; i < childCount; i++) {
7566            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7567            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7568                    true /* removeBaseMarker */);
7569        }
7570    }
7571
7572    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7573            boolean removeBaseMarker) {
7574        if (pkg.isForwardLocked()) {
7575            return;
7576        }
7577
7578        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7579            try {
7580                path = PackageManagerServiceUtils.realpath(new File(path));
7581            } catch (IOException e) {
7582                // TODO: Should we return early here ?
7583                Slog.w(TAG, "Failed to get canonical path", e);
7584                continue;
7585            }
7586
7587            final String useMarker = path.replace('/', '@');
7588            for (int realUserId : resolveUserIds(userId)) {
7589                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7590                if (removeBaseMarker) {
7591                    File foreignUseMark = new File(profileDir, useMarker);
7592                    if (foreignUseMark.exists()) {
7593                        if (!foreignUseMark.delete()) {
7594                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7595                                    + pkg.packageName);
7596                        }
7597                    }
7598                }
7599
7600                File[] markers = profileDir.listFiles();
7601                if (markers != null) {
7602                    final String searchString = "@" + pkg.packageName + "@";
7603                    // We also delete all markers that contain the package name we're
7604                    // uninstalling. These are associated with secondary dex-files belonging
7605                    // to the package. Reconstructing the path of these dex files is messy
7606                    // in general.
7607                    for (File marker : markers) {
7608                        if (marker.getName().indexOf(searchString) > 0) {
7609                            if (!marker.delete()) {
7610                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7611                                    + pkg.packageName);
7612                            }
7613                        }
7614                    }
7615                }
7616            }
7617        }
7618    }
7619
7620    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7621        try {
7622            mInstaller.destroyAppProfiles(pkg.packageName);
7623        } catch (InstallerException e) {
7624            Slog.w(TAG, String.valueOf(e));
7625        }
7626    }
7627
7628    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7629        if (pkg == null) {
7630            Slog.wtf(TAG, "Package was null!", new Throwable());
7631            return;
7632        }
7633        clearAppProfilesLeafLIF(pkg);
7634        // We don't remove the base foreign use marker when clearing profiles because
7635        // we will rename it when the app is updated. Unlike the actual profile contents,
7636        // the foreign use marker is good across installs.
7637        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7638        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7639        for (int i = 0; i < childCount; i++) {
7640            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7641        }
7642    }
7643
7644    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7645        try {
7646            mInstaller.clearAppProfiles(pkg.packageName);
7647        } catch (InstallerException e) {
7648            Slog.w(TAG, String.valueOf(e));
7649        }
7650    }
7651
7652    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7653            long lastUpdateTime) {
7654        // Set parent install/update time
7655        PackageSetting ps = (PackageSetting) pkg.mExtras;
7656        if (ps != null) {
7657            ps.firstInstallTime = firstInstallTime;
7658            ps.lastUpdateTime = lastUpdateTime;
7659        }
7660        // Set children install/update time
7661        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7662        for (int i = 0; i < childCount; i++) {
7663            PackageParser.Package childPkg = pkg.childPackages.get(i);
7664            ps = (PackageSetting) childPkg.mExtras;
7665            if (ps != null) {
7666                ps.firstInstallTime = firstInstallTime;
7667                ps.lastUpdateTime = lastUpdateTime;
7668            }
7669        }
7670    }
7671
7672    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7673            PackageParser.Package changingLib) {
7674        if (file.path != null) {
7675            usesLibraryFiles.add(file.path);
7676            return;
7677        }
7678        PackageParser.Package p = mPackages.get(file.apk);
7679        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7680            // If we are doing this while in the middle of updating a library apk,
7681            // then we need to make sure to use that new apk for determining the
7682            // dependencies here.  (We haven't yet finished committing the new apk
7683            // to the package manager state.)
7684            if (p == null || p.packageName.equals(changingLib.packageName)) {
7685                p = changingLib;
7686            }
7687        }
7688        if (p != null) {
7689            usesLibraryFiles.addAll(p.getAllCodePaths());
7690        }
7691    }
7692
7693    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7694            PackageParser.Package changingLib) throws PackageManagerException {
7695        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7696            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7697            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7698            for (int i=0; i<N; i++) {
7699                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7700                if (file == null) {
7701                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7702                            "Package " + pkg.packageName + " requires unavailable shared library "
7703                            + pkg.usesLibraries.get(i) + "; failing!");
7704                }
7705                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7706            }
7707            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7708            for (int i=0; i<N; i++) {
7709                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7710                if (file == null) {
7711                    Slog.w(TAG, "Package " + pkg.packageName
7712                            + " desires unavailable shared library "
7713                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7714                } else {
7715                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7716                }
7717            }
7718            N = usesLibraryFiles.size();
7719            if (N > 0) {
7720                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7721            } else {
7722                pkg.usesLibraryFiles = null;
7723            }
7724        }
7725    }
7726
7727    private static boolean hasString(List<String> list, List<String> which) {
7728        if (list == null) {
7729            return false;
7730        }
7731        for (int i=list.size()-1; i>=0; i--) {
7732            for (int j=which.size()-1; j>=0; j--) {
7733                if (which.get(j).equals(list.get(i))) {
7734                    return true;
7735                }
7736            }
7737        }
7738        return false;
7739    }
7740
7741    private void updateAllSharedLibrariesLPw() {
7742        for (PackageParser.Package pkg : mPackages.values()) {
7743            try {
7744                updateSharedLibrariesLPw(pkg, null);
7745            } catch (PackageManagerException e) {
7746                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7747            }
7748        }
7749    }
7750
7751    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7752            PackageParser.Package changingPkg) {
7753        ArrayList<PackageParser.Package> res = null;
7754        for (PackageParser.Package pkg : mPackages.values()) {
7755            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7756                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7757                if (res == null) {
7758                    res = new ArrayList<PackageParser.Package>();
7759                }
7760                res.add(pkg);
7761                try {
7762                    updateSharedLibrariesLPw(pkg, changingPkg);
7763                } catch (PackageManagerException e) {
7764                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7765                }
7766            }
7767        }
7768        return res;
7769    }
7770
7771    /**
7772     * Derive the value of the {@code cpuAbiOverride} based on the provided
7773     * value and an optional stored value from the package settings.
7774     */
7775    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7776        String cpuAbiOverride = null;
7777
7778        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7779            cpuAbiOverride = null;
7780        } else if (abiOverride != null) {
7781            cpuAbiOverride = abiOverride;
7782        } else if (settings != null) {
7783            cpuAbiOverride = settings.cpuAbiOverrideString;
7784        }
7785
7786        return cpuAbiOverride;
7787    }
7788
7789    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7790            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7791                    throws PackageManagerException {
7792        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7793        // If the package has children and this is the first dive in the function
7794        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7795        // whether all packages (parent and children) would be successfully scanned
7796        // before the actual scan since scanning mutates internal state and we want
7797        // to atomically install the package and its children.
7798        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7799            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7800                scanFlags |= SCAN_CHECK_ONLY;
7801            }
7802        } else {
7803            scanFlags &= ~SCAN_CHECK_ONLY;
7804        }
7805
7806        final PackageParser.Package scannedPkg;
7807        try {
7808            // Scan the parent
7809            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7810            // Scan the children
7811            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7812            for (int i = 0; i < childCount; i++) {
7813                PackageParser.Package childPkg = pkg.childPackages.get(i);
7814                scanPackageLI(childPkg, policyFlags,
7815                        scanFlags, currentTime, user);
7816            }
7817        } finally {
7818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7819        }
7820
7821        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7822            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7823        }
7824
7825        return scannedPkg;
7826    }
7827
7828    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7829            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7830        boolean success = false;
7831        try {
7832            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7833                    currentTime, user);
7834            success = true;
7835            return res;
7836        } finally {
7837            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7838                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7839                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7840                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7841                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7842            }
7843        }
7844    }
7845
7846    /**
7847     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7848     */
7849    private static boolean apkHasCode(String fileName) {
7850        StrictJarFile jarFile = null;
7851        try {
7852            jarFile = new StrictJarFile(fileName,
7853                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7854            return jarFile.findEntry("classes.dex") != null;
7855        } catch (IOException ignore) {
7856        } finally {
7857            try {
7858                if (jarFile != null) {
7859                    jarFile.close();
7860                }
7861            } catch (IOException ignore) {}
7862        }
7863        return false;
7864    }
7865
7866    /**
7867     * Enforces code policy for the package. This ensures that if an APK has
7868     * declared hasCode="true" in its manifest that the APK actually contains
7869     * code.
7870     *
7871     * @throws PackageManagerException If bytecode could not be found when it should exist
7872     */
7873    private static void enforceCodePolicy(PackageParser.Package pkg)
7874            throws PackageManagerException {
7875        final boolean shouldHaveCode =
7876                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7877        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7878            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7879                    "Package " + pkg.baseCodePath + " code is missing");
7880        }
7881
7882        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7883            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7884                final boolean splitShouldHaveCode =
7885                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7886                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7887                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7888                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7889                }
7890            }
7891        }
7892    }
7893
7894    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7895            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7896            throws PackageManagerException {
7897        final File scanFile = new File(pkg.codePath);
7898        if (pkg.applicationInfo.getCodePath() == null ||
7899                pkg.applicationInfo.getResourcePath() == null) {
7900            // Bail out. The resource and code paths haven't been set.
7901            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7902                    "Code and resource paths haven't been set correctly");
7903        }
7904
7905        // Apply policy
7906        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7907            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7908            if (pkg.applicationInfo.isDirectBootAware()) {
7909                // we're direct boot aware; set for all components
7910                for (PackageParser.Service s : pkg.services) {
7911                    s.info.encryptionAware = s.info.directBootAware = true;
7912                }
7913                for (PackageParser.Provider p : pkg.providers) {
7914                    p.info.encryptionAware = p.info.directBootAware = true;
7915                }
7916                for (PackageParser.Activity a : pkg.activities) {
7917                    a.info.encryptionAware = a.info.directBootAware = true;
7918                }
7919                for (PackageParser.Activity r : pkg.receivers) {
7920                    r.info.encryptionAware = r.info.directBootAware = true;
7921                }
7922            }
7923        } else {
7924            // Only allow system apps to be flagged as core apps.
7925            pkg.coreApp = false;
7926            // clear flags not applicable to regular apps
7927            pkg.applicationInfo.privateFlags &=
7928                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7929            pkg.applicationInfo.privateFlags &=
7930                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7931        }
7932        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7933
7934        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7935            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7936        }
7937
7938        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7939            enforceCodePolicy(pkg);
7940        }
7941
7942        if (mCustomResolverComponentName != null &&
7943                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7944            setUpCustomResolverActivity(pkg);
7945        }
7946
7947        if (pkg.packageName.equals("android")) {
7948            synchronized (mPackages) {
7949                if (mAndroidApplication != null) {
7950                    Slog.w(TAG, "*************************************************");
7951                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7952                    Slog.w(TAG, " file=" + scanFile);
7953                    Slog.w(TAG, "*************************************************");
7954                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7955                            "Core android package being redefined.  Skipping.");
7956                }
7957
7958                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7959                    // Set up information for our fall-back user intent resolution activity.
7960                    mPlatformPackage = pkg;
7961                    pkg.mVersionCode = mSdkVersion;
7962                    mAndroidApplication = pkg.applicationInfo;
7963
7964                    if (!mResolverReplaced) {
7965                        mResolveActivity.applicationInfo = mAndroidApplication;
7966                        mResolveActivity.name = ResolverActivity.class.getName();
7967                        mResolveActivity.packageName = mAndroidApplication.packageName;
7968                        mResolveActivity.processName = "system:ui";
7969                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7970                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7971                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7972                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7973                        mResolveActivity.exported = true;
7974                        mResolveActivity.enabled = true;
7975                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7976                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7977                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7978                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7979                                | ActivityInfo.CONFIG_ORIENTATION
7980                                | ActivityInfo.CONFIG_KEYBOARD
7981                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7982                        mResolveInfo.activityInfo = mResolveActivity;
7983                        mResolveInfo.priority = 0;
7984                        mResolveInfo.preferredOrder = 0;
7985                        mResolveInfo.match = 0;
7986                        mResolveComponentName = new ComponentName(
7987                                mAndroidApplication.packageName, mResolveActivity.name);
7988                    }
7989                }
7990            }
7991        }
7992
7993        if (DEBUG_PACKAGE_SCANNING) {
7994            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7995                Log.d(TAG, "Scanning package " + pkg.packageName);
7996        }
7997
7998        synchronized (mPackages) {
7999            if (mPackages.containsKey(pkg.packageName)
8000                    || mSharedLibraries.containsKey(pkg.packageName)) {
8001                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8002                        "Application package " + pkg.packageName
8003                                + " already installed.  Skipping duplicate.");
8004            }
8005
8006            // If we're only installing presumed-existing packages, require that the
8007            // scanned APK is both already known and at the path previously established
8008            // for it.  Previously unknown packages we pick up normally, but if we have an
8009            // a priori expectation about this package's install presence, enforce it.
8010            // With a singular exception for new system packages. When an OTA contains
8011            // a new system package, we allow the codepath to change from a system location
8012            // to the user-installed location. If we don't allow this change, any newer,
8013            // user-installed version of the application will be ignored.
8014            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8015                if (mExpectingBetter.containsKey(pkg.packageName)) {
8016                    logCriticalInfo(Log.WARN,
8017                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8018                } else {
8019                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8020                    if (known != null) {
8021                        if (DEBUG_PACKAGE_SCANNING) {
8022                            Log.d(TAG, "Examining " + pkg.codePath
8023                                    + " and requiring known paths " + known.codePathString
8024                                    + " & " + known.resourcePathString);
8025                        }
8026                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8027                                || !pkg.applicationInfo.getResourcePath().equals(
8028                                known.resourcePathString)) {
8029                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8030                                    "Application package " + pkg.packageName
8031                                            + " found at " + pkg.applicationInfo.getCodePath()
8032                                            + " but expected at " + known.codePathString
8033                                            + "; ignoring.");
8034                        }
8035                    }
8036                }
8037            }
8038        }
8039
8040        // Initialize package source and resource directories
8041        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8042        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8043
8044        SharedUserSetting suid = null;
8045        PackageSetting pkgSetting = null;
8046
8047        if (!isSystemApp(pkg)) {
8048            // Only system apps can use these features.
8049            pkg.mOriginalPackages = null;
8050            pkg.mRealPackage = null;
8051            pkg.mAdoptPermissions = null;
8052        }
8053
8054        // Getting the package setting may have a side-effect, so if we
8055        // are only checking if scan would succeed, stash a copy of the
8056        // old setting to restore at the end.
8057        PackageSetting nonMutatedPs = null;
8058
8059        // writer
8060        synchronized (mPackages) {
8061            if (pkg.mSharedUserId != null) {
8062                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8063                if (suid == null) {
8064                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8065                            "Creating application package " + pkg.packageName
8066                            + " for shared user failed");
8067                }
8068                if (DEBUG_PACKAGE_SCANNING) {
8069                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8070                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8071                                + "): packages=" + suid.packages);
8072                }
8073            }
8074
8075            // Check if we are renaming from an original package name.
8076            PackageSetting origPackage = null;
8077            String realName = null;
8078            if (pkg.mOriginalPackages != null) {
8079                // This package may need to be renamed to a previously
8080                // installed name.  Let's check on that...
8081                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8082                if (pkg.mOriginalPackages.contains(renamed)) {
8083                    // This package had originally been installed as the
8084                    // original name, and we have already taken care of
8085                    // transitioning to the new one.  Just update the new
8086                    // one to continue using the old name.
8087                    realName = pkg.mRealPackage;
8088                    if (!pkg.packageName.equals(renamed)) {
8089                        // Callers into this function may have already taken
8090                        // care of renaming the package; only do it here if
8091                        // it is not already done.
8092                        pkg.setPackageName(renamed);
8093                    }
8094
8095                } else {
8096                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8097                        if ((origPackage = mSettings.peekPackageLPr(
8098                                pkg.mOriginalPackages.get(i))) != null) {
8099                            // We do have the package already installed under its
8100                            // original name...  should we use it?
8101                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8102                                // New package is not compatible with original.
8103                                origPackage = null;
8104                                continue;
8105                            } else if (origPackage.sharedUser != null) {
8106                                // Make sure uid is compatible between packages.
8107                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8108                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8109                                            + " to " + pkg.packageName + ": old uid "
8110                                            + origPackage.sharedUser.name
8111                                            + " differs from " + pkg.mSharedUserId);
8112                                    origPackage = null;
8113                                    continue;
8114                                }
8115                                // TODO: Add case when shared user id is added [b/28144775]
8116                            } else {
8117                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8118                                        + pkg.packageName + " to old name " + origPackage.name);
8119                            }
8120                            break;
8121                        }
8122                    }
8123                }
8124            }
8125
8126            if (mTransferedPackages.contains(pkg.packageName)) {
8127                Slog.w(TAG, "Package " + pkg.packageName
8128                        + " was transferred to another, but its .apk remains");
8129            }
8130
8131            // See comments in nonMutatedPs declaration
8132            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8133                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8134                if (foundPs != null) {
8135                    nonMutatedPs = new PackageSetting(foundPs);
8136                }
8137            }
8138
8139            // Just create the setting, don't add it yet. For already existing packages
8140            // the PkgSetting exists already and doesn't have to be created.
8141            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8142                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8143                    pkg.applicationInfo.primaryCpuAbi,
8144                    pkg.applicationInfo.secondaryCpuAbi,
8145                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8146                    user, false);
8147            if (pkgSetting == null) {
8148                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8149                        "Creating application package " + pkg.packageName + " failed");
8150            }
8151
8152            if (pkgSetting.origPackage != null) {
8153                // If we are first transitioning from an original package,
8154                // fix up the new package's name now.  We need to do this after
8155                // looking up the package under its new name, so getPackageLP
8156                // can take care of fiddling things correctly.
8157                pkg.setPackageName(origPackage.name);
8158
8159                // File a report about this.
8160                String msg = "New package " + pkgSetting.realName
8161                        + " renamed to replace old package " + pkgSetting.name;
8162                reportSettingsProblem(Log.WARN, msg);
8163
8164                // Make a note of it.
8165                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8166                    mTransferedPackages.add(origPackage.name);
8167                }
8168
8169                // No longer need to retain this.
8170                pkgSetting.origPackage = null;
8171            }
8172
8173            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8174                // Make a note of it.
8175                mTransferedPackages.add(pkg.packageName);
8176            }
8177
8178            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8179                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8180            }
8181
8182            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8183                // Check all shared libraries and map to their actual file path.
8184                // We only do this here for apps not on a system dir, because those
8185                // are the only ones that can fail an install due to this.  We
8186                // will take care of the system apps by updating all of their
8187                // library paths after the scan is done.
8188                updateSharedLibrariesLPw(pkg, null);
8189            }
8190
8191            if (mFoundPolicyFile) {
8192                SELinuxMMAC.assignSeinfoValue(pkg);
8193            }
8194
8195            pkg.applicationInfo.uid = pkgSetting.appId;
8196            pkg.mExtras = pkgSetting;
8197            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8198                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8199                    // We just determined the app is signed correctly, so bring
8200                    // over the latest parsed certs.
8201                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8202                } else {
8203                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8204                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8205                                "Package " + pkg.packageName + " upgrade keys do not match the "
8206                                + "previously installed version");
8207                    } else {
8208                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8209                        String msg = "System package " + pkg.packageName
8210                            + " signature changed; retaining data.";
8211                        reportSettingsProblem(Log.WARN, msg);
8212                    }
8213                }
8214            } else {
8215                try {
8216                    verifySignaturesLP(pkgSetting, pkg);
8217                    // We just determined the app is signed correctly, so bring
8218                    // over the latest parsed certs.
8219                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8220                } catch (PackageManagerException e) {
8221                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8222                        throw e;
8223                    }
8224                    // The signature has changed, but this package is in the system
8225                    // image...  let's recover!
8226                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8227                    // However...  if this package is part of a shared user, but it
8228                    // doesn't match the signature of the shared user, let's fail.
8229                    // What this means is that you can't change the signatures
8230                    // associated with an overall shared user, which doesn't seem all
8231                    // that unreasonable.
8232                    if (pkgSetting.sharedUser != null) {
8233                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8234                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8235                            throw new PackageManagerException(
8236                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8237                                            "Signature mismatch for shared user: "
8238                                            + pkgSetting.sharedUser);
8239                        }
8240                    }
8241                    // File a report about this.
8242                    String msg = "System package " + pkg.packageName
8243                        + " signature changed; retaining data.";
8244                    reportSettingsProblem(Log.WARN, msg);
8245                }
8246            }
8247            // Verify that this new package doesn't have any content providers
8248            // that conflict with existing packages.  Only do this if the
8249            // package isn't already installed, since we don't want to break
8250            // things that are installed.
8251            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8252                final int N = pkg.providers.size();
8253                int i;
8254                for (i=0; i<N; i++) {
8255                    PackageParser.Provider p = pkg.providers.get(i);
8256                    if (p.info.authority != null) {
8257                        String names[] = p.info.authority.split(";");
8258                        for (int j = 0; j < names.length; j++) {
8259                            if (mProvidersByAuthority.containsKey(names[j])) {
8260                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8261                                final String otherPackageName =
8262                                        ((other != null && other.getComponentName() != null) ?
8263                                                other.getComponentName().getPackageName() : "?");
8264                                throw new PackageManagerException(
8265                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8266                                                "Can't install because provider name " + names[j]
8267                                                + " (in package " + pkg.applicationInfo.packageName
8268                                                + ") is already used by " + otherPackageName);
8269                            }
8270                        }
8271                    }
8272                }
8273            }
8274
8275            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8276                // This package wants to adopt ownership of permissions from
8277                // another package.
8278                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8279                    final String origName = pkg.mAdoptPermissions.get(i);
8280                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8281                    if (orig != null) {
8282                        if (verifyPackageUpdateLPr(orig, pkg)) {
8283                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8284                                    + pkg.packageName);
8285                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8286                        }
8287                    }
8288                }
8289            }
8290        }
8291
8292        final String pkgName = pkg.packageName;
8293
8294        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8295        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8296        pkg.applicationInfo.processName = fixProcessName(
8297                pkg.applicationInfo.packageName,
8298                pkg.applicationInfo.processName,
8299                pkg.applicationInfo.uid);
8300
8301        if (pkg != mPlatformPackage) {
8302            // Get all of our default paths setup
8303            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8304        }
8305
8306        final String path = scanFile.getPath();
8307        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8308
8309        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8310            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8311
8312            // Some system apps still use directory structure for native libraries
8313            // in which case we might end up not detecting abi solely based on apk
8314            // structure. Try to detect abi based on directory structure.
8315            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8316                    pkg.applicationInfo.primaryCpuAbi == null) {
8317                setBundledAppAbisAndRoots(pkg, pkgSetting);
8318                setNativeLibraryPaths(pkg);
8319            }
8320
8321        } else {
8322            if ((scanFlags & SCAN_MOVE) != 0) {
8323                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8324                // but we already have this packages package info in the PackageSetting. We just
8325                // use that and derive the native library path based on the new codepath.
8326                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8327                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8328            }
8329
8330            // Set native library paths again. For moves, the path will be updated based on the
8331            // ABIs we've determined above. For non-moves, the path will be updated based on the
8332            // ABIs we determined during compilation, but the path will depend on the final
8333            // package path (after the rename away from the stage path).
8334            setNativeLibraryPaths(pkg);
8335        }
8336
8337        // This is a special case for the "system" package, where the ABI is
8338        // dictated by the zygote configuration (and init.rc). We should keep track
8339        // of this ABI so that we can deal with "normal" applications that run under
8340        // the same UID correctly.
8341        if (mPlatformPackage == pkg) {
8342            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8343                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8344        }
8345
8346        // If there's a mismatch between the abi-override in the package setting
8347        // and the abiOverride specified for the install. Warn about this because we
8348        // would've already compiled the app without taking the package setting into
8349        // account.
8350        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8351            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8352                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8353                        " for package " + pkg.packageName);
8354            }
8355        }
8356
8357        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8358        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8359        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8360
8361        // Copy the derived override back to the parsed package, so that we can
8362        // update the package settings accordingly.
8363        pkg.cpuAbiOverride = cpuAbiOverride;
8364
8365        if (DEBUG_ABI_SELECTION) {
8366            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8367                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8368                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8369        }
8370
8371        // Push the derived path down into PackageSettings so we know what to
8372        // clean up at uninstall time.
8373        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8374
8375        if (DEBUG_ABI_SELECTION) {
8376            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8377                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8378                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8379        }
8380
8381        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8382            // We don't do this here during boot because we can do it all
8383            // at once after scanning all existing packages.
8384            //
8385            // We also do this *before* we perform dexopt on this package, so that
8386            // we can avoid redundant dexopts, and also to make sure we've got the
8387            // code and package path correct.
8388            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8389                    pkg, true /* boot complete */);
8390        }
8391
8392        if (mFactoryTest && pkg.requestedPermissions.contains(
8393                android.Manifest.permission.FACTORY_TEST)) {
8394            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8395        }
8396
8397        if (isSystemApp(pkg)) {
8398            pkgSetting.isOrphaned = true;
8399        }
8400
8401        ArrayList<PackageParser.Package> clientLibPkgs = null;
8402
8403        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8404            if (nonMutatedPs != null) {
8405                synchronized (mPackages) {
8406                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8407                }
8408            }
8409            return pkg;
8410        }
8411
8412        // Only privileged apps and updated privileged apps can add child packages.
8413        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8414            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8415                throw new PackageManagerException("Only privileged apps and updated "
8416                        + "privileged apps can add child packages. Ignoring package "
8417                        + pkg.packageName);
8418            }
8419            final int childCount = pkg.childPackages.size();
8420            for (int i = 0; i < childCount; i++) {
8421                PackageParser.Package childPkg = pkg.childPackages.get(i);
8422                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8423                        childPkg.packageName)) {
8424                    throw new PackageManagerException("Cannot override a child package of "
8425                            + "another disabled system app. Ignoring package " + pkg.packageName);
8426                }
8427            }
8428        }
8429
8430        // writer
8431        synchronized (mPackages) {
8432            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8433                // Only system apps can add new shared libraries.
8434                if (pkg.libraryNames != null) {
8435                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8436                        String name = pkg.libraryNames.get(i);
8437                        boolean allowed = false;
8438                        if (pkg.isUpdatedSystemApp()) {
8439                            // New library entries can only be added through the
8440                            // system image.  This is important to get rid of a lot
8441                            // of nasty edge cases: for example if we allowed a non-
8442                            // system update of the app to add a library, then uninstalling
8443                            // the update would make the library go away, and assumptions
8444                            // we made such as through app install filtering would now
8445                            // have allowed apps on the device which aren't compatible
8446                            // with it.  Better to just have the restriction here, be
8447                            // conservative, and create many fewer cases that can negatively
8448                            // impact the user experience.
8449                            final PackageSetting sysPs = mSettings
8450                                    .getDisabledSystemPkgLPr(pkg.packageName);
8451                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8452                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8453                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8454                                        allowed = true;
8455                                        break;
8456                                    }
8457                                }
8458                            }
8459                        } else {
8460                            allowed = true;
8461                        }
8462                        if (allowed) {
8463                            if (!mSharedLibraries.containsKey(name)) {
8464                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8465                            } else if (!name.equals(pkg.packageName)) {
8466                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8467                                        + name + " already exists; skipping");
8468                            }
8469                        } else {
8470                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8471                                    + name + " that is not declared on system image; skipping");
8472                        }
8473                    }
8474                    if ((scanFlags & SCAN_BOOTING) == 0) {
8475                        // If we are not booting, we need to update any applications
8476                        // that are clients of our shared library.  If we are booting,
8477                        // this will all be done once the scan is complete.
8478                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8479                    }
8480                }
8481            }
8482        }
8483
8484        if ((scanFlags & SCAN_BOOTING) != 0) {
8485            // No apps can run during boot scan, so they don't need to be frozen
8486        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8487            // Caller asked to not kill app, so it's probably not frozen
8488        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8489            // Caller asked us to ignore frozen check for some reason; they
8490            // probably didn't know the package name
8491        } else {
8492            // We're doing major surgery on this package, so it better be frozen
8493            // right now to keep it from launching
8494            checkPackageFrozen(pkgName);
8495        }
8496
8497        // Also need to kill any apps that are dependent on the library.
8498        if (clientLibPkgs != null) {
8499            for (int i=0; i<clientLibPkgs.size(); i++) {
8500                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8501                killApplication(clientPkg.applicationInfo.packageName,
8502                        clientPkg.applicationInfo.uid, "update lib");
8503            }
8504        }
8505
8506        // Make sure we're not adding any bogus keyset info
8507        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8508        ksms.assertScannedPackageValid(pkg);
8509
8510        // writer
8511        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8512
8513        boolean createIdmapFailed = false;
8514        synchronized (mPackages) {
8515            // We don't expect installation to fail beyond this point
8516
8517            if (pkgSetting.pkg != null) {
8518                // Note that |user| might be null during the initial boot scan. If a codePath
8519                // for an app has changed during a boot scan, it's due to an app update that's
8520                // part of the system partition and marker changes must be applied to all users.
8521                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8522                    (user != null) ? user : UserHandle.ALL);
8523            }
8524
8525            // Add the new setting to mSettings
8526            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8527            // Add the new setting to mPackages
8528            mPackages.put(pkg.applicationInfo.packageName, pkg);
8529            // Make sure we don't accidentally delete its data.
8530            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8531            while (iter.hasNext()) {
8532                PackageCleanItem item = iter.next();
8533                if (pkgName.equals(item.packageName)) {
8534                    iter.remove();
8535                }
8536            }
8537
8538            // Take care of first install / last update times.
8539            if (currentTime != 0) {
8540                if (pkgSetting.firstInstallTime == 0) {
8541                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8542                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8543                    pkgSetting.lastUpdateTime = currentTime;
8544                }
8545            } else if (pkgSetting.firstInstallTime == 0) {
8546                // We need *something*.  Take time time stamp of the file.
8547                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8548            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8549                if (scanFileTime != pkgSetting.timeStamp) {
8550                    // A package on the system image has changed; consider this
8551                    // to be an update.
8552                    pkgSetting.lastUpdateTime = scanFileTime;
8553                }
8554            }
8555
8556            // Add the package's KeySets to the global KeySetManagerService
8557            ksms.addScannedPackageLPw(pkg);
8558
8559            int N = pkg.providers.size();
8560            StringBuilder r = null;
8561            int i;
8562            for (i=0; i<N; i++) {
8563                PackageParser.Provider p = pkg.providers.get(i);
8564                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8565                        p.info.processName, pkg.applicationInfo.uid);
8566                mProviders.addProvider(p);
8567                p.syncable = p.info.isSyncable;
8568                if (p.info.authority != null) {
8569                    String names[] = p.info.authority.split(";");
8570                    p.info.authority = null;
8571                    for (int j = 0; j < names.length; j++) {
8572                        if (j == 1 && p.syncable) {
8573                            // We only want the first authority for a provider to possibly be
8574                            // syncable, so if we already added this provider using a different
8575                            // authority clear the syncable flag. We copy the provider before
8576                            // changing it because the mProviders object contains a reference
8577                            // to a provider that we don't want to change.
8578                            // Only do this for the second authority since the resulting provider
8579                            // object can be the same for all future authorities for this provider.
8580                            p = new PackageParser.Provider(p);
8581                            p.syncable = false;
8582                        }
8583                        if (!mProvidersByAuthority.containsKey(names[j])) {
8584                            mProvidersByAuthority.put(names[j], p);
8585                            if (p.info.authority == null) {
8586                                p.info.authority = names[j];
8587                            } else {
8588                                p.info.authority = p.info.authority + ";" + names[j];
8589                            }
8590                            if (DEBUG_PACKAGE_SCANNING) {
8591                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8592                                    Log.d(TAG, "Registered content provider: " + names[j]
8593                                            + ", className = " + p.info.name + ", isSyncable = "
8594                                            + p.info.isSyncable);
8595                            }
8596                        } else {
8597                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8598                            Slog.w(TAG, "Skipping provider name " + names[j] +
8599                                    " (in package " + pkg.applicationInfo.packageName +
8600                                    "): name already used by "
8601                                    + ((other != null && other.getComponentName() != null)
8602                                            ? other.getComponentName().getPackageName() : "?"));
8603                        }
8604                    }
8605                }
8606                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8607                    if (r == null) {
8608                        r = new StringBuilder(256);
8609                    } else {
8610                        r.append(' ');
8611                    }
8612                    r.append(p.info.name);
8613                }
8614            }
8615            if (r != null) {
8616                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8617            }
8618
8619            N = pkg.services.size();
8620            r = null;
8621            for (i=0; i<N; i++) {
8622                PackageParser.Service s = pkg.services.get(i);
8623                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8624                        s.info.processName, pkg.applicationInfo.uid);
8625                mServices.addService(s);
8626                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8627                    if (r == null) {
8628                        r = new StringBuilder(256);
8629                    } else {
8630                        r.append(' ');
8631                    }
8632                    r.append(s.info.name);
8633                }
8634            }
8635            if (r != null) {
8636                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8637            }
8638
8639            N = pkg.receivers.size();
8640            r = null;
8641            for (i=0; i<N; i++) {
8642                PackageParser.Activity a = pkg.receivers.get(i);
8643                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8644                        a.info.processName, pkg.applicationInfo.uid);
8645                mReceivers.addActivity(a, "receiver");
8646                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8647                    if (r == null) {
8648                        r = new StringBuilder(256);
8649                    } else {
8650                        r.append(' ');
8651                    }
8652                    r.append(a.info.name);
8653                }
8654            }
8655            if (r != null) {
8656                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8657            }
8658
8659            N = pkg.activities.size();
8660            r = null;
8661            for (i=0; i<N; i++) {
8662                PackageParser.Activity a = pkg.activities.get(i);
8663                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8664                        a.info.processName, pkg.applicationInfo.uid);
8665                mActivities.addActivity(a, "activity");
8666                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8667                    if (r == null) {
8668                        r = new StringBuilder(256);
8669                    } else {
8670                        r.append(' ');
8671                    }
8672                    r.append(a.info.name);
8673                }
8674            }
8675            if (r != null) {
8676                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8677            }
8678
8679            N = pkg.permissionGroups.size();
8680            r = null;
8681            for (i=0; i<N; i++) {
8682                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8683                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8684                final String curPackageName = cur == null ? null : cur.info.packageName;
8685                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8686                if (cur == null || isPackageUpdate) {
8687                    mPermissionGroups.put(pg.info.name, pg);
8688                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8689                        if (r == null) {
8690                            r = new StringBuilder(256);
8691                        } else {
8692                            r.append(' ');
8693                        }
8694                        if (isPackageUpdate) {
8695                            r.append("UPD:");
8696                        }
8697                        r.append(pg.info.name);
8698                    }
8699                } else {
8700                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8701                            + pg.info.packageName + " ignored: original from "
8702                            + cur.info.packageName);
8703                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8704                        if (r == null) {
8705                            r = new StringBuilder(256);
8706                        } else {
8707                            r.append(' ');
8708                        }
8709                        r.append("DUP:");
8710                        r.append(pg.info.name);
8711                    }
8712                }
8713            }
8714            if (r != null) {
8715                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8716            }
8717
8718            N = pkg.permissions.size();
8719            r = null;
8720            for (i=0; i<N; i++) {
8721                PackageParser.Permission p = pkg.permissions.get(i);
8722
8723                // Assume by default that we did not install this permission into the system.
8724                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8725
8726                // Now that permission groups have a special meaning, we ignore permission
8727                // groups for legacy apps to prevent unexpected behavior. In particular,
8728                // permissions for one app being granted to someone just becase they happen
8729                // to be in a group defined by another app (before this had no implications).
8730                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8731                    p.group = mPermissionGroups.get(p.info.group);
8732                    // Warn for a permission in an unknown group.
8733                    if (p.info.group != null && p.group == null) {
8734                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8735                                + p.info.packageName + " in an unknown group " + p.info.group);
8736                    }
8737                }
8738
8739                ArrayMap<String, BasePermission> permissionMap =
8740                        p.tree ? mSettings.mPermissionTrees
8741                                : mSettings.mPermissions;
8742                BasePermission bp = permissionMap.get(p.info.name);
8743
8744                // Allow system apps to redefine non-system permissions
8745                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8746                    final boolean currentOwnerIsSystem = (bp.perm != null
8747                            && isSystemApp(bp.perm.owner));
8748                    if (isSystemApp(p.owner)) {
8749                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8750                            // It's a built-in permission and no owner, take ownership now
8751                            bp.packageSetting = pkgSetting;
8752                            bp.perm = p;
8753                            bp.uid = pkg.applicationInfo.uid;
8754                            bp.sourcePackage = p.info.packageName;
8755                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8756                        } else if (!currentOwnerIsSystem) {
8757                            String msg = "New decl " + p.owner + " of permission  "
8758                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8759                            reportSettingsProblem(Log.WARN, msg);
8760                            bp = null;
8761                        }
8762                    }
8763                }
8764
8765                if (bp == null) {
8766                    bp = new BasePermission(p.info.name, p.info.packageName,
8767                            BasePermission.TYPE_NORMAL);
8768                    permissionMap.put(p.info.name, bp);
8769                }
8770
8771                if (bp.perm == null) {
8772                    if (bp.sourcePackage == null
8773                            || bp.sourcePackage.equals(p.info.packageName)) {
8774                        BasePermission tree = findPermissionTreeLP(p.info.name);
8775                        if (tree == null
8776                                || tree.sourcePackage.equals(p.info.packageName)) {
8777                            bp.packageSetting = pkgSetting;
8778                            bp.perm = p;
8779                            bp.uid = pkg.applicationInfo.uid;
8780                            bp.sourcePackage = p.info.packageName;
8781                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8782                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8783                                if (r == null) {
8784                                    r = new StringBuilder(256);
8785                                } else {
8786                                    r.append(' ');
8787                                }
8788                                r.append(p.info.name);
8789                            }
8790                        } else {
8791                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8792                                    + p.info.packageName + " ignored: base tree "
8793                                    + tree.name + " is from package "
8794                                    + tree.sourcePackage);
8795                        }
8796                    } else {
8797                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8798                                + p.info.packageName + " ignored: original from "
8799                                + bp.sourcePackage);
8800                    }
8801                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8802                    if (r == null) {
8803                        r = new StringBuilder(256);
8804                    } else {
8805                        r.append(' ');
8806                    }
8807                    r.append("DUP:");
8808                    r.append(p.info.name);
8809                }
8810                if (bp.perm == p) {
8811                    bp.protectionLevel = p.info.protectionLevel;
8812                }
8813            }
8814
8815            if (r != null) {
8816                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8817            }
8818
8819            N = pkg.instrumentation.size();
8820            r = null;
8821            for (i=0; i<N; i++) {
8822                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8823                a.info.packageName = pkg.applicationInfo.packageName;
8824                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8825                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8826                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8827                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8828                a.info.dataDir = pkg.applicationInfo.dataDir;
8829                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8830                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8831
8832                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8833                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8834                mInstrumentation.put(a.getComponentName(), a);
8835                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8836                    if (r == null) {
8837                        r = new StringBuilder(256);
8838                    } else {
8839                        r.append(' ');
8840                    }
8841                    r.append(a.info.name);
8842                }
8843            }
8844            if (r != null) {
8845                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8846            }
8847
8848            if (pkg.protectedBroadcasts != null) {
8849                N = pkg.protectedBroadcasts.size();
8850                for (i=0; i<N; i++) {
8851                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8852                }
8853            }
8854
8855            pkgSetting.setTimeStamp(scanFileTime);
8856
8857            // Create idmap files for pairs of (packages, overlay packages).
8858            // Note: "android", ie framework-res.apk, is handled by native layers.
8859            if (pkg.mOverlayTarget != null) {
8860                // This is an overlay package.
8861                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8862                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8863                        mOverlays.put(pkg.mOverlayTarget,
8864                                new ArrayMap<String, PackageParser.Package>());
8865                    }
8866                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8867                    map.put(pkg.packageName, pkg);
8868                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8869                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8870                        createIdmapFailed = true;
8871                    }
8872                }
8873            } else if (mOverlays.containsKey(pkg.packageName) &&
8874                    !pkg.packageName.equals("android")) {
8875                // This is a regular package, with one or more known overlay packages.
8876                createIdmapsForPackageLI(pkg);
8877            }
8878        }
8879
8880        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8881
8882        if (createIdmapFailed) {
8883            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8884                    "scanPackageLI failed to createIdmap");
8885        }
8886        return pkg;
8887    }
8888
8889    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8890            PackageParser.Package update, UserHandle user) {
8891        if (existing.applicationInfo == null || update.applicationInfo == null) {
8892            // This isn't due to an app installation.
8893            return;
8894        }
8895
8896        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8897        final File newCodePath = new File(update.applicationInfo.getCodePath());
8898
8899        // The codePath hasn't changed, so there's nothing for us to do.
8900        if (Objects.equals(oldCodePath, newCodePath)) {
8901            return;
8902        }
8903
8904        File canonicalNewCodePath;
8905        try {
8906            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8907        } catch (IOException e) {
8908            Slog.w(TAG, "Failed to get canonical path.", e);
8909            return;
8910        }
8911
8912        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8913        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8914        // that the last component of the path (i.e, the name) doesn't need canonicalization
8915        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8916        // but may change in the future. Hopefully this function won't exist at that point.
8917        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8918                oldCodePath.getName());
8919
8920        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8921        // with "@".
8922        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8923        if (!oldMarkerPrefix.endsWith("@")) {
8924            oldMarkerPrefix += "@";
8925        }
8926        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8927        if (!newMarkerPrefix.endsWith("@")) {
8928            newMarkerPrefix += "@";
8929        }
8930
8931        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8932        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8933        for (String updatedPath : updatedPaths) {
8934            String updatedPathName = new File(updatedPath).getName();
8935            markerSuffixes.add(updatedPathName.replace('/', '@'));
8936        }
8937
8938        for (int userId : resolveUserIds(user.getIdentifier())) {
8939            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8940
8941            for (String markerSuffix : markerSuffixes) {
8942                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8943                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8944                if (oldForeignUseMark.exists()) {
8945                    try {
8946                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8947                                newForeignUseMark.getAbsolutePath());
8948                    } catch (ErrnoException e) {
8949                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8950                        oldForeignUseMark.delete();
8951                    }
8952                }
8953            }
8954        }
8955    }
8956
8957    /**
8958     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8959     * is derived purely on the basis of the contents of {@code scanFile} and
8960     * {@code cpuAbiOverride}.
8961     *
8962     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8963     */
8964    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8965                                 String cpuAbiOverride, boolean extractLibs)
8966            throws PackageManagerException {
8967        // TODO: We can probably be smarter about this stuff. For installed apps,
8968        // we can calculate this information at install time once and for all. For
8969        // system apps, we can probably assume that this information doesn't change
8970        // after the first boot scan. As things stand, we do lots of unnecessary work.
8971
8972        // Give ourselves some initial paths; we'll come back for another
8973        // pass once we've determined ABI below.
8974        setNativeLibraryPaths(pkg);
8975
8976        // We would never need to extract libs for forward-locked and external packages,
8977        // since the container service will do it for us. We shouldn't attempt to
8978        // extract libs from system app when it was not updated.
8979        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8980                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8981            extractLibs = false;
8982        }
8983
8984        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8985        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8986
8987        NativeLibraryHelper.Handle handle = null;
8988        try {
8989            handle = NativeLibraryHelper.Handle.create(pkg);
8990            // TODO(multiArch): This can be null for apps that didn't go through the
8991            // usual installation process. We can calculate it again, like we
8992            // do during install time.
8993            //
8994            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8995            // unnecessary.
8996            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8997
8998            // Null out the abis so that they can be recalculated.
8999            pkg.applicationInfo.primaryCpuAbi = null;
9000            pkg.applicationInfo.secondaryCpuAbi = null;
9001            if (isMultiArch(pkg.applicationInfo)) {
9002                // Warn if we've set an abiOverride for multi-lib packages..
9003                // By definition, we need to copy both 32 and 64 bit libraries for
9004                // such packages.
9005                if (pkg.cpuAbiOverride != null
9006                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9007                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9008                }
9009
9010                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9011                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9012                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9013                    if (extractLibs) {
9014                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9015                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9016                                useIsaSpecificSubdirs);
9017                    } else {
9018                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9019                    }
9020                }
9021
9022                maybeThrowExceptionForMultiArchCopy(
9023                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9024
9025                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9026                    if (extractLibs) {
9027                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9028                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9029                                useIsaSpecificSubdirs);
9030                    } else {
9031                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9032                    }
9033                }
9034
9035                maybeThrowExceptionForMultiArchCopy(
9036                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9037
9038                if (abi64 >= 0) {
9039                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9040                }
9041
9042                if (abi32 >= 0) {
9043                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9044                    if (abi64 >= 0) {
9045                        if (pkg.use32bitAbi) {
9046                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9047                            pkg.applicationInfo.primaryCpuAbi = abi;
9048                        } else {
9049                            pkg.applicationInfo.secondaryCpuAbi = abi;
9050                        }
9051                    } else {
9052                        pkg.applicationInfo.primaryCpuAbi = abi;
9053                    }
9054                }
9055
9056            } else {
9057                String[] abiList = (cpuAbiOverride != null) ?
9058                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9059
9060                // Enable gross and lame hacks for apps that are built with old
9061                // SDK tools. We must scan their APKs for renderscript bitcode and
9062                // not launch them if it's present. Don't bother checking on devices
9063                // that don't have 64 bit support.
9064                boolean needsRenderScriptOverride = false;
9065                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9066                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9067                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9068                    needsRenderScriptOverride = true;
9069                }
9070
9071                final int copyRet;
9072                if (extractLibs) {
9073                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9074                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9075                } else {
9076                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9077                }
9078
9079                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9080                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9081                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9082                }
9083
9084                if (copyRet >= 0) {
9085                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9086                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9087                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9088                } else if (needsRenderScriptOverride) {
9089                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9090                }
9091            }
9092        } catch (IOException ioe) {
9093            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9094        } finally {
9095            IoUtils.closeQuietly(handle);
9096        }
9097
9098        // Now that we've calculated the ABIs and determined if it's an internal app,
9099        // we will go ahead and populate the nativeLibraryPath.
9100        setNativeLibraryPaths(pkg);
9101    }
9102
9103    /**
9104     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9105     * i.e, so that all packages can be run inside a single process if required.
9106     *
9107     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9108     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9109     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9110     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9111     * updating a package that belongs to a shared user.
9112     *
9113     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9114     * adds unnecessary complexity.
9115     */
9116    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9117            PackageParser.Package scannedPackage, boolean bootComplete) {
9118        String requiredInstructionSet = null;
9119        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9120            requiredInstructionSet = VMRuntime.getInstructionSet(
9121                     scannedPackage.applicationInfo.primaryCpuAbi);
9122        }
9123
9124        PackageSetting requirer = null;
9125        for (PackageSetting ps : packagesForUser) {
9126            // If packagesForUser contains scannedPackage, we skip it. This will happen
9127            // when scannedPackage is an update of an existing package. Without this check,
9128            // we will never be able to change the ABI of any package belonging to a shared
9129            // user, even if it's compatible with other packages.
9130            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9131                if (ps.primaryCpuAbiString == null) {
9132                    continue;
9133                }
9134
9135                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9136                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9137                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9138                    // this but there's not much we can do.
9139                    String errorMessage = "Instruction set mismatch, "
9140                            + ((requirer == null) ? "[caller]" : requirer)
9141                            + " requires " + requiredInstructionSet + " whereas " + ps
9142                            + " requires " + instructionSet;
9143                    Slog.w(TAG, errorMessage);
9144                }
9145
9146                if (requiredInstructionSet == null) {
9147                    requiredInstructionSet = instructionSet;
9148                    requirer = ps;
9149                }
9150            }
9151        }
9152
9153        if (requiredInstructionSet != null) {
9154            String adjustedAbi;
9155            if (requirer != null) {
9156                // requirer != null implies that either scannedPackage was null or that scannedPackage
9157                // did not require an ABI, in which case we have to adjust scannedPackage to match
9158                // the ABI of the set (which is the same as requirer's ABI)
9159                adjustedAbi = requirer.primaryCpuAbiString;
9160                if (scannedPackage != null) {
9161                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9162                }
9163            } else {
9164                // requirer == null implies that we're updating all ABIs in the set to
9165                // match scannedPackage.
9166                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9167            }
9168
9169            for (PackageSetting ps : packagesForUser) {
9170                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9171                    if (ps.primaryCpuAbiString != null) {
9172                        continue;
9173                    }
9174
9175                    ps.primaryCpuAbiString = adjustedAbi;
9176                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9177                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9178                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9179                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9180                                + " (requirer="
9181                                + (requirer == null ? "null" : requirer.pkg.packageName)
9182                                + ", scannedPackage="
9183                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9184                                + ")");
9185                        try {
9186                            mInstaller.rmdex(ps.codePathString,
9187                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9188                        } catch (InstallerException ignored) {
9189                        }
9190                    }
9191                }
9192            }
9193        }
9194    }
9195
9196    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9197        synchronized (mPackages) {
9198            mResolverReplaced = true;
9199            // Set up information for custom user intent resolution activity.
9200            mResolveActivity.applicationInfo = pkg.applicationInfo;
9201            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9202            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9203            mResolveActivity.processName = pkg.applicationInfo.packageName;
9204            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9205            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9206                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9207            mResolveActivity.theme = 0;
9208            mResolveActivity.exported = true;
9209            mResolveActivity.enabled = true;
9210            mResolveInfo.activityInfo = mResolveActivity;
9211            mResolveInfo.priority = 0;
9212            mResolveInfo.preferredOrder = 0;
9213            mResolveInfo.match = 0;
9214            mResolveComponentName = mCustomResolverComponentName;
9215            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9216                    mResolveComponentName);
9217        }
9218    }
9219
9220    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9221        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9222
9223        // Set up information for ephemeral installer activity
9224        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9225        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9226        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9227        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9228        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9229        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9230                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9231        mEphemeralInstallerActivity.theme = 0;
9232        mEphemeralInstallerActivity.exported = true;
9233        mEphemeralInstallerActivity.enabled = true;
9234        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9235        mEphemeralInstallerInfo.priority = 0;
9236        mEphemeralInstallerInfo.preferredOrder = 0;
9237        mEphemeralInstallerInfo.match = 0;
9238
9239        if (DEBUG_EPHEMERAL) {
9240            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9241        }
9242    }
9243
9244    private static String calculateBundledApkRoot(final String codePathString) {
9245        final File codePath = new File(codePathString);
9246        final File codeRoot;
9247        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9248            codeRoot = Environment.getRootDirectory();
9249        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9250            codeRoot = Environment.getOemDirectory();
9251        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9252            codeRoot = Environment.getVendorDirectory();
9253        } else {
9254            // Unrecognized code path; take its top real segment as the apk root:
9255            // e.g. /something/app/blah.apk => /something
9256            try {
9257                File f = codePath.getCanonicalFile();
9258                File parent = f.getParentFile();    // non-null because codePath is a file
9259                File tmp;
9260                while ((tmp = parent.getParentFile()) != null) {
9261                    f = parent;
9262                    parent = tmp;
9263                }
9264                codeRoot = f;
9265                Slog.w(TAG, "Unrecognized code path "
9266                        + codePath + " - using " + codeRoot);
9267            } catch (IOException e) {
9268                // Can't canonicalize the code path -- shenanigans?
9269                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9270                return Environment.getRootDirectory().getPath();
9271            }
9272        }
9273        return codeRoot.getPath();
9274    }
9275
9276    /**
9277     * Derive and set the location of native libraries for the given package,
9278     * which varies depending on where and how the package was installed.
9279     */
9280    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9281        final ApplicationInfo info = pkg.applicationInfo;
9282        final String codePath = pkg.codePath;
9283        final File codeFile = new File(codePath);
9284        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9285        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9286
9287        info.nativeLibraryRootDir = null;
9288        info.nativeLibraryRootRequiresIsa = false;
9289        info.nativeLibraryDir = null;
9290        info.secondaryNativeLibraryDir = null;
9291
9292        if (isApkFile(codeFile)) {
9293            // Monolithic install
9294            if (bundledApp) {
9295                // If "/system/lib64/apkname" exists, assume that is the per-package
9296                // native library directory to use; otherwise use "/system/lib/apkname".
9297                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9298                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9299                        getPrimaryInstructionSet(info));
9300
9301                // This is a bundled system app so choose the path based on the ABI.
9302                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9303                // is just the default path.
9304                final String apkName = deriveCodePathName(codePath);
9305                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9306                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9307                        apkName).getAbsolutePath();
9308
9309                if (info.secondaryCpuAbi != null) {
9310                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9311                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9312                            secondaryLibDir, apkName).getAbsolutePath();
9313                }
9314            } else if (asecApp) {
9315                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9316                        .getAbsolutePath();
9317            } else {
9318                final String apkName = deriveCodePathName(codePath);
9319                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9320                        .getAbsolutePath();
9321            }
9322
9323            info.nativeLibraryRootRequiresIsa = false;
9324            info.nativeLibraryDir = info.nativeLibraryRootDir;
9325        } else {
9326            // Cluster install
9327            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9328            info.nativeLibraryRootRequiresIsa = true;
9329
9330            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9331                    getPrimaryInstructionSet(info)).getAbsolutePath();
9332
9333            if (info.secondaryCpuAbi != null) {
9334                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9335                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9336            }
9337        }
9338    }
9339
9340    /**
9341     * Calculate the abis and roots for a bundled app. These can uniquely
9342     * be determined from the contents of the system partition, i.e whether
9343     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9344     * of this information, and instead assume that the system was built
9345     * sensibly.
9346     */
9347    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9348                                           PackageSetting pkgSetting) {
9349        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9350
9351        // If "/system/lib64/apkname" exists, assume that is the per-package
9352        // native library directory to use; otherwise use "/system/lib/apkname".
9353        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9354        setBundledAppAbi(pkg, apkRoot, apkName);
9355        // pkgSetting might be null during rescan following uninstall of updates
9356        // to a bundled app, so accommodate that possibility.  The settings in
9357        // that case will be established later from the parsed package.
9358        //
9359        // If the settings aren't null, sync them up with what we've just derived.
9360        // note that apkRoot isn't stored in the package settings.
9361        if (pkgSetting != null) {
9362            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9363            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9364        }
9365    }
9366
9367    /**
9368     * Deduces the ABI of a bundled app and sets the relevant fields on the
9369     * parsed pkg object.
9370     *
9371     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9372     *        under which system libraries are installed.
9373     * @param apkName the name of the installed package.
9374     */
9375    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9376        final File codeFile = new File(pkg.codePath);
9377
9378        final boolean has64BitLibs;
9379        final boolean has32BitLibs;
9380        if (isApkFile(codeFile)) {
9381            // Monolithic install
9382            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9383            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9384        } else {
9385            // Cluster install
9386            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9387            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9388                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9389                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9390                has64BitLibs = (new File(rootDir, isa)).exists();
9391            } else {
9392                has64BitLibs = false;
9393            }
9394            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9395                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9396                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9397                has32BitLibs = (new File(rootDir, isa)).exists();
9398            } else {
9399                has32BitLibs = false;
9400            }
9401        }
9402
9403        if (has64BitLibs && !has32BitLibs) {
9404            // The package has 64 bit libs, but not 32 bit libs. Its primary
9405            // ABI should be 64 bit. We can safely assume here that the bundled
9406            // native libraries correspond to the most preferred ABI in the list.
9407
9408            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9409            pkg.applicationInfo.secondaryCpuAbi = null;
9410        } else if (has32BitLibs && !has64BitLibs) {
9411            // The package has 32 bit libs but not 64 bit libs. Its primary
9412            // ABI should be 32 bit.
9413
9414            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9415            pkg.applicationInfo.secondaryCpuAbi = null;
9416        } else if (has32BitLibs && has64BitLibs) {
9417            // The application has both 64 and 32 bit bundled libraries. We check
9418            // here that the app declares multiArch support, and warn if it doesn't.
9419            //
9420            // We will be lenient here and record both ABIs. The primary will be the
9421            // ABI that's higher on the list, i.e, a device that's configured to prefer
9422            // 64 bit apps will see a 64 bit primary ABI,
9423
9424            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9425                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9426            }
9427
9428            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9429                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9430                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9431            } else {
9432                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9433                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9434            }
9435        } else {
9436            pkg.applicationInfo.primaryCpuAbi = null;
9437            pkg.applicationInfo.secondaryCpuAbi = null;
9438        }
9439    }
9440
9441    private void killApplication(String pkgName, int appId, String reason) {
9442        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9443    }
9444
9445    private void killApplication(String pkgName, int appId, int userId, String reason) {
9446        // Request the ActivityManager to kill the process(only for existing packages)
9447        // so that we do not end up in a confused state while the user is still using the older
9448        // version of the application while the new one gets installed.
9449        final long token = Binder.clearCallingIdentity();
9450        try {
9451            IActivityManager am = ActivityManagerNative.getDefault();
9452            if (am != null) {
9453                try {
9454                    am.killApplication(pkgName, appId, userId, reason);
9455                } catch (RemoteException e) {
9456                }
9457            }
9458        } finally {
9459            Binder.restoreCallingIdentity(token);
9460        }
9461    }
9462
9463    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9464        // Remove the parent package setting
9465        PackageSetting ps = (PackageSetting) pkg.mExtras;
9466        if (ps != null) {
9467            removePackageLI(ps, chatty);
9468        }
9469        // Remove the child package setting
9470        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9471        for (int i = 0; i < childCount; i++) {
9472            PackageParser.Package childPkg = pkg.childPackages.get(i);
9473            ps = (PackageSetting) childPkg.mExtras;
9474            if (ps != null) {
9475                removePackageLI(ps, chatty);
9476            }
9477        }
9478    }
9479
9480    void removePackageLI(PackageSetting ps, boolean chatty) {
9481        if (DEBUG_INSTALL) {
9482            if (chatty)
9483                Log.d(TAG, "Removing package " + ps.name);
9484        }
9485
9486        // writer
9487        synchronized (mPackages) {
9488            mPackages.remove(ps.name);
9489            final PackageParser.Package pkg = ps.pkg;
9490            if (pkg != null) {
9491                cleanPackageDataStructuresLILPw(pkg, chatty);
9492            }
9493        }
9494    }
9495
9496    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9497        if (DEBUG_INSTALL) {
9498            if (chatty)
9499                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9500        }
9501
9502        // writer
9503        synchronized (mPackages) {
9504            // Remove the parent package
9505            mPackages.remove(pkg.applicationInfo.packageName);
9506            cleanPackageDataStructuresLILPw(pkg, chatty);
9507
9508            // Remove the child packages
9509            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9510            for (int i = 0; i < childCount; i++) {
9511                PackageParser.Package childPkg = pkg.childPackages.get(i);
9512                mPackages.remove(childPkg.applicationInfo.packageName);
9513                cleanPackageDataStructuresLILPw(childPkg, chatty);
9514            }
9515        }
9516    }
9517
9518    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9519        int N = pkg.providers.size();
9520        StringBuilder r = null;
9521        int i;
9522        for (i=0; i<N; i++) {
9523            PackageParser.Provider p = pkg.providers.get(i);
9524            mProviders.removeProvider(p);
9525            if (p.info.authority == null) {
9526
9527                /* There was another ContentProvider with this authority when
9528                 * this app was installed so this authority is null,
9529                 * Ignore it as we don't have to unregister the provider.
9530                 */
9531                continue;
9532            }
9533            String names[] = p.info.authority.split(";");
9534            for (int j = 0; j < names.length; j++) {
9535                if (mProvidersByAuthority.get(names[j]) == p) {
9536                    mProvidersByAuthority.remove(names[j]);
9537                    if (DEBUG_REMOVE) {
9538                        if (chatty)
9539                            Log.d(TAG, "Unregistered content provider: " + names[j]
9540                                    + ", className = " + p.info.name + ", isSyncable = "
9541                                    + p.info.isSyncable);
9542                    }
9543                }
9544            }
9545            if (DEBUG_REMOVE && chatty) {
9546                if (r == null) {
9547                    r = new StringBuilder(256);
9548                } else {
9549                    r.append(' ');
9550                }
9551                r.append(p.info.name);
9552            }
9553        }
9554        if (r != null) {
9555            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9556        }
9557
9558        N = pkg.services.size();
9559        r = null;
9560        for (i=0; i<N; i++) {
9561            PackageParser.Service s = pkg.services.get(i);
9562            mServices.removeService(s);
9563            if (chatty) {
9564                if (r == null) {
9565                    r = new StringBuilder(256);
9566                } else {
9567                    r.append(' ');
9568                }
9569                r.append(s.info.name);
9570            }
9571        }
9572        if (r != null) {
9573            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9574        }
9575
9576        N = pkg.receivers.size();
9577        r = null;
9578        for (i=0; i<N; i++) {
9579            PackageParser.Activity a = pkg.receivers.get(i);
9580            mReceivers.removeActivity(a, "receiver");
9581            if (DEBUG_REMOVE && chatty) {
9582                if (r == null) {
9583                    r = new StringBuilder(256);
9584                } else {
9585                    r.append(' ');
9586                }
9587                r.append(a.info.name);
9588            }
9589        }
9590        if (r != null) {
9591            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9592        }
9593
9594        N = pkg.activities.size();
9595        r = null;
9596        for (i=0; i<N; i++) {
9597            PackageParser.Activity a = pkg.activities.get(i);
9598            mActivities.removeActivity(a, "activity");
9599            if (DEBUG_REMOVE && chatty) {
9600                if (r == null) {
9601                    r = new StringBuilder(256);
9602                } else {
9603                    r.append(' ');
9604                }
9605                r.append(a.info.name);
9606            }
9607        }
9608        if (r != null) {
9609            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9610        }
9611
9612        N = pkg.permissions.size();
9613        r = null;
9614        for (i=0; i<N; i++) {
9615            PackageParser.Permission p = pkg.permissions.get(i);
9616            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9617            if (bp == null) {
9618                bp = mSettings.mPermissionTrees.get(p.info.name);
9619            }
9620            if (bp != null && bp.perm == p) {
9621                bp.perm = null;
9622                if (DEBUG_REMOVE && chatty) {
9623                    if (r == null) {
9624                        r = new StringBuilder(256);
9625                    } else {
9626                        r.append(' ');
9627                    }
9628                    r.append(p.info.name);
9629                }
9630            }
9631            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9632                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9633                if (appOpPkgs != null) {
9634                    appOpPkgs.remove(pkg.packageName);
9635                }
9636            }
9637        }
9638        if (r != null) {
9639            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9640        }
9641
9642        N = pkg.requestedPermissions.size();
9643        r = null;
9644        for (i=0; i<N; i++) {
9645            String perm = pkg.requestedPermissions.get(i);
9646            BasePermission bp = mSettings.mPermissions.get(perm);
9647            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9648                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9649                if (appOpPkgs != null) {
9650                    appOpPkgs.remove(pkg.packageName);
9651                    if (appOpPkgs.isEmpty()) {
9652                        mAppOpPermissionPackages.remove(perm);
9653                    }
9654                }
9655            }
9656        }
9657        if (r != null) {
9658            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9659        }
9660
9661        N = pkg.instrumentation.size();
9662        r = null;
9663        for (i=0; i<N; i++) {
9664            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9665            mInstrumentation.remove(a.getComponentName());
9666            if (DEBUG_REMOVE && chatty) {
9667                if (r == null) {
9668                    r = new StringBuilder(256);
9669                } else {
9670                    r.append(' ');
9671                }
9672                r.append(a.info.name);
9673            }
9674        }
9675        if (r != null) {
9676            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9677        }
9678
9679        r = null;
9680        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9681            // Only system apps can hold shared libraries.
9682            if (pkg.libraryNames != null) {
9683                for (i=0; i<pkg.libraryNames.size(); i++) {
9684                    String name = pkg.libraryNames.get(i);
9685                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9686                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9687                        mSharedLibraries.remove(name);
9688                        if (DEBUG_REMOVE && chatty) {
9689                            if (r == null) {
9690                                r = new StringBuilder(256);
9691                            } else {
9692                                r.append(' ');
9693                            }
9694                            r.append(name);
9695                        }
9696                    }
9697                }
9698            }
9699        }
9700        if (r != null) {
9701            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9702        }
9703    }
9704
9705    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9706        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9707            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9708                return true;
9709            }
9710        }
9711        return false;
9712    }
9713
9714    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9715    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9716    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9717
9718    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9719        // Update the parent permissions
9720        updatePermissionsLPw(pkg.packageName, pkg, flags);
9721        // Update the child permissions
9722        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9723        for (int i = 0; i < childCount; i++) {
9724            PackageParser.Package childPkg = pkg.childPackages.get(i);
9725            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9726        }
9727    }
9728
9729    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9730            int flags) {
9731        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9732        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9733    }
9734
9735    private void updatePermissionsLPw(String changingPkg,
9736            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9737        // Make sure there are no dangling permission trees.
9738        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9739        while (it.hasNext()) {
9740            final BasePermission bp = it.next();
9741            if (bp.packageSetting == null) {
9742                // We may not yet have parsed the package, so just see if
9743                // we still know about its settings.
9744                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9745            }
9746            if (bp.packageSetting == null) {
9747                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9748                        + " from package " + bp.sourcePackage);
9749                it.remove();
9750            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9751                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9752                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9753                            + " from package " + bp.sourcePackage);
9754                    flags |= UPDATE_PERMISSIONS_ALL;
9755                    it.remove();
9756                }
9757            }
9758        }
9759
9760        // Make sure all dynamic permissions have been assigned to a package,
9761        // and make sure there are no dangling permissions.
9762        it = mSettings.mPermissions.values().iterator();
9763        while (it.hasNext()) {
9764            final BasePermission bp = it.next();
9765            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9766                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9767                        + bp.name + " pkg=" + bp.sourcePackage
9768                        + " info=" + bp.pendingInfo);
9769                if (bp.packageSetting == null && bp.pendingInfo != null) {
9770                    final BasePermission tree = findPermissionTreeLP(bp.name);
9771                    if (tree != null && tree.perm != null) {
9772                        bp.packageSetting = tree.packageSetting;
9773                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9774                                new PermissionInfo(bp.pendingInfo));
9775                        bp.perm.info.packageName = tree.perm.info.packageName;
9776                        bp.perm.info.name = bp.name;
9777                        bp.uid = tree.uid;
9778                    }
9779                }
9780            }
9781            if (bp.packageSetting == null) {
9782                // We may not yet have parsed the package, so just see if
9783                // we still know about its settings.
9784                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9785            }
9786            if (bp.packageSetting == null) {
9787                Slog.w(TAG, "Removing dangling permission: " + bp.name
9788                        + " from package " + bp.sourcePackage);
9789                it.remove();
9790            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9791                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9792                    Slog.i(TAG, "Removing old permission: " + bp.name
9793                            + " from package " + bp.sourcePackage);
9794                    flags |= UPDATE_PERMISSIONS_ALL;
9795                    it.remove();
9796                }
9797            }
9798        }
9799
9800        // Now update the permissions for all packages, in particular
9801        // replace the granted permissions of the system packages.
9802        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9803            for (PackageParser.Package pkg : mPackages.values()) {
9804                if (pkg != pkgInfo) {
9805                    // Only replace for packages on requested volume
9806                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9807                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9808                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9809                    grantPermissionsLPw(pkg, replace, changingPkg);
9810                }
9811            }
9812        }
9813
9814        if (pkgInfo != null) {
9815            // Only replace for packages on requested volume
9816            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9817            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9818                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9819            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9820        }
9821    }
9822
9823    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9824            String packageOfInterest) {
9825        // IMPORTANT: There are two types of permissions: install and runtime.
9826        // Install time permissions are granted when the app is installed to
9827        // all device users and users added in the future. Runtime permissions
9828        // are granted at runtime explicitly to specific users. Normal and signature
9829        // protected permissions are install time permissions. Dangerous permissions
9830        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9831        // otherwise they are runtime permissions. This function does not manage
9832        // runtime permissions except for the case an app targeting Lollipop MR1
9833        // being upgraded to target a newer SDK, in which case dangerous permissions
9834        // are transformed from install time to runtime ones.
9835
9836        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9837        if (ps == null) {
9838            return;
9839        }
9840
9841        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9842
9843        PermissionsState permissionsState = ps.getPermissionsState();
9844        PermissionsState origPermissions = permissionsState;
9845
9846        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9847
9848        boolean runtimePermissionsRevoked = false;
9849        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9850
9851        boolean changedInstallPermission = false;
9852
9853        if (replace) {
9854            ps.installPermissionsFixed = false;
9855            if (!ps.isSharedUser()) {
9856                origPermissions = new PermissionsState(permissionsState);
9857                permissionsState.reset();
9858            } else {
9859                // We need to know only about runtime permission changes since the
9860                // calling code always writes the install permissions state but
9861                // the runtime ones are written only if changed. The only cases of
9862                // changed runtime permissions here are promotion of an install to
9863                // runtime and revocation of a runtime from a shared user.
9864                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9865                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9866                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9867                    runtimePermissionsRevoked = true;
9868                }
9869            }
9870        }
9871
9872        permissionsState.setGlobalGids(mGlobalGids);
9873
9874        final int N = pkg.requestedPermissions.size();
9875        for (int i=0; i<N; i++) {
9876            final String name = pkg.requestedPermissions.get(i);
9877            final BasePermission bp = mSettings.mPermissions.get(name);
9878
9879            if (DEBUG_INSTALL) {
9880                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9881            }
9882
9883            if (bp == null || bp.packageSetting == null) {
9884                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9885                    Slog.w(TAG, "Unknown permission " + name
9886                            + " in package " + pkg.packageName);
9887                }
9888                continue;
9889            }
9890
9891            final String perm = bp.name;
9892            boolean allowedSig = false;
9893            int grant = GRANT_DENIED;
9894
9895            // Keep track of app op permissions.
9896            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9897                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9898                if (pkgs == null) {
9899                    pkgs = new ArraySet<>();
9900                    mAppOpPermissionPackages.put(bp.name, pkgs);
9901                }
9902                pkgs.add(pkg.packageName);
9903            }
9904
9905            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9906            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9907                    >= Build.VERSION_CODES.M;
9908            switch (level) {
9909                case PermissionInfo.PROTECTION_NORMAL: {
9910                    // For all apps normal permissions are install time ones.
9911                    grant = GRANT_INSTALL;
9912                } break;
9913
9914                case PermissionInfo.PROTECTION_DANGEROUS: {
9915                    // If a permission review is required for legacy apps we represent
9916                    // their permissions as always granted runtime ones since we need
9917                    // to keep the review required permission flag per user while an
9918                    // install permission's state is shared across all users.
9919                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9920                        // For legacy apps dangerous permissions are install time ones.
9921                        grant = GRANT_INSTALL;
9922                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9923                        // For legacy apps that became modern, install becomes runtime.
9924                        grant = GRANT_UPGRADE;
9925                    } else if (mPromoteSystemApps
9926                            && isSystemApp(ps)
9927                            && mExistingSystemPackages.contains(ps.name)) {
9928                        // For legacy system apps, install becomes runtime.
9929                        // We cannot check hasInstallPermission() for system apps since those
9930                        // permissions were granted implicitly and not persisted pre-M.
9931                        grant = GRANT_UPGRADE;
9932                    } else {
9933                        // For modern apps keep runtime permissions unchanged.
9934                        grant = GRANT_RUNTIME;
9935                    }
9936                } break;
9937
9938                case PermissionInfo.PROTECTION_SIGNATURE: {
9939                    // For all apps signature permissions are install time ones.
9940                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9941                    if (allowedSig) {
9942                        grant = GRANT_INSTALL;
9943                    }
9944                } break;
9945            }
9946
9947            if (DEBUG_INSTALL) {
9948                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9949            }
9950
9951            if (grant != GRANT_DENIED) {
9952                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9953                    // If this is an existing, non-system package, then
9954                    // we can't add any new permissions to it.
9955                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9956                        // Except...  if this is a permission that was added
9957                        // to the platform (note: need to only do this when
9958                        // updating the platform).
9959                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9960                            grant = GRANT_DENIED;
9961                        }
9962                    }
9963                }
9964
9965                switch (grant) {
9966                    case GRANT_INSTALL: {
9967                        // Revoke this as runtime permission to handle the case of
9968                        // a runtime permission being downgraded to an install one.
9969                        // Also in permission review mode we keep dangerous permissions
9970                        // for legacy apps
9971                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9972                            if (origPermissions.getRuntimePermissionState(
9973                                    bp.name, userId) != null) {
9974                                // Revoke the runtime permission and clear the flags.
9975                                origPermissions.revokeRuntimePermission(bp, userId);
9976                                origPermissions.updatePermissionFlags(bp, userId,
9977                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9978                                // If we revoked a permission permission, we have to write.
9979                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9980                                        changedRuntimePermissionUserIds, userId);
9981                            }
9982                        }
9983                        // Grant an install permission.
9984                        if (permissionsState.grantInstallPermission(bp) !=
9985                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9986                            changedInstallPermission = true;
9987                        }
9988                    } break;
9989
9990                    case GRANT_RUNTIME: {
9991                        // Grant previously granted runtime permissions.
9992                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9993                            PermissionState permissionState = origPermissions
9994                                    .getRuntimePermissionState(bp.name, userId);
9995                            int flags = permissionState != null
9996                                    ? permissionState.getFlags() : 0;
9997                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9998                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9999                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10000                                    // If we cannot put the permission as it was, we have to write.
10001                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10002                                            changedRuntimePermissionUserIds, userId);
10003                                }
10004                                // If the app supports runtime permissions no need for a review.
10005                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10006                                        && appSupportsRuntimePermissions
10007                                        && (flags & PackageManager
10008                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10009                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10010                                    // Since we changed the flags, we have to write.
10011                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10012                                            changedRuntimePermissionUserIds, userId);
10013                                }
10014                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10015                                    && !appSupportsRuntimePermissions) {
10016                                // For legacy apps that need a permission review, every new
10017                                // runtime permission is granted but it is pending a review.
10018                                // We also need to review only platform defined runtime
10019                                // permissions as these are the only ones the platform knows
10020                                // how to disable the API to simulate revocation as legacy
10021                                // apps don't expect to run with revoked permissions.
10022                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10023                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10024                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10025                                        // We changed the flags, hence have to write.
10026                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10027                                                changedRuntimePermissionUserIds, userId);
10028                                    }
10029                                }
10030                                if (permissionsState.grantRuntimePermission(bp, userId)
10031                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10032                                    // We changed the permission, hence have to write.
10033                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10034                                            changedRuntimePermissionUserIds, userId);
10035                                }
10036                            }
10037                            // Propagate the permission flags.
10038                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10039                        }
10040                    } break;
10041
10042                    case GRANT_UPGRADE: {
10043                        // Grant runtime permissions for a previously held install permission.
10044                        PermissionState permissionState = origPermissions
10045                                .getInstallPermissionState(bp.name);
10046                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10047
10048                        if (origPermissions.revokeInstallPermission(bp)
10049                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10050                            // We will be transferring the permission flags, so clear them.
10051                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10052                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10053                            changedInstallPermission = true;
10054                        }
10055
10056                        // If the permission is not to be promoted to runtime we ignore it and
10057                        // also its other flags as they are not applicable to install permissions.
10058                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10059                            for (int userId : currentUserIds) {
10060                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10061                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10062                                    // Transfer the permission flags.
10063                                    permissionsState.updatePermissionFlags(bp, userId,
10064                                            flags, flags);
10065                                    // If we granted the permission, we have to write.
10066                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10067                                            changedRuntimePermissionUserIds, userId);
10068                                }
10069                            }
10070                        }
10071                    } break;
10072
10073                    default: {
10074                        if (packageOfInterest == null
10075                                || packageOfInterest.equals(pkg.packageName)) {
10076                            Slog.w(TAG, "Not granting permission " + perm
10077                                    + " to package " + pkg.packageName
10078                                    + " because it was previously installed without");
10079                        }
10080                    } break;
10081                }
10082            } else {
10083                if (permissionsState.revokeInstallPermission(bp) !=
10084                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10085                    // Also drop the permission flags.
10086                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10087                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10088                    changedInstallPermission = true;
10089                    Slog.i(TAG, "Un-granting permission " + perm
10090                            + " from package " + pkg.packageName
10091                            + " (protectionLevel=" + bp.protectionLevel
10092                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10093                            + ")");
10094                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10095                    // Don't print warning for app op permissions, since it is fine for them
10096                    // not to be granted, there is a UI for the user to decide.
10097                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10098                        Slog.w(TAG, "Not granting permission " + perm
10099                                + " to package " + pkg.packageName
10100                                + " (protectionLevel=" + bp.protectionLevel
10101                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10102                                + ")");
10103                    }
10104                }
10105            }
10106        }
10107
10108        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10109                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10110            // This is the first that we have heard about this package, so the
10111            // permissions we have now selected are fixed until explicitly
10112            // changed.
10113            ps.installPermissionsFixed = true;
10114        }
10115
10116        // Persist the runtime permissions state for users with changes. If permissions
10117        // were revoked because no app in the shared user declares them we have to
10118        // write synchronously to avoid losing runtime permissions state.
10119        for (int userId : changedRuntimePermissionUserIds) {
10120            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10121        }
10122
10123        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10124    }
10125
10126    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10127        boolean allowed = false;
10128        final int NP = PackageParser.NEW_PERMISSIONS.length;
10129        for (int ip=0; ip<NP; ip++) {
10130            final PackageParser.NewPermissionInfo npi
10131                    = PackageParser.NEW_PERMISSIONS[ip];
10132            if (npi.name.equals(perm)
10133                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10134                allowed = true;
10135                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10136                        + pkg.packageName);
10137                break;
10138            }
10139        }
10140        return allowed;
10141    }
10142
10143    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10144            BasePermission bp, PermissionsState origPermissions) {
10145        boolean allowed;
10146        allowed = (compareSignatures(
10147                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10148                        == PackageManager.SIGNATURE_MATCH)
10149                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10150                        == PackageManager.SIGNATURE_MATCH);
10151        if (!allowed && (bp.protectionLevel
10152                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10153            if (isSystemApp(pkg)) {
10154                // For updated system applications, a system permission
10155                // is granted only if it had been defined by the original application.
10156                if (pkg.isUpdatedSystemApp()) {
10157                    final PackageSetting sysPs = mSettings
10158                            .getDisabledSystemPkgLPr(pkg.packageName);
10159                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10160                        // If the original was granted this permission, we take
10161                        // that grant decision as read and propagate it to the
10162                        // update.
10163                        if (sysPs.isPrivileged()) {
10164                            allowed = true;
10165                        }
10166                    } else {
10167                        // The system apk may have been updated with an older
10168                        // version of the one on the data partition, but which
10169                        // granted a new system permission that it didn't have
10170                        // before.  In this case we do want to allow the app to
10171                        // now get the new permission if the ancestral apk is
10172                        // privileged to get it.
10173                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10174                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10175                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10176                                    allowed = true;
10177                                    break;
10178                                }
10179                            }
10180                        }
10181                        // Also if a privileged parent package on the system image or any of
10182                        // its children requested a privileged permission, the updated child
10183                        // packages can also get the permission.
10184                        if (pkg.parentPackage != null) {
10185                            final PackageSetting disabledSysParentPs = mSettings
10186                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10187                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10188                                    && disabledSysParentPs.isPrivileged()) {
10189                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10190                                    allowed = true;
10191                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10192                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10193                                    for (int i = 0; i < count; i++) {
10194                                        PackageParser.Package disabledSysChildPkg =
10195                                                disabledSysParentPs.pkg.childPackages.get(i);
10196                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10197                                                perm)) {
10198                                            allowed = true;
10199                                            break;
10200                                        }
10201                                    }
10202                                }
10203                            }
10204                        }
10205                    }
10206                } else {
10207                    allowed = isPrivilegedApp(pkg);
10208                }
10209            }
10210        }
10211        if (!allowed) {
10212            if (!allowed && (bp.protectionLevel
10213                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10214                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10215                // If this was a previously normal/dangerous permission that got moved
10216                // to a system permission as part of the runtime permission redesign, then
10217                // we still want to blindly grant it to old apps.
10218                allowed = true;
10219            }
10220            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10221                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10222                // If this permission is to be granted to the system installer and
10223                // this app is an installer, then it gets the permission.
10224                allowed = true;
10225            }
10226            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10227                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10228                // If this permission is to be granted to the system verifier and
10229                // this app is a verifier, then it gets the permission.
10230                allowed = true;
10231            }
10232            if (!allowed && (bp.protectionLevel
10233                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10234                    && isSystemApp(pkg)) {
10235                // Any pre-installed system app is allowed to get this permission.
10236                allowed = true;
10237            }
10238            if (!allowed && (bp.protectionLevel
10239                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10240                // For development permissions, a development permission
10241                // is granted only if it was already granted.
10242                allowed = origPermissions.hasInstallPermission(perm);
10243            }
10244            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10245                    && pkg.packageName.equals(mSetupWizardPackage)) {
10246                // If this permission is to be granted to the system setup wizard and
10247                // this app is a setup wizard, then it gets the permission.
10248                allowed = true;
10249            }
10250        }
10251        return allowed;
10252    }
10253
10254    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10255        final int permCount = pkg.requestedPermissions.size();
10256        for (int j = 0; j < permCount; j++) {
10257            String requestedPermission = pkg.requestedPermissions.get(j);
10258            if (permission.equals(requestedPermission)) {
10259                return true;
10260            }
10261        }
10262        return false;
10263    }
10264
10265    final class ActivityIntentResolver
10266            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10267        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10268                boolean defaultOnly, int userId) {
10269            if (!sUserManager.exists(userId)) return null;
10270            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10271            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10272        }
10273
10274        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10275                int userId) {
10276            if (!sUserManager.exists(userId)) return null;
10277            mFlags = flags;
10278            return super.queryIntent(intent, resolvedType,
10279                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10280        }
10281
10282        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10283                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10284            if (!sUserManager.exists(userId)) return null;
10285            if (packageActivities == null) {
10286                return null;
10287            }
10288            mFlags = flags;
10289            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10290            final int N = packageActivities.size();
10291            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10292                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10293
10294            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10295            for (int i = 0; i < N; ++i) {
10296                intentFilters = packageActivities.get(i).intents;
10297                if (intentFilters != null && intentFilters.size() > 0) {
10298                    PackageParser.ActivityIntentInfo[] array =
10299                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10300                    intentFilters.toArray(array);
10301                    listCut.add(array);
10302                }
10303            }
10304            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10305        }
10306
10307        /**
10308         * Finds a privileged activity that matches the specified activity names.
10309         */
10310        private PackageParser.Activity findMatchingActivity(
10311                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10312            for (PackageParser.Activity sysActivity : activityList) {
10313                if (sysActivity.info.name.equals(activityInfo.name)) {
10314                    return sysActivity;
10315                }
10316                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10317                    return sysActivity;
10318                }
10319                if (sysActivity.info.targetActivity != null) {
10320                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10321                        return sysActivity;
10322                    }
10323                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10324                        return sysActivity;
10325                    }
10326                }
10327            }
10328            return null;
10329        }
10330
10331        public class IterGenerator<E> {
10332            public Iterator<E> generate(ActivityIntentInfo info) {
10333                return null;
10334            }
10335        }
10336
10337        public class ActionIterGenerator extends IterGenerator<String> {
10338            @Override
10339            public Iterator<String> generate(ActivityIntentInfo info) {
10340                return info.actionsIterator();
10341            }
10342        }
10343
10344        public class CategoriesIterGenerator extends IterGenerator<String> {
10345            @Override
10346            public Iterator<String> generate(ActivityIntentInfo info) {
10347                return info.categoriesIterator();
10348            }
10349        }
10350
10351        public class SchemesIterGenerator extends IterGenerator<String> {
10352            @Override
10353            public Iterator<String> generate(ActivityIntentInfo info) {
10354                return info.schemesIterator();
10355            }
10356        }
10357
10358        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10359            @Override
10360            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10361                return info.authoritiesIterator();
10362            }
10363        }
10364
10365        /**
10366         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10367         * MODIFIED. Do not pass in a list that should not be changed.
10368         */
10369        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10370                IterGenerator<T> generator, Iterator<T> searchIterator) {
10371            // loop through the set of actions; every one must be found in the intent filter
10372            while (searchIterator.hasNext()) {
10373                // we must have at least one filter in the list to consider a match
10374                if (intentList.size() == 0) {
10375                    break;
10376                }
10377
10378                final T searchAction = searchIterator.next();
10379
10380                // loop through the set of intent filters
10381                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10382                while (intentIter.hasNext()) {
10383                    final ActivityIntentInfo intentInfo = intentIter.next();
10384                    boolean selectionFound = false;
10385
10386                    // loop through the intent filter's selection criteria; at least one
10387                    // of them must match the searched criteria
10388                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10389                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10390                        final T intentSelection = intentSelectionIter.next();
10391                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10392                            selectionFound = true;
10393                            break;
10394                        }
10395                    }
10396
10397                    // the selection criteria wasn't found in this filter's set; this filter
10398                    // is not a potential match
10399                    if (!selectionFound) {
10400                        intentIter.remove();
10401                    }
10402                }
10403            }
10404        }
10405
10406        private boolean isProtectedAction(ActivityIntentInfo filter) {
10407            final Iterator<String> actionsIter = filter.actionsIterator();
10408            while (actionsIter != null && actionsIter.hasNext()) {
10409                final String filterAction = actionsIter.next();
10410                if (PROTECTED_ACTIONS.contains(filterAction)) {
10411                    return true;
10412                }
10413            }
10414            return false;
10415        }
10416
10417        /**
10418         * Adjusts the priority of the given intent filter according to policy.
10419         * <p>
10420         * <ul>
10421         * <li>The priority for non privileged applications is capped to '0'</li>
10422         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10423         * <li>The priority for unbundled updates to privileged applications is capped to the
10424         *      priority defined on the system partition</li>
10425         * </ul>
10426         * <p>
10427         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10428         * allowed to obtain any priority on any action.
10429         */
10430        private void adjustPriority(
10431                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10432            // nothing to do; priority is fine as-is
10433            if (intent.getPriority() <= 0) {
10434                return;
10435            }
10436
10437            final ActivityInfo activityInfo = intent.activity.info;
10438            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10439
10440            final boolean privilegedApp =
10441                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10442            if (!privilegedApp) {
10443                // non-privileged applications can never define a priority >0
10444                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10445                        + " package: " + applicationInfo.packageName
10446                        + " activity: " + intent.activity.className
10447                        + " origPrio: " + intent.getPriority());
10448                intent.setPriority(0);
10449                return;
10450            }
10451
10452            if (systemActivities == null) {
10453                // the system package is not disabled; we're parsing the system partition
10454                if (isProtectedAction(intent)) {
10455                    if (mDeferProtectedFilters) {
10456                        // We can't deal with these just yet. No component should ever obtain a
10457                        // >0 priority for a protected actions, with ONE exception -- the setup
10458                        // wizard. The setup wizard, however, cannot be known until we're able to
10459                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10460                        // until all intent filters have been processed. Chicken, meet egg.
10461                        // Let the filter temporarily have a high priority and rectify the
10462                        // priorities after all system packages have been scanned.
10463                        mProtectedFilters.add(intent);
10464                        if (DEBUG_FILTERS) {
10465                            Slog.i(TAG, "Protected action; save for later;"
10466                                    + " package: " + applicationInfo.packageName
10467                                    + " activity: " + intent.activity.className
10468                                    + " origPrio: " + intent.getPriority());
10469                        }
10470                        return;
10471                    } else {
10472                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10473                            Slog.i(TAG, "No setup wizard;"
10474                                + " All protected intents capped to priority 0");
10475                        }
10476                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10477                            if (DEBUG_FILTERS) {
10478                                Slog.i(TAG, "Found setup wizard;"
10479                                    + " allow priority " + intent.getPriority() + ";"
10480                                    + " package: " + intent.activity.info.packageName
10481                                    + " activity: " + intent.activity.className
10482                                    + " priority: " + intent.getPriority());
10483                            }
10484                            // setup wizard gets whatever it wants
10485                            return;
10486                        }
10487                        Slog.w(TAG, "Protected action; cap priority to 0;"
10488                                + " package: " + intent.activity.info.packageName
10489                                + " activity: " + intent.activity.className
10490                                + " origPrio: " + intent.getPriority());
10491                        intent.setPriority(0);
10492                        return;
10493                    }
10494                }
10495                // privileged apps on the system image get whatever priority they request
10496                return;
10497            }
10498
10499            // privileged app unbundled update ... try to find the same activity
10500            final PackageParser.Activity foundActivity =
10501                    findMatchingActivity(systemActivities, activityInfo);
10502            if (foundActivity == null) {
10503                // this is a new activity; it cannot obtain >0 priority
10504                if (DEBUG_FILTERS) {
10505                    Slog.i(TAG, "New activity; cap priority to 0;"
10506                            + " package: " + applicationInfo.packageName
10507                            + " activity: " + intent.activity.className
10508                            + " origPrio: " + intent.getPriority());
10509                }
10510                intent.setPriority(0);
10511                return;
10512            }
10513
10514            // found activity, now check for filter equivalence
10515
10516            // a shallow copy is enough; we modify the list, not its contents
10517            final List<ActivityIntentInfo> intentListCopy =
10518                    new ArrayList<>(foundActivity.intents);
10519            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10520
10521            // find matching action subsets
10522            final Iterator<String> actionsIterator = intent.actionsIterator();
10523            if (actionsIterator != null) {
10524                getIntentListSubset(
10525                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10526                if (intentListCopy.size() == 0) {
10527                    // no more intents to match; we're not equivalent
10528                    if (DEBUG_FILTERS) {
10529                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10530                                + " package: " + applicationInfo.packageName
10531                                + " activity: " + intent.activity.className
10532                                + " origPrio: " + intent.getPriority());
10533                    }
10534                    intent.setPriority(0);
10535                    return;
10536                }
10537            }
10538
10539            // find matching category subsets
10540            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10541            if (categoriesIterator != null) {
10542                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10543                        categoriesIterator);
10544                if (intentListCopy.size() == 0) {
10545                    // no more intents to match; we're not equivalent
10546                    if (DEBUG_FILTERS) {
10547                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10548                                + " package: " + applicationInfo.packageName
10549                                + " activity: " + intent.activity.className
10550                                + " origPrio: " + intent.getPriority());
10551                    }
10552                    intent.setPriority(0);
10553                    return;
10554                }
10555            }
10556
10557            // find matching schemes subsets
10558            final Iterator<String> schemesIterator = intent.schemesIterator();
10559            if (schemesIterator != null) {
10560                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10561                        schemesIterator);
10562                if (intentListCopy.size() == 0) {
10563                    // no more intents to match; we're not equivalent
10564                    if (DEBUG_FILTERS) {
10565                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10566                                + " package: " + applicationInfo.packageName
10567                                + " activity: " + intent.activity.className
10568                                + " origPrio: " + intent.getPriority());
10569                    }
10570                    intent.setPriority(0);
10571                    return;
10572                }
10573            }
10574
10575            // find matching authorities subsets
10576            final Iterator<IntentFilter.AuthorityEntry>
10577                    authoritiesIterator = intent.authoritiesIterator();
10578            if (authoritiesIterator != null) {
10579                getIntentListSubset(intentListCopy,
10580                        new AuthoritiesIterGenerator(),
10581                        authoritiesIterator);
10582                if (intentListCopy.size() == 0) {
10583                    // no more intents to match; we're not equivalent
10584                    if (DEBUG_FILTERS) {
10585                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10586                                + " package: " + applicationInfo.packageName
10587                                + " activity: " + intent.activity.className
10588                                + " origPrio: " + intent.getPriority());
10589                    }
10590                    intent.setPriority(0);
10591                    return;
10592                }
10593            }
10594
10595            // we found matching filter(s); app gets the max priority of all intents
10596            int cappedPriority = 0;
10597            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10598                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10599            }
10600            if (intent.getPriority() > cappedPriority) {
10601                if (DEBUG_FILTERS) {
10602                    Slog.i(TAG, "Found matching filter(s);"
10603                            + " cap priority to " + cappedPriority + ";"
10604                            + " package: " + applicationInfo.packageName
10605                            + " activity: " + intent.activity.className
10606                            + " origPrio: " + intent.getPriority());
10607                }
10608                intent.setPriority(cappedPriority);
10609                return;
10610            }
10611            // all this for nothing; the requested priority was <= what was on the system
10612        }
10613
10614        public final void addActivity(PackageParser.Activity a, String type) {
10615            mActivities.put(a.getComponentName(), a);
10616            if (DEBUG_SHOW_INFO)
10617                Log.v(
10618                TAG, "  " + type + " " +
10619                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10620            if (DEBUG_SHOW_INFO)
10621                Log.v(TAG, "    Class=" + a.info.name);
10622            final int NI = a.intents.size();
10623            for (int j=0; j<NI; j++) {
10624                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10625                if ("activity".equals(type)) {
10626                    final PackageSetting ps =
10627                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10628                    final List<PackageParser.Activity> systemActivities =
10629                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10630                    adjustPriority(systemActivities, intent);
10631                }
10632                if (DEBUG_SHOW_INFO) {
10633                    Log.v(TAG, "    IntentFilter:");
10634                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10635                }
10636                if (!intent.debugCheck()) {
10637                    Log.w(TAG, "==> For Activity " + a.info.name);
10638                }
10639                addFilter(intent);
10640            }
10641        }
10642
10643        public final void removeActivity(PackageParser.Activity a, String type) {
10644            mActivities.remove(a.getComponentName());
10645            if (DEBUG_SHOW_INFO) {
10646                Log.v(TAG, "  " + type + " "
10647                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10648                                : a.info.name) + ":");
10649                Log.v(TAG, "    Class=" + a.info.name);
10650            }
10651            final int NI = a.intents.size();
10652            for (int j=0; j<NI; j++) {
10653                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10654                if (DEBUG_SHOW_INFO) {
10655                    Log.v(TAG, "    IntentFilter:");
10656                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10657                }
10658                removeFilter(intent);
10659            }
10660        }
10661
10662        @Override
10663        protected boolean allowFilterResult(
10664                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10665            ActivityInfo filterAi = filter.activity.info;
10666            for (int i=dest.size()-1; i>=0; i--) {
10667                ActivityInfo destAi = dest.get(i).activityInfo;
10668                if (destAi.name == filterAi.name
10669                        && destAi.packageName == filterAi.packageName) {
10670                    return false;
10671                }
10672            }
10673            return true;
10674        }
10675
10676        @Override
10677        protected ActivityIntentInfo[] newArray(int size) {
10678            return new ActivityIntentInfo[size];
10679        }
10680
10681        @Override
10682        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10683            if (!sUserManager.exists(userId)) return true;
10684            PackageParser.Package p = filter.activity.owner;
10685            if (p != null) {
10686                PackageSetting ps = (PackageSetting)p.mExtras;
10687                if (ps != null) {
10688                    // System apps are never considered stopped for purposes of
10689                    // filtering, because there may be no way for the user to
10690                    // actually re-launch them.
10691                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10692                            && ps.getStopped(userId);
10693                }
10694            }
10695            return false;
10696        }
10697
10698        @Override
10699        protected boolean isPackageForFilter(String packageName,
10700                PackageParser.ActivityIntentInfo info) {
10701            return packageName.equals(info.activity.owner.packageName);
10702        }
10703
10704        @Override
10705        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10706                int match, int userId) {
10707            if (!sUserManager.exists(userId)) return null;
10708            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10709                return null;
10710            }
10711            final PackageParser.Activity activity = info.activity;
10712            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10713            if (ps == null) {
10714                return null;
10715            }
10716            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10717                    ps.readUserState(userId), userId);
10718            if (ai == null) {
10719                return null;
10720            }
10721            final ResolveInfo res = new ResolveInfo();
10722            res.activityInfo = ai;
10723            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10724                res.filter = info;
10725            }
10726            if (info != null) {
10727                res.handleAllWebDataURI = info.handleAllWebDataURI();
10728            }
10729            res.priority = info.getPriority();
10730            res.preferredOrder = activity.owner.mPreferredOrder;
10731            //System.out.println("Result: " + res.activityInfo.className +
10732            //                   " = " + res.priority);
10733            res.match = match;
10734            res.isDefault = info.hasDefault;
10735            res.labelRes = info.labelRes;
10736            res.nonLocalizedLabel = info.nonLocalizedLabel;
10737            if (userNeedsBadging(userId)) {
10738                res.noResourceId = true;
10739            } else {
10740                res.icon = info.icon;
10741            }
10742            res.iconResourceId = info.icon;
10743            res.system = res.activityInfo.applicationInfo.isSystemApp();
10744            return res;
10745        }
10746
10747        @Override
10748        protected void sortResults(List<ResolveInfo> results) {
10749            Collections.sort(results, mResolvePrioritySorter);
10750        }
10751
10752        @Override
10753        protected void dumpFilter(PrintWriter out, String prefix,
10754                PackageParser.ActivityIntentInfo filter) {
10755            out.print(prefix); out.print(
10756                    Integer.toHexString(System.identityHashCode(filter.activity)));
10757                    out.print(' ');
10758                    filter.activity.printComponentShortName(out);
10759                    out.print(" filter ");
10760                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10761        }
10762
10763        @Override
10764        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10765            return filter.activity;
10766        }
10767
10768        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10769            PackageParser.Activity activity = (PackageParser.Activity)label;
10770            out.print(prefix); out.print(
10771                    Integer.toHexString(System.identityHashCode(activity)));
10772                    out.print(' ');
10773                    activity.printComponentShortName(out);
10774            if (count > 1) {
10775                out.print(" ("); out.print(count); out.print(" filters)");
10776            }
10777            out.println();
10778        }
10779
10780        // Keys are String (activity class name), values are Activity.
10781        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10782                = new ArrayMap<ComponentName, PackageParser.Activity>();
10783        private int mFlags;
10784    }
10785
10786    private final class ServiceIntentResolver
10787            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10788        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10789                boolean defaultOnly, int userId) {
10790            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10791            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10792        }
10793
10794        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10795                int userId) {
10796            if (!sUserManager.exists(userId)) return null;
10797            mFlags = flags;
10798            return super.queryIntent(intent, resolvedType,
10799                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10800        }
10801
10802        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10803                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10804            if (!sUserManager.exists(userId)) return null;
10805            if (packageServices == null) {
10806                return null;
10807            }
10808            mFlags = flags;
10809            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10810            final int N = packageServices.size();
10811            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10812                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10813
10814            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10815            for (int i = 0; i < N; ++i) {
10816                intentFilters = packageServices.get(i).intents;
10817                if (intentFilters != null && intentFilters.size() > 0) {
10818                    PackageParser.ServiceIntentInfo[] array =
10819                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10820                    intentFilters.toArray(array);
10821                    listCut.add(array);
10822                }
10823            }
10824            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10825        }
10826
10827        public final void addService(PackageParser.Service s) {
10828            mServices.put(s.getComponentName(), s);
10829            if (DEBUG_SHOW_INFO) {
10830                Log.v(TAG, "  "
10831                        + (s.info.nonLocalizedLabel != null
10832                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10833                Log.v(TAG, "    Class=" + s.info.name);
10834            }
10835            final int NI = s.intents.size();
10836            int j;
10837            for (j=0; j<NI; j++) {
10838                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10839                if (DEBUG_SHOW_INFO) {
10840                    Log.v(TAG, "    IntentFilter:");
10841                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10842                }
10843                if (!intent.debugCheck()) {
10844                    Log.w(TAG, "==> For Service " + s.info.name);
10845                }
10846                addFilter(intent);
10847            }
10848        }
10849
10850        public final void removeService(PackageParser.Service s) {
10851            mServices.remove(s.getComponentName());
10852            if (DEBUG_SHOW_INFO) {
10853                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10854                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10855                Log.v(TAG, "    Class=" + s.info.name);
10856            }
10857            final int NI = s.intents.size();
10858            int j;
10859            for (j=0; j<NI; j++) {
10860                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10861                if (DEBUG_SHOW_INFO) {
10862                    Log.v(TAG, "    IntentFilter:");
10863                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10864                }
10865                removeFilter(intent);
10866            }
10867        }
10868
10869        @Override
10870        protected boolean allowFilterResult(
10871                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10872            ServiceInfo filterSi = filter.service.info;
10873            for (int i=dest.size()-1; i>=0; i--) {
10874                ServiceInfo destAi = dest.get(i).serviceInfo;
10875                if (destAi.name == filterSi.name
10876                        && destAi.packageName == filterSi.packageName) {
10877                    return false;
10878                }
10879            }
10880            return true;
10881        }
10882
10883        @Override
10884        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10885            return new PackageParser.ServiceIntentInfo[size];
10886        }
10887
10888        @Override
10889        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10890            if (!sUserManager.exists(userId)) return true;
10891            PackageParser.Package p = filter.service.owner;
10892            if (p != null) {
10893                PackageSetting ps = (PackageSetting)p.mExtras;
10894                if (ps != null) {
10895                    // System apps are never considered stopped for purposes of
10896                    // filtering, because there may be no way for the user to
10897                    // actually re-launch them.
10898                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10899                            && ps.getStopped(userId);
10900                }
10901            }
10902            return false;
10903        }
10904
10905        @Override
10906        protected boolean isPackageForFilter(String packageName,
10907                PackageParser.ServiceIntentInfo info) {
10908            return packageName.equals(info.service.owner.packageName);
10909        }
10910
10911        @Override
10912        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10913                int match, int userId) {
10914            if (!sUserManager.exists(userId)) return null;
10915            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10916            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10917                return null;
10918            }
10919            final PackageParser.Service service = info.service;
10920            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10921            if (ps == null) {
10922                return null;
10923            }
10924            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10925                    ps.readUserState(userId), userId);
10926            if (si == null) {
10927                return null;
10928            }
10929            final ResolveInfo res = new ResolveInfo();
10930            res.serviceInfo = si;
10931            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10932                res.filter = filter;
10933            }
10934            res.priority = info.getPriority();
10935            res.preferredOrder = service.owner.mPreferredOrder;
10936            res.match = match;
10937            res.isDefault = info.hasDefault;
10938            res.labelRes = info.labelRes;
10939            res.nonLocalizedLabel = info.nonLocalizedLabel;
10940            res.icon = info.icon;
10941            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10942            return res;
10943        }
10944
10945        @Override
10946        protected void sortResults(List<ResolveInfo> results) {
10947            Collections.sort(results, mResolvePrioritySorter);
10948        }
10949
10950        @Override
10951        protected void dumpFilter(PrintWriter out, String prefix,
10952                PackageParser.ServiceIntentInfo filter) {
10953            out.print(prefix); out.print(
10954                    Integer.toHexString(System.identityHashCode(filter.service)));
10955                    out.print(' ');
10956                    filter.service.printComponentShortName(out);
10957                    out.print(" filter ");
10958                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10959        }
10960
10961        @Override
10962        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10963            return filter.service;
10964        }
10965
10966        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10967            PackageParser.Service service = (PackageParser.Service)label;
10968            out.print(prefix); out.print(
10969                    Integer.toHexString(System.identityHashCode(service)));
10970                    out.print(' ');
10971                    service.printComponentShortName(out);
10972            if (count > 1) {
10973                out.print(" ("); out.print(count); out.print(" filters)");
10974            }
10975            out.println();
10976        }
10977
10978//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10979//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10980//            final List<ResolveInfo> retList = Lists.newArrayList();
10981//            while (i.hasNext()) {
10982//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10983//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10984//                    retList.add(resolveInfo);
10985//                }
10986//            }
10987//            return retList;
10988//        }
10989
10990        // Keys are String (activity class name), values are Activity.
10991        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10992                = new ArrayMap<ComponentName, PackageParser.Service>();
10993        private int mFlags;
10994    };
10995
10996    private final class ProviderIntentResolver
10997            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10998        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10999                boolean defaultOnly, int userId) {
11000            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11001            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11002        }
11003
11004        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11005                int userId) {
11006            if (!sUserManager.exists(userId))
11007                return null;
11008            mFlags = flags;
11009            return super.queryIntent(intent, resolvedType,
11010                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11011        }
11012
11013        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11014                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11015            if (!sUserManager.exists(userId))
11016                return null;
11017            if (packageProviders == null) {
11018                return null;
11019            }
11020            mFlags = flags;
11021            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11022            final int N = packageProviders.size();
11023            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11024                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11025
11026            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11027            for (int i = 0; i < N; ++i) {
11028                intentFilters = packageProviders.get(i).intents;
11029                if (intentFilters != null && intentFilters.size() > 0) {
11030                    PackageParser.ProviderIntentInfo[] array =
11031                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11032                    intentFilters.toArray(array);
11033                    listCut.add(array);
11034                }
11035            }
11036            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11037        }
11038
11039        public final void addProvider(PackageParser.Provider p) {
11040            if (mProviders.containsKey(p.getComponentName())) {
11041                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11042                return;
11043            }
11044
11045            mProviders.put(p.getComponentName(), p);
11046            if (DEBUG_SHOW_INFO) {
11047                Log.v(TAG, "  "
11048                        + (p.info.nonLocalizedLabel != null
11049                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11050                Log.v(TAG, "    Class=" + p.info.name);
11051            }
11052            final int NI = p.intents.size();
11053            int j;
11054            for (j = 0; j < NI; j++) {
11055                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11056                if (DEBUG_SHOW_INFO) {
11057                    Log.v(TAG, "    IntentFilter:");
11058                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11059                }
11060                if (!intent.debugCheck()) {
11061                    Log.w(TAG, "==> For Provider " + p.info.name);
11062                }
11063                addFilter(intent);
11064            }
11065        }
11066
11067        public final void removeProvider(PackageParser.Provider p) {
11068            mProviders.remove(p.getComponentName());
11069            if (DEBUG_SHOW_INFO) {
11070                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11071                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11072                Log.v(TAG, "    Class=" + p.info.name);
11073            }
11074            final int NI = p.intents.size();
11075            int j;
11076            for (j = 0; j < NI; j++) {
11077                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11078                if (DEBUG_SHOW_INFO) {
11079                    Log.v(TAG, "    IntentFilter:");
11080                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11081                }
11082                removeFilter(intent);
11083            }
11084        }
11085
11086        @Override
11087        protected boolean allowFilterResult(
11088                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11089            ProviderInfo filterPi = filter.provider.info;
11090            for (int i = dest.size() - 1; i >= 0; i--) {
11091                ProviderInfo destPi = dest.get(i).providerInfo;
11092                if (destPi.name == filterPi.name
11093                        && destPi.packageName == filterPi.packageName) {
11094                    return false;
11095                }
11096            }
11097            return true;
11098        }
11099
11100        @Override
11101        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11102            return new PackageParser.ProviderIntentInfo[size];
11103        }
11104
11105        @Override
11106        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11107            if (!sUserManager.exists(userId))
11108                return true;
11109            PackageParser.Package p = filter.provider.owner;
11110            if (p != null) {
11111                PackageSetting ps = (PackageSetting) p.mExtras;
11112                if (ps != null) {
11113                    // System apps are never considered stopped for purposes of
11114                    // filtering, because there may be no way for the user to
11115                    // actually re-launch them.
11116                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11117                            && ps.getStopped(userId);
11118                }
11119            }
11120            return false;
11121        }
11122
11123        @Override
11124        protected boolean isPackageForFilter(String packageName,
11125                PackageParser.ProviderIntentInfo info) {
11126            return packageName.equals(info.provider.owner.packageName);
11127        }
11128
11129        @Override
11130        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11131                int match, int userId) {
11132            if (!sUserManager.exists(userId))
11133                return null;
11134            final PackageParser.ProviderIntentInfo info = filter;
11135            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11136                return null;
11137            }
11138            final PackageParser.Provider provider = info.provider;
11139            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11140            if (ps == null) {
11141                return null;
11142            }
11143            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11144                    ps.readUserState(userId), userId);
11145            if (pi == null) {
11146                return null;
11147            }
11148            final ResolveInfo res = new ResolveInfo();
11149            res.providerInfo = pi;
11150            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11151                res.filter = filter;
11152            }
11153            res.priority = info.getPriority();
11154            res.preferredOrder = provider.owner.mPreferredOrder;
11155            res.match = match;
11156            res.isDefault = info.hasDefault;
11157            res.labelRes = info.labelRes;
11158            res.nonLocalizedLabel = info.nonLocalizedLabel;
11159            res.icon = info.icon;
11160            res.system = res.providerInfo.applicationInfo.isSystemApp();
11161            return res;
11162        }
11163
11164        @Override
11165        protected void sortResults(List<ResolveInfo> results) {
11166            Collections.sort(results, mResolvePrioritySorter);
11167        }
11168
11169        @Override
11170        protected void dumpFilter(PrintWriter out, String prefix,
11171                PackageParser.ProviderIntentInfo filter) {
11172            out.print(prefix);
11173            out.print(
11174                    Integer.toHexString(System.identityHashCode(filter.provider)));
11175            out.print(' ');
11176            filter.provider.printComponentShortName(out);
11177            out.print(" filter ");
11178            out.println(Integer.toHexString(System.identityHashCode(filter)));
11179        }
11180
11181        @Override
11182        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11183            return filter.provider;
11184        }
11185
11186        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11187            PackageParser.Provider provider = (PackageParser.Provider)label;
11188            out.print(prefix); out.print(
11189                    Integer.toHexString(System.identityHashCode(provider)));
11190                    out.print(' ');
11191                    provider.printComponentShortName(out);
11192            if (count > 1) {
11193                out.print(" ("); out.print(count); out.print(" filters)");
11194            }
11195            out.println();
11196        }
11197
11198        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11199                = new ArrayMap<ComponentName, PackageParser.Provider>();
11200        private int mFlags;
11201    }
11202
11203    private static final class EphemeralIntentResolver
11204            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11205        @Override
11206        protected EphemeralResolveIntentInfo[] newArray(int size) {
11207            return new EphemeralResolveIntentInfo[size];
11208        }
11209
11210        @Override
11211        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11212            return true;
11213        }
11214
11215        @Override
11216        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11217                int userId) {
11218            if (!sUserManager.exists(userId)) {
11219                return null;
11220            }
11221            return info.getEphemeralResolveInfo();
11222        }
11223    }
11224
11225    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11226            new Comparator<ResolveInfo>() {
11227        public int compare(ResolveInfo r1, ResolveInfo r2) {
11228            int v1 = r1.priority;
11229            int v2 = r2.priority;
11230            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11231            if (v1 != v2) {
11232                return (v1 > v2) ? -1 : 1;
11233            }
11234            v1 = r1.preferredOrder;
11235            v2 = r2.preferredOrder;
11236            if (v1 != v2) {
11237                return (v1 > v2) ? -1 : 1;
11238            }
11239            if (r1.isDefault != r2.isDefault) {
11240                return r1.isDefault ? -1 : 1;
11241            }
11242            v1 = r1.match;
11243            v2 = r2.match;
11244            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11245            if (v1 != v2) {
11246                return (v1 > v2) ? -1 : 1;
11247            }
11248            if (r1.system != r2.system) {
11249                return r1.system ? -1 : 1;
11250            }
11251            if (r1.activityInfo != null) {
11252                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11253            }
11254            if (r1.serviceInfo != null) {
11255                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11256            }
11257            if (r1.providerInfo != null) {
11258                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11259            }
11260            return 0;
11261        }
11262    };
11263
11264    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11265            new Comparator<ProviderInfo>() {
11266        public int compare(ProviderInfo p1, ProviderInfo p2) {
11267            final int v1 = p1.initOrder;
11268            final int v2 = p2.initOrder;
11269            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11270        }
11271    };
11272
11273    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11274            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11275            final int[] userIds) {
11276        mHandler.post(new Runnable() {
11277            @Override
11278            public void run() {
11279                try {
11280                    final IActivityManager am = ActivityManagerNative.getDefault();
11281                    if (am == null) return;
11282                    final int[] resolvedUserIds;
11283                    if (userIds == null) {
11284                        resolvedUserIds = am.getRunningUserIds();
11285                    } else {
11286                        resolvedUserIds = userIds;
11287                    }
11288                    for (int id : resolvedUserIds) {
11289                        final Intent intent = new Intent(action,
11290                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11291                        if (extras != null) {
11292                            intent.putExtras(extras);
11293                        }
11294                        if (targetPkg != null) {
11295                            intent.setPackage(targetPkg);
11296                        }
11297                        // Modify the UID when posting to other users
11298                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11299                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11300                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11301                            intent.putExtra(Intent.EXTRA_UID, uid);
11302                        }
11303                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11304                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11305                        if (DEBUG_BROADCASTS) {
11306                            RuntimeException here = new RuntimeException("here");
11307                            here.fillInStackTrace();
11308                            Slog.d(TAG, "Sending to user " + id + ": "
11309                                    + intent.toShortString(false, true, false, false)
11310                                    + " " + intent.getExtras(), here);
11311                        }
11312                        am.broadcastIntent(null, intent, null, finishedReceiver,
11313                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11314                                null, finishedReceiver != null, false, id);
11315                    }
11316                } catch (RemoteException ex) {
11317                }
11318            }
11319        });
11320    }
11321
11322    /**
11323     * Check if the external storage media is available. This is true if there
11324     * is a mounted external storage medium or if the external storage is
11325     * emulated.
11326     */
11327    private boolean isExternalMediaAvailable() {
11328        return mMediaMounted || Environment.isExternalStorageEmulated();
11329    }
11330
11331    @Override
11332    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11333        // writer
11334        synchronized (mPackages) {
11335            if (!isExternalMediaAvailable()) {
11336                // If the external storage is no longer mounted at this point,
11337                // the caller may not have been able to delete all of this
11338                // packages files and can not delete any more.  Bail.
11339                return null;
11340            }
11341            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11342            if (lastPackage != null) {
11343                pkgs.remove(lastPackage);
11344            }
11345            if (pkgs.size() > 0) {
11346                return pkgs.get(0);
11347            }
11348        }
11349        return null;
11350    }
11351
11352    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11353        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11354                userId, andCode ? 1 : 0, packageName);
11355        if (mSystemReady) {
11356            msg.sendToTarget();
11357        } else {
11358            if (mPostSystemReadyMessages == null) {
11359                mPostSystemReadyMessages = new ArrayList<>();
11360            }
11361            mPostSystemReadyMessages.add(msg);
11362        }
11363    }
11364
11365    void startCleaningPackages() {
11366        // reader
11367        if (!isExternalMediaAvailable()) {
11368            return;
11369        }
11370        synchronized (mPackages) {
11371            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11372                return;
11373            }
11374        }
11375        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11376        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11377        IActivityManager am = ActivityManagerNative.getDefault();
11378        if (am != null) {
11379            try {
11380                am.startService(null, intent, null, mContext.getOpPackageName(),
11381                        UserHandle.USER_SYSTEM);
11382            } catch (RemoteException e) {
11383            }
11384        }
11385    }
11386
11387    @Override
11388    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11389            int installFlags, String installerPackageName, int userId) {
11390        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11391
11392        final int callingUid = Binder.getCallingUid();
11393        enforceCrossUserPermission(callingUid, userId,
11394                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11395
11396        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11397            try {
11398                if (observer != null) {
11399                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11400                }
11401            } catch (RemoteException re) {
11402            }
11403            return;
11404        }
11405
11406        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11407            installFlags |= PackageManager.INSTALL_FROM_ADB;
11408
11409        } else {
11410            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11411            // about installerPackageName.
11412
11413            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11414            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11415        }
11416
11417        UserHandle user;
11418        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11419            user = UserHandle.ALL;
11420        } else {
11421            user = new UserHandle(userId);
11422        }
11423
11424        // Only system components can circumvent runtime permissions when installing.
11425        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11426                && mContext.checkCallingOrSelfPermission(Manifest.permission
11427                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11428            throw new SecurityException("You need the "
11429                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11430                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11431        }
11432
11433        final File originFile = new File(originPath);
11434        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11435
11436        final Message msg = mHandler.obtainMessage(INIT_COPY);
11437        final VerificationInfo verificationInfo = new VerificationInfo(
11438                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11439        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11440                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11441                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11442                null /*certificates*/);
11443        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11444        msg.obj = params;
11445
11446        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11447                System.identityHashCode(msg.obj));
11448        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11449                System.identityHashCode(msg.obj));
11450
11451        mHandler.sendMessage(msg);
11452    }
11453
11454    void installStage(String packageName, File stagedDir, String stagedCid,
11455            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11456            String installerPackageName, int installerUid, UserHandle user,
11457            Certificate[][] certificates) {
11458        if (DEBUG_EPHEMERAL) {
11459            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11460                Slog.d(TAG, "Ephemeral install of " + packageName);
11461            }
11462        }
11463        final VerificationInfo verificationInfo = new VerificationInfo(
11464                sessionParams.originatingUri, sessionParams.referrerUri,
11465                sessionParams.originatingUid, installerUid);
11466
11467        final OriginInfo origin;
11468        if (stagedDir != null) {
11469            origin = OriginInfo.fromStagedFile(stagedDir);
11470        } else {
11471            origin = OriginInfo.fromStagedContainer(stagedCid);
11472        }
11473
11474        final Message msg = mHandler.obtainMessage(INIT_COPY);
11475        final InstallParams params = new InstallParams(origin, null, observer,
11476                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11477                verificationInfo, user, sessionParams.abiOverride,
11478                sessionParams.grantedRuntimePermissions, certificates);
11479        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11480        msg.obj = params;
11481
11482        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11483                System.identityHashCode(msg.obj));
11484        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11485                System.identityHashCode(msg.obj));
11486
11487        mHandler.sendMessage(msg);
11488    }
11489
11490    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11491            int userId) {
11492        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11493        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11494    }
11495
11496    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11497            int appId, int userId) {
11498        Bundle extras = new Bundle(1);
11499        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11500
11501        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11502                packageName, extras, 0, null, null, new int[] {userId});
11503        try {
11504            IActivityManager am = ActivityManagerNative.getDefault();
11505            if (isSystem && am.isUserRunning(userId, 0)) {
11506                // The just-installed/enabled app is bundled on the system, so presumed
11507                // to be able to run automatically without needing an explicit launch.
11508                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11509                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11510                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11511                        .setPackage(packageName);
11512                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11513                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11514            }
11515        } catch (RemoteException e) {
11516            // shouldn't happen
11517            Slog.w(TAG, "Unable to bootstrap installed package", e);
11518        }
11519    }
11520
11521    @Override
11522    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11523            int userId) {
11524        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11525        PackageSetting pkgSetting;
11526        final int uid = Binder.getCallingUid();
11527        enforceCrossUserPermission(uid, userId,
11528                true /* requireFullPermission */, true /* checkShell */,
11529                "setApplicationHiddenSetting for user " + userId);
11530
11531        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11532            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11533            return false;
11534        }
11535
11536        long callingId = Binder.clearCallingIdentity();
11537        try {
11538            boolean sendAdded = false;
11539            boolean sendRemoved = false;
11540            // writer
11541            synchronized (mPackages) {
11542                pkgSetting = mSettings.mPackages.get(packageName);
11543                if (pkgSetting == null) {
11544                    return false;
11545                }
11546                // Do not allow "android" is being disabled
11547                if ("android".equals(packageName)) {
11548                    Slog.w(TAG, "Cannot hide package: android");
11549                    return false;
11550                }
11551                // Only allow protected packages to hide themselves.
11552                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11553                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11554                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11555                    return false;
11556                }
11557
11558                if (pkgSetting.getHidden(userId) != hidden) {
11559                    pkgSetting.setHidden(hidden, userId);
11560                    mSettings.writePackageRestrictionsLPr(userId);
11561                    if (hidden) {
11562                        sendRemoved = true;
11563                    } else {
11564                        sendAdded = true;
11565                    }
11566                }
11567            }
11568            if (sendAdded) {
11569                sendPackageAddedForUser(packageName, pkgSetting, userId);
11570                return true;
11571            }
11572            if (sendRemoved) {
11573                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11574                        "hiding pkg");
11575                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11576                return true;
11577            }
11578        } finally {
11579            Binder.restoreCallingIdentity(callingId);
11580        }
11581        return false;
11582    }
11583
11584    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11585            int userId) {
11586        final PackageRemovedInfo info = new PackageRemovedInfo();
11587        info.removedPackage = packageName;
11588        info.removedUsers = new int[] {userId};
11589        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11590        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11591    }
11592
11593    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11594        if (pkgList.length > 0) {
11595            Bundle extras = new Bundle(1);
11596            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11597
11598            sendPackageBroadcast(
11599                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11600                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11601                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11602                    new int[] {userId});
11603        }
11604    }
11605
11606    /**
11607     * Returns true if application is not found or there was an error. Otherwise it returns
11608     * the hidden state of the package for the given user.
11609     */
11610    @Override
11611    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11612        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11613        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11614                true /* requireFullPermission */, false /* checkShell */,
11615                "getApplicationHidden for user " + userId);
11616        PackageSetting pkgSetting;
11617        long callingId = Binder.clearCallingIdentity();
11618        try {
11619            // writer
11620            synchronized (mPackages) {
11621                pkgSetting = mSettings.mPackages.get(packageName);
11622                if (pkgSetting == null) {
11623                    return true;
11624                }
11625                return pkgSetting.getHidden(userId);
11626            }
11627        } finally {
11628            Binder.restoreCallingIdentity(callingId);
11629        }
11630    }
11631
11632    /**
11633     * @hide
11634     */
11635    @Override
11636    public int installExistingPackageAsUser(String packageName, int userId) {
11637        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11638                null);
11639        PackageSetting pkgSetting;
11640        final int uid = Binder.getCallingUid();
11641        enforceCrossUserPermission(uid, userId,
11642                true /* requireFullPermission */, true /* checkShell */,
11643                "installExistingPackage for user " + userId);
11644        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11645            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11646        }
11647
11648        long callingId = Binder.clearCallingIdentity();
11649        try {
11650            boolean installed = false;
11651
11652            // writer
11653            synchronized (mPackages) {
11654                pkgSetting = mSettings.mPackages.get(packageName);
11655                if (pkgSetting == null) {
11656                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11657                }
11658                if (!pkgSetting.getInstalled(userId)) {
11659                    pkgSetting.setInstalled(true, userId);
11660                    pkgSetting.setHidden(false, userId);
11661                    mSettings.writePackageRestrictionsLPr(userId);
11662                    installed = true;
11663                }
11664            }
11665
11666            if (installed) {
11667                if (pkgSetting.pkg != null) {
11668                    synchronized (mInstallLock) {
11669                        // We don't need to freeze for a brand new install
11670                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11671                    }
11672                }
11673                sendPackageAddedForUser(packageName, pkgSetting, userId);
11674            }
11675        } finally {
11676            Binder.restoreCallingIdentity(callingId);
11677        }
11678
11679        return PackageManager.INSTALL_SUCCEEDED;
11680    }
11681
11682    boolean isUserRestricted(int userId, String restrictionKey) {
11683        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11684        if (restrictions.getBoolean(restrictionKey, false)) {
11685            Log.w(TAG, "User is restricted: " + restrictionKey);
11686            return true;
11687        }
11688        return false;
11689    }
11690
11691    @Override
11692    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11693            int userId) {
11694        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11695        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11696                true /* requireFullPermission */, true /* checkShell */,
11697                "setPackagesSuspended for user " + userId);
11698
11699        if (ArrayUtils.isEmpty(packageNames)) {
11700            return packageNames;
11701        }
11702
11703        // List of package names for whom the suspended state has changed.
11704        List<String> changedPackages = new ArrayList<>(packageNames.length);
11705        // List of package names for whom the suspended state is not set as requested in this
11706        // method.
11707        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11708        long callingId = Binder.clearCallingIdentity();
11709        try {
11710            for (int i = 0; i < packageNames.length; i++) {
11711                String packageName = packageNames[i];
11712                boolean changed = false;
11713                final int appId;
11714                synchronized (mPackages) {
11715                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11716                    if (pkgSetting == null) {
11717                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11718                                + "\". Skipping suspending/un-suspending.");
11719                        unactionedPackages.add(packageName);
11720                        continue;
11721                    }
11722                    appId = pkgSetting.appId;
11723                    if (pkgSetting.getSuspended(userId) != suspended) {
11724                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11725                            unactionedPackages.add(packageName);
11726                            continue;
11727                        }
11728                        pkgSetting.setSuspended(suspended, userId);
11729                        mSettings.writePackageRestrictionsLPr(userId);
11730                        changed = true;
11731                        changedPackages.add(packageName);
11732                    }
11733                }
11734
11735                if (changed && suspended) {
11736                    killApplication(packageName, UserHandle.getUid(userId, appId),
11737                            "suspending package");
11738                }
11739            }
11740        } finally {
11741            Binder.restoreCallingIdentity(callingId);
11742        }
11743
11744        if (!changedPackages.isEmpty()) {
11745            sendPackagesSuspendedForUser(changedPackages.toArray(
11746                    new String[changedPackages.size()]), userId, suspended);
11747        }
11748
11749        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11750    }
11751
11752    @Override
11753    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11754        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11755                true /* requireFullPermission */, false /* checkShell */,
11756                "isPackageSuspendedForUser for user " + userId);
11757        synchronized (mPackages) {
11758            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11759            if (pkgSetting == null) {
11760                throw new IllegalArgumentException("Unknown target package: " + packageName);
11761            }
11762            return pkgSetting.getSuspended(userId);
11763        }
11764    }
11765
11766    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11767        if (isPackageDeviceAdmin(packageName, userId)) {
11768            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11769                    + "\": has an active device admin");
11770            return false;
11771        }
11772
11773        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11774        if (packageName.equals(activeLauncherPackageName)) {
11775            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11776                    + "\": contains the active launcher");
11777            return false;
11778        }
11779
11780        if (packageName.equals(mRequiredInstallerPackage)) {
11781            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11782                    + "\": required for package installation");
11783            return false;
11784        }
11785
11786        if (packageName.equals(mRequiredUninstallerPackage)) {
11787            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11788                    + "\": required for package uninstallation");
11789            return false;
11790        }
11791
11792        if (packageName.equals(mRequiredVerifierPackage)) {
11793            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11794                    + "\": required for package verification");
11795            return false;
11796        }
11797
11798        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11799            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11800                    + "\": is the default dialer");
11801            return false;
11802        }
11803
11804        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11805            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11806                    + "\": protected package");
11807            return false;
11808        }
11809
11810        return true;
11811    }
11812
11813    private String getActiveLauncherPackageName(int userId) {
11814        Intent intent = new Intent(Intent.ACTION_MAIN);
11815        intent.addCategory(Intent.CATEGORY_HOME);
11816        ResolveInfo resolveInfo = resolveIntent(
11817                intent,
11818                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11819                PackageManager.MATCH_DEFAULT_ONLY,
11820                userId);
11821
11822        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11823    }
11824
11825    private String getDefaultDialerPackageName(int userId) {
11826        synchronized (mPackages) {
11827            return mSettings.getDefaultDialerPackageNameLPw(userId);
11828        }
11829    }
11830
11831    @Override
11832    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11833        mContext.enforceCallingOrSelfPermission(
11834                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11835                "Only package verification agents can verify applications");
11836
11837        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11838        final PackageVerificationResponse response = new PackageVerificationResponse(
11839                verificationCode, Binder.getCallingUid());
11840        msg.arg1 = id;
11841        msg.obj = response;
11842        mHandler.sendMessage(msg);
11843    }
11844
11845    @Override
11846    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11847            long millisecondsToDelay) {
11848        mContext.enforceCallingOrSelfPermission(
11849                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11850                "Only package verification agents can extend verification timeouts");
11851
11852        final PackageVerificationState state = mPendingVerification.get(id);
11853        final PackageVerificationResponse response = new PackageVerificationResponse(
11854                verificationCodeAtTimeout, Binder.getCallingUid());
11855
11856        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11857            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11858        }
11859        if (millisecondsToDelay < 0) {
11860            millisecondsToDelay = 0;
11861        }
11862        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11863                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11864            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11865        }
11866
11867        if ((state != null) && !state.timeoutExtended()) {
11868            state.extendTimeout();
11869
11870            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11871            msg.arg1 = id;
11872            msg.obj = response;
11873            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11874        }
11875    }
11876
11877    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11878            int verificationCode, UserHandle user) {
11879        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11880        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11881        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11882        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11883        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11884
11885        mContext.sendBroadcastAsUser(intent, user,
11886                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11887    }
11888
11889    private ComponentName matchComponentForVerifier(String packageName,
11890            List<ResolveInfo> receivers) {
11891        ActivityInfo targetReceiver = null;
11892
11893        final int NR = receivers.size();
11894        for (int i = 0; i < NR; i++) {
11895            final ResolveInfo info = receivers.get(i);
11896            if (info.activityInfo == null) {
11897                continue;
11898            }
11899
11900            if (packageName.equals(info.activityInfo.packageName)) {
11901                targetReceiver = info.activityInfo;
11902                break;
11903            }
11904        }
11905
11906        if (targetReceiver == null) {
11907            return null;
11908        }
11909
11910        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11911    }
11912
11913    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11914            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11915        if (pkgInfo.verifiers.length == 0) {
11916            return null;
11917        }
11918
11919        final int N = pkgInfo.verifiers.length;
11920        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11921        for (int i = 0; i < N; i++) {
11922            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11923
11924            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11925                    receivers);
11926            if (comp == null) {
11927                continue;
11928            }
11929
11930            final int verifierUid = getUidForVerifier(verifierInfo);
11931            if (verifierUid == -1) {
11932                continue;
11933            }
11934
11935            if (DEBUG_VERIFY) {
11936                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11937                        + " with the correct signature");
11938            }
11939            sufficientVerifiers.add(comp);
11940            verificationState.addSufficientVerifier(verifierUid);
11941        }
11942
11943        return sufficientVerifiers;
11944    }
11945
11946    private int getUidForVerifier(VerifierInfo verifierInfo) {
11947        synchronized (mPackages) {
11948            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11949            if (pkg == null) {
11950                return -1;
11951            } else if (pkg.mSignatures.length != 1) {
11952                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11953                        + " has more than one signature; ignoring");
11954                return -1;
11955            }
11956
11957            /*
11958             * If the public key of the package's signature does not match
11959             * our expected public key, then this is a different package and
11960             * we should skip.
11961             */
11962
11963            final byte[] expectedPublicKey;
11964            try {
11965                final Signature verifierSig = pkg.mSignatures[0];
11966                final PublicKey publicKey = verifierSig.getPublicKey();
11967                expectedPublicKey = publicKey.getEncoded();
11968            } catch (CertificateException e) {
11969                return -1;
11970            }
11971
11972            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11973
11974            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11975                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11976                        + " does not have the expected public key; ignoring");
11977                return -1;
11978            }
11979
11980            return pkg.applicationInfo.uid;
11981        }
11982    }
11983
11984    @Override
11985    public void finishPackageInstall(int token, boolean didLaunch) {
11986        enforceSystemOrRoot("Only the system is allowed to finish installs");
11987
11988        if (DEBUG_INSTALL) {
11989            Slog.v(TAG, "BM finishing package install for " + token);
11990        }
11991        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11992
11993        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11994        mHandler.sendMessage(msg);
11995    }
11996
11997    /**
11998     * Get the verification agent timeout.
11999     *
12000     * @return verification timeout in milliseconds
12001     */
12002    private long getVerificationTimeout() {
12003        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12004                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12005                DEFAULT_VERIFICATION_TIMEOUT);
12006    }
12007
12008    /**
12009     * Get the default verification agent response code.
12010     *
12011     * @return default verification response code
12012     */
12013    private int getDefaultVerificationResponse() {
12014        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12015                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12016                DEFAULT_VERIFICATION_RESPONSE);
12017    }
12018
12019    /**
12020     * Check whether or not package verification has been enabled.
12021     *
12022     * @return true if verification should be performed
12023     */
12024    private boolean isVerificationEnabled(int userId, int installFlags) {
12025        if (!DEFAULT_VERIFY_ENABLE) {
12026            return false;
12027        }
12028        // Ephemeral apps don't get the full verification treatment
12029        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12030            if (DEBUG_EPHEMERAL) {
12031                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12032            }
12033            return false;
12034        }
12035
12036        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12037
12038        // Check if installing from ADB
12039        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12040            // Do not run verification in a test harness environment
12041            if (ActivityManager.isRunningInTestHarness()) {
12042                return false;
12043            }
12044            if (ensureVerifyAppsEnabled) {
12045                return true;
12046            }
12047            // Check if the developer does not want package verification for ADB installs
12048            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12049                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12050                return false;
12051            }
12052        }
12053
12054        if (ensureVerifyAppsEnabled) {
12055            return true;
12056        }
12057
12058        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12059                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12060    }
12061
12062    @Override
12063    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12064            throws RemoteException {
12065        mContext.enforceCallingOrSelfPermission(
12066                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12067                "Only intentfilter verification agents can verify applications");
12068
12069        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12070        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12071                Binder.getCallingUid(), verificationCode, failedDomains);
12072        msg.arg1 = id;
12073        msg.obj = response;
12074        mHandler.sendMessage(msg);
12075    }
12076
12077    @Override
12078    public int getIntentVerificationStatus(String packageName, int userId) {
12079        synchronized (mPackages) {
12080            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12081        }
12082    }
12083
12084    @Override
12085    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12086        mContext.enforceCallingOrSelfPermission(
12087                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12088
12089        boolean result = false;
12090        synchronized (mPackages) {
12091            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12092        }
12093        if (result) {
12094            scheduleWritePackageRestrictionsLocked(userId);
12095        }
12096        return result;
12097    }
12098
12099    @Override
12100    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12101            String packageName) {
12102        synchronized (mPackages) {
12103            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12104        }
12105    }
12106
12107    @Override
12108    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12109        if (TextUtils.isEmpty(packageName)) {
12110            return ParceledListSlice.emptyList();
12111        }
12112        synchronized (mPackages) {
12113            PackageParser.Package pkg = mPackages.get(packageName);
12114            if (pkg == null || pkg.activities == null) {
12115                return ParceledListSlice.emptyList();
12116            }
12117            final int count = pkg.activities.size();
12118            ArrayList<IntentFilter> result = new ArrayList<>();
12119            for (int n=0; n<count; n++) {
12120                PackageParser.Activity activity = pkg.activities.get(n);
12121                if (activity.intents != null && activity.intents.size() > 0) {
12122                    result.addAll(activity.intents);
12123                }
12124            }
12125            return new ParceledListSlice<>(result);
12126        }
12127    }
12128
12129    @Override
12130    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12131        mContext.enforceCallingOrSelfPermission(
12132                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12133
12134        synchronized (mPackages) {
12135            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12136            if (packageName != null) {
12137                result |= updateIntentVerificationStatus(packageName,
12138                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12139                        userId);
12140                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12141                        packageName, userId);
12142            }
12143            return result;
12144        }
12145    }
12146
12147    @Override
12148    public String getDefaultBrowserPackageName(int userId) {
12149        synchronized (mPackages) {
12150            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12151        }
12152    }
12153
12154    /**
12155     * Get the "allow unknown sources" setting.
12156     *
12157     * @return the current "allow unknown sources" setting
12158     */
12159    private int getUnknownSourcesSettings() {
12160        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12161                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12162                -1);
12163    }
12164
12165    @Override
12166    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12167        final int uid = Binder.getCallingUid();
12168        // writer
12169        synchronized (mPackages) {
12170            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12171            if (targetPackageSetting == null) {
12172                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12173            }
12174
12175            PackageSetting installerPackageSetting;
12176            if (installerPackageName != null) {
12177                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12178                if (installerPackageSetting == null) {
12179                    throw new IllegalArgumentException("Unknown installer package: "
12180                            + installerPackageName);
12181                }
12182            } else {
12183                installerPackageSetting = null;
12184            }
12185
12186            Signature[] callerSignature;
12187            Object obj = mSettings.getUserIdLPr(uid);
12188            if (obj != null) {
12189                if (obj instanceof SharedUserSetting) {
12190                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12191                } else if (obj instanceof PackageSetting) {
12192                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12193                } else {
12194                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12195                }
12196            } else {
12197                throw new SecurityException("Unknown calling UID: " + uid);
12198            }
12199
12200            // Verify: can't set installerPackageName to a package that is
12201            // not signed with the same cert as the caller.
12202            if (installerPackageSetting != null) {
12203                if (compareSignatures(callerSignature,
12204                        installerPackageSetting.signatures.mSignatures)
12205                        != PackageManager.SIGNATURE_MATCH) {
12206                    throw new SecurityException(
12207                            "Caller does not have same cert as new installer package "
12208                            + installerPackageName);
12209                }
12210            }
12211
12212            // Verify: if target already has an installer package, it must
12213            // be signed with the same cert as the caller.
12214            if (targetPackageSetting.installerPackageName != null) {
12215                PackageSetting setting = mSettings.mPackages.get(
12216                        targetPackageSetting.installerPackageName);
12217                // If the currently set package isn't valid, then it's always
12218                // okay to change it.
12219                if (setting != null) {
12220                    if (compareSignatures(callerSignature,
12221                            setting.signatures.mSignatures)
12222                            != PackageManager.SIGNATURE_MATCH) {
12223                        throw new SecurityException(
12224                                "Caller does not have same cert as old installer package "
12225                                + targetPackageSetting.installerPackageName);
12226                    }
12227                }
12228            }
12229
12230            // Okay!
12231            targetPackageSetting.installerPackageName = installerPackageName;
12232            if (installerPackageName != null) {
12233                mSettings.mInstallerPackages.add(installerPackageName);
12234            }
12235            scheduleWriteSettingsLocked();
12236        }
12237    }
12238
12239    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12240        // Queue up an async operation since the package installation may take a little while.
12241        mHandler.post(new Runnable() {
12242            public void run() {
12243                mHandler.removeCallbacks(this);
12244                 // Result object to be returned
12245                PackageInstalledInfo res = new PackageInstalledInfo();
12246                res.setReturnCode(currentStatus);
12247                res.uid = -1;
12248                res.pkg = null;
12249                res.removedInfo = null;
12250                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12251                    args.doPreInstall(res.returnCode);
12252                    synchronized (mInstallLock) {
12253                        installPackageTracedLI(args, res);
12254                    }
12255                    args.doPostInstall(res.returnCode, res.uid);
12256                }
12257
12258                // A restore should be performed at this point if (a) the install
12259                // succeeded, (b) the operation is not an update, and (c) the new
12260                // package has not opted out of backup participation.
12261                final boolean update = res.removedInfo != null
12262                        && res.removedInfo.removedPackage != null;
12263                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12264                boolean doRestore = !update
12265                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12266
12267                // Set up the post-install work request bookkeeping.  This will be used
12268                // and cleaned up by the post-install event handling regardless of whether
12269                // there's a restore pass performed.  Token values are >= 1.
12270                int token;
12271                if (mNextInstallToken < 0) mNextInstallToken = 1;
12272                token = mNextInstallToken++;
12273
12274                PostInstallData data = new PostInstallData(args, res);
12275                mRunningInstalls.put(token, data);
12276                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12277
12278                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12279                    // Pass responsibility to the Backup Manager.  It will perform a
12280                    // restore if appropriate, then pass responsibility back to the
12281                    // Package Manager to run the post-install observer callbacks
12282                    // and broadcasts.
12283                    IBackupManager bm = IBackupManager.Stub.asInterface(
12284                            ServiceManager.getService(Context.BACKUP_SERVICE));
12285                    if (bm != null) {
12286                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12287                                + " to BM for possible restore");
12288                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12289                        try {
12290                            // TODO: http://b/22388012
12291                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12292                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12293                            } else {
12294                                doRestore = false;
12295                            }
12296                        } catch (RemoteException e) {
12297                            // can't happen; the backup manager is local
12298                        } catch (Exception e) {
12299                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12300                            doRestore = false;
12301                        }
12302                    } else {
12303                        Slog.e(TAG, "Backup Manager not found!");
12304                        doRestore = false;
12305                    }
12306                }
12307
12308                if (!doRestore) {
12309                    // No restore possible, or the Backup Manager was mysteriously not
12310                    // available -- just fire the post-install work request directly.
12311                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12312
12313                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12314
12315                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12316                    mHandler.sendMessage(msg);
12317                }
12318            }
12319        });
12320    }
12321
12322    /**
12323     * Callback from PackageSettings whenever an app is first transitioned out of the
12324     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12325     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12326     * here whether the app is the target of an ongoing install, and only send the
12327     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12328     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12329     * handling.
12330     */
12331    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12332        // Serialize this with the rest of the install-process message chain.  In the
12333        // restore-at-install case, this Runnable will necessarily run before the
12334        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12335        // are coherent.  In the non-restore case, the app has already completed install
12336        // and been launched through some other means, so it is not in a problematic
12337        // state for observers to see the FIRST_LAUNCH signal.
12338        mHandler.post(new Runnable() {
12339            @Override
12340            public void run() {
12341                for (int i = 0; i < mRunningInstalls.size(); i++) {
12342                    final PostInstallData data = mRunningInstalls.valueAt(i);
12343                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12344                        continue;
12345                    }
12346                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12347                        // right package; but is it for the right user?
12348                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12349                            if (userId == data.res.newUsers[uIndex]) {
12350                                if (DEBUG_BACKUP) {
12351                                    Slog.i(TAG, "Package " + pkgName
12352                                            + " being restored so deferring FIRST_LAUNCH");
12353                                }
12354                                return;
12355                            }
12356                        }
12357                    }
12358                }
12359                // didn't find it, so not being restored
12360                if (DEBUG_BACKUP) {
12361                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12362                }
12363                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12364            }
12365        });
12366    }
12367
12368    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12369        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12370                installerPkg, null, userIds);
12371    }
12372
12373    private abstract class HandlerParams {
12374        private static final int MAX_RETRIES = 4;
12375
12376        /**
12377         * Number of times startCopy() has been attempted and had a non-fatal
12378         * error.
12379         */
12380        private int mRetries = 0;
12381
12382        /** User handle for the user requesting the information or installation. */
12383        private final UserHandle mUser;
12384        String traceMethod;
12385        int traceCookie;
12386
12387        HandlerParams(UserHandle user) {
12388            mUser = user;
12389        }
12390
12391        UserHandle getUser() {
12392            return mUser;
12393        }
12394
12395        HandlerParams setTraceMethod(String traceMethod) {
12396            this.traceMethod = traceMethod;
12397            return this;
12398        }
12399
12400        HandlerParams setTraceCookie(int traceCookie) {
12401            this.traceCookie = traceCookie;
12402            return this;
12403        }
12404
12405        final boolean startCopy() {
12406            boolean res;
12407            try {
12408                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12409
12410                if (++mRetries > MAX_RETRIES) {
12411                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12412                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12413                    handleServiceError();
12414                    return false;
12415                } else {
12416                    handleStartCopy();
12417                    res = true;
12418                }
12419            } catch (RemoteException e) {
12420                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12421                mHandler.sendEmptyMessage(MCS_RECONNECT);
12422                res = false;
12423            }
12424            handleReturnCode();
12425            return res;
12426        }
12427
12428        final void serviceError() {
12429            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12430            handleServiceError();
12431            handleReturnCode();
12432        }
12433
12434        abstract void handleStartCopy() throws RemoteException;
12435        abstract void handleServiceError();
12436        abstract void handleReturnCode();
12437    }
12438
12439    class MeasureParams extends HandlerParams {
12440        private final PackageStats mStats;
12441        private boolean mSuccess;
12442
12443        private final IPackageStatsObserver mObserver;
12444
12445        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12446            super(new UserHandle(stats.userHandle));
12447            mObserver = observer;
12448            mStats = stats;
12449        }
12450
12451        @Override
12452        public String toString() {
12453            return "MeasureParams{"
12454                + Integer.toHexString(System.identityHashCode(this))
12455                + " " + mStats.packageName + "}";
12456        }
12457
12458        @Override
12459        void handleStartCopy() throws RemoteException {
12460            synchronized (mInstallLock) {
12461                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12462            }
12463
12464            if (mSuccess) {
12465                boolean mounted = false;
12466                try {
12467                    final String status = Environment.getExternalStorageState();
12468                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12469                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12470                } catch (Exception e) {
12471                }
12472
12473                if (mounted) {
12474                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12475
12476                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12477                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12478
12479                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12480                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12481
12482                    // Always subtract cache size, since it's a subdirectory
12483                    mStats.externalDataSize -= mStats.externalCacheSize;
12484
12485                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12486                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12487
12488                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12489                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12490                }
12491            }
12492        }
12493
12494        @Override
12495        void handleReturnCode() {
12496            if (mObserver != null) {
12497                try {
12498                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12499                } catch (RemoteException e) {
12500                    Slog.i(TAG, "Observer no longer exists.");
12501                }
12502            }
12503        }
12504
12505        @Override
12506        void handleServiceError() {
12507            Slog.e(TAG, "Could not measure application " + mStats.packageName
12508                            + " external storage");
12509        }
12510    }
12511
12512    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12513            throws RemoteException {
12514        long result = 0;
12515        for (File path : paths) {
12516            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12517        }
12518        return result;
12519    }
12520
12521    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12522        for (File path : paths) {
12523            try {
12524                mcs.clearDirectory(path.getAbsolutePath());
12525            } catch (RemoteException e) {
12526            }
12527        }
12528    }
12529
12530    static class OriginInfo {
12531        /**
12532         * Location where install is coming from, before it has been
12533         * copied/renamed into place. This could be a single monolithic APK
12534         * file, or a cluster directory. This location may be untrusted.
12535         */
12536        final File file;
12537        final String cid;
12538
12539        /**
12540         * Flag indicating that {@link #file} or {@link #cid} has already been
12541         * staged, meaning downstream users don't need to defensively copy the
12542         * contents.
12543         */
12544        final boolean staged;
12545
12546        /**
12547         * Flag indicating that {@link #file} or {@link #cid} is an already
12548         * installed app that is being moved.
12549         */
12550        final boolean existing;
12551
12552        final String resolvedPath;
12553        final File resolvedFile;
12554
12555        static OriginInfo fromNothing() {
12556            return new OriginInfo(null, null, false, false);
12557        }
12558
12559        static OriginInfo fromUntrustedFile(File file) {
12560            return new OriginInfo(file, null, false, false);
12561        }
12562
12563        static OriginInfo fromExistingFile(File file) {
12564            return new OriginInfo(file, null, false, true);
12565        }
12566
12567        static OriginInfo fromStagedFile(File file) {
12568            return new OriginInfo(file, null, true, false);
12569        }
12570
12571        static OriginInfo fromStagedContainer(String cid) {
12572            return new OriginInfo(null, cid, true, false);
12573        }
12574
12575        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12576            this.file = file;
12577            this.cid = cid;
12578            this.staged = staged;
12579            this.existing = existing;
12580
12581            if (cid != null) {
12582                resolvedPath = PackageHelper.getSdDir(cid);
12583                resolvedFile = new File(resolvedPath);
12584            } else if (file != null) {
12585                resolvedPath = file.getAbsolutePath();
12586                resolvedFile = file;
12587            } else {
12588                resolvedPath = null;
12589                resolvedFile = null;
12590            }
12591        }
12592    }
12593
12594    static class MoveInfo {
12595        final int moveId;
12596        final String fromUuid;
12597        final String toUuid;
12598        final String packageName;
12599        final String dataAppName;
12600        final int appId;
12601        final String seinfo;
12602        final int targetSdkVersion;
12603
12604        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12605                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12606            this.moveId = moveId;
12607            this.fromUuid = fromUuid;
12608            this.toUuid = toUuid;
12609            this.packageName = packageName;
12610            this.dataAppName = dataAppName;
12611            this.appId = appId;
12612            this.seinfo = seinfo;
12613            this.targetSdkVersion = targetSdkVersion;
12614        }
12615    }
12616
12617    static class VerificationInfo {
12618        /** A constant used to indicate that a uid value is not present. */
12619        public static final int NO_UID = -1;
12620
12621        /** URI referencing where the package was downloaded from. */
12622        final Uri originatingUri;
12623
12624        /** HTTP referrer URI associated with the originatingURI. */
12625        final Uri referrer;
12626
12627        /** UID of the application that the install request originated from. */
12628        final int originatingUid;
12629
12630        /** UID of application requesting the install */
12631        final int installerUid;
12632
12633        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12634            this.originatingUri = originatingUri;
12635            this.referrer = referrer;
12636            this.originatingUid = originatingUid;
12637            this.installerUid = installerUid;
12638        }
12639    }
12640
12641    class InstallParams extends HandlerParams {
12642        final OriginInfo origin;
12643        final MoveInfo move;
12644        final IPackageInstallObserver2 observer;
12645        int installFlags;
12646        final String installerPackageName;
12647        final String volumeUuid;
12648        private InstallArgs mArgs;
12649        private int mRet;
12650        final String packageAbiOverride;
12651        final String[] grantedRuntimePermissions;
12652        final VerificationInfo verificationInfo;
12653        final Certificate[][] certificates;
12654
12655        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12656                int installFlags, String installerPackageName, String volumeUuid,
12657                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12658                String[] grantedPermissions, Certificate[][] certificates) {
12659            super(user);
12660            this.origin = origin;
12661            this.move = move;
12662            this.observer = observer;
12663            this.installFlags = installFlags;
12664            this.installerPackageName = installerPackageName;
12665            this.volumeUuid = volumeUuid;
12666            this.verificationInfo = verificationInfo;
12667            this.packageAbiOverride = packageAbiOverride;
12668            this.grantedRuntimePermissions = grantedPermissions;
12669            this.certificates = certificates;
12670        }
12671
12672        @Override
12673        public String toString() {
12674            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12675                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12676        }
12677
12678        private int installLocationPolicy(PackageInfoLite pkgLite) {
12679            String packageName = pkgLite.packageName;
12680            int installLocation = pkgLite.installLocation;
12681            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12682            // reader
12683            synchronized (mPackages) {
12684                // Currently installed package which the new package is attempting to replace or
12685                // null if no such package is installed.
12686                PackageParser.Package installedPkg = mPackages.get(packageName);
12687                // Package which currently owns the data which the new package will own if installed.
12688                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12689                // will be null whereas dataOwnerPkg will contain information about the package
12690                // which was uninstalled while keeping its data.
12691                PackageParser.Package dataOwnerPkg = installedPkg;
12692                if (dataOwnerPkg  == null) {
12693                    PackageSetting ps = mSettings.mPackages.get(packageName);
12694                    if (ps != null) {
12695                        dataOwnerPkg = ps.pkg;
12696                    }
12697                }
12698
12699                if (dataOwnerPkg != null) {
12700                    // If installed, the package will get access to data left on the device by its
12701                    // predecessor. As a security measure, this is permited only if this is not a
12702                    // version downgrade or if the predecessor package is marked as debuggable and
12703                    // a downgrade is explicitly requested.
12704                    //
12705                    // On debuggable platform builds, downgrades are permitted even for
12706                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12707                    // not offer security guarantees and thus it's OK to disable some security
12708                    // mechanisms to make debugging/testing easier on those builds. However, even on
12709                    // debuggable builds downgrades of packages are permitted only if requested via
12710                    // installFlags. This is because we aim to keep the behavior of debuggable
12711                    // platform builds as close as possible to the behavior of non-debuggable
12712                    // platform builds.
12713                    final boolean downgradeRequested =
12714                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12715                    final boolean packageDebuggable =
12716                                (dataOwnerPkg.applicationInfo.flags
12717                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12718                    final boolean downgradePermitted =
12719                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12720                    if (!downgradePermitted) {
12721                        try {
12722                            checkDowngrade(dataOwnerPkg, pkgLite);
12723                        } catch (PackageManagerException e) {
12724                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12725                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12726                        }
12727                    }
12728                }
12729
12730                if (installedPkg != null) {
12731                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12732                        // Check for updated system application.
12733                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12734                            if (onSd) {
12735                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12736                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12737                            }
12738                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12739                        } else {
12740                            if (onSd) {
12741                                // Install flag overrides everything.
12742                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12743                            }
12744                            // If current upgrade specifies particular preference
12745                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12746                                // Application explicitly specified internal.
12747                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12748                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12749                                // App explictly prefers external. Let policy decide
12750                            } else {
12751                                // Prefer previous location
12752                                if (isExternal(installedPkg)) {
12753                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12754                                }
12755                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12756                            }
12757                        }
12758                    } else {
12759                        // Invalid install. Return error code
12760                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12761                    }
12762                }
12763            }
12764            // All the special cases have been taken care of.
12765            // Return result based on recommended install location.
12766            if (onSd) {
12767                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12768            }
12769            return pkgLite.recommendedInstallLocation;
12770        }
12771
12772        /*
12773         * Invoke remote method to get package information and install
12774         * location values. Override install location based on default
12775         * policy if needed and then create install arguments based
12776         * on the install location.
12777         */
12778        public void handleStartCopy() throws RemoteException {
12779            int ret = PackageManager.INSTALL_SUCCEEDED;
12780
12781            // If we're already staged, we've firmly committed to an install location
12782            if (origin.staged) {
12783                if (origin.file != null) {
12784                    installFlags |= PackageManager.INSTALL_INTERNAL;
12785                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12786                } else if (origin.cid != null) {
12787                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12788                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12789                } else {
12790                    throw new IllegalStateException("Invalid stage location");
12791                }
12792            }
12793
12794            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12795            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12796            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12797            PackageInfoLite pkgLite = null;
12798
12799            if (onInt && onSd) {
12800                // Check if both bits are set.
12801                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12802                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12803            } else if (onSd && ephemeral) {
12804                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12805                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12806            } else {
12807                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12808                        packageAbiOverride);
12809
12810                if (DEBUG_EPHEMERAL && ephemeral) {
12811                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12812                }
12813
12814                /*
12815                 * If we have too little free space, try to free cache
12816                 * before giving up.
12817                 */
12818                if (!origin.staged && pkgLite.recommendedInstallLocation
12819                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12820                    // TODO: focus freeing disk space on the target device
12821                    final StorageManager storage = StorageManager.from(mContext);
12822                    final long lowThreshold = storage.getStorageLowBytes(
12823                            Environment.getDataDirectory());
12824
12825                    final long sizeBytes = mContainerService.calculateInstalledSize(
12826                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12827
12828                    try {
12829                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12830                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12831                                installFlags, packageAbiOverride);
12832                    } catch (InstallerException e) {
12833                        Slog.w(TAG, "Failed to free cache", e);
12834                    }
12835
12836                    /*
12837                     * The cache free must have deleted the file we
12838                     * downloaded to install.
12839                     *
12840                     * TODO: fix the "freeCache" call to not delete
12841                     *       the file we care about.
12842                     */
12843                    if (pkgLite.recommendedInstallLocation
12844                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12845                        pkgLite.recommendedInstallLocation
12846                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12847                    }
12848                }
12849            }
12850
12851            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12852                int loc = pkgLite.recommendedInstallLocation;
12853                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12854                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12855                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12856                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12857                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12858                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12859                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12860                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12861                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12862                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12863                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12864                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12865                } else {
12866                    // Override with defaults if needed.
12867                    loc = installLocationPolicy(pkgLite);
12868                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12869                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12870                    } else if (!onSd && !onInt) {
12871                        // Override install location with flags
12872                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12873                            // Set the flag to install on external media.
12874                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12875                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12876                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12877                            if (DEBUG_EPHEMERAL) {
12878                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12879                            }
12880                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12881                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12882                                    |PackageManager.INSTALL_INTERNAL);
12883                        } else {
12884                            // Make sure the flag for installing on external
12885                            // media is unset
12886                            installFlags |= PackageManager.INSTALL_INTERNAL;
12887                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12888                        }
12889                    }
12890                }
12891            }
12892
12893            final InstallArgs args = createInstallArgs(this);
12894            mArgs = args;
12895
12896            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12897                // TODO: http://b/22976637
12898                // Apps installed for "all" users use the device owner to verify the app
12899                UserHandle verifierUser = getUser();
12900                if (verifierUser == UserHandle.ALL) {
12901                    verifierUser = UserHandle.SYSTEM;
12902                }
12903
12904                /*
12905                 * Determine if we have any installed package verifiers. If we
12906                 * do, then we'll defer to them to verify the packages.
12907                 */
12908                final int requiredUid = mRequiredVerifierPackage == null ? -1
12909                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12910                                verifierUser.getIdentifier());
12911                if (!origin.existing && requiredUid != -1
12912                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12913                    final Intent verification = new Intent(
12914                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12915                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12916                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12917                            PACKAGE_MIME_TYPE);
12918                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12919
12920                    // Query all live verifiers based on current user state
12921                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12922                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12923
12924                    if (DEBUG_VERIFY) {
12925                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12926                                + verification.toString() + " with " + pkgLite.verifiers.length
12927                                + " optional verifiers");
12928                    }
12929
12930                    final int verificationId = mPendingVerificationToken++;
12931
12932                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12933
12934                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12935                            installerPackageName);
12936
12937                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12938                            installFlags);
12939
12940                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12941                            pkgLite.packageName);
12942
12943                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12944                            pkgLite.versionCode);
12945
12946                    if (verificationInfo != null) {
12947                        if (verificationInfo.originatingUri != null) {
12948                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12949                                    verificationInfo.originatingUri);
12950                        }
12951                        if (verificationInfo.referrer != null) {
12952                            verification.putExtra(Intent.EXTRA_REFERRER,
12953                                    verificationInfo.referrer);
12954                        }
12955                        if (verificationInfo.originatingUid >= 0) {
12956                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12957                                    verificationInfo.originatingUid);
12958                        }
12959                        if (verificationInfo.installerUid >= 0) {
12960                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12961                                    verificationInfo.installerUid);
12962                        }
12963                    }
12964
12965                    final PackageVerificationState verificationState = new PackageVerificationState(
12966                            requiredUid, args);
12967
12968                    mPendingVerification.append(verificationId, verificationState);
12969
12970                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12971                            receivers, verificationState);
12972
12973                    /*
12974                     * If any sufficient verifiers were listed in the package
12975                     * manifest, attempt to ask them.
12976                     */
12977                    if (sufficientVerifiers != null) {
12978                        final int N = sufficientVerifiers.size();
12979                        if (N == 0) {
12980                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12981                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12982                        } else {
12983                            for (int i = 0; i < N; i++) {
12984                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12985
12986                                final Intent sufficientIntent = new Intent(verification);
12987                                sufficientIntent.setComponent(verifierComponent);
12988                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12989                            }
12990                        }
12991                    }
12992
12993                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12994                            mRequiredVerifierPackage, receivers);
12995                    if (ret == PackageManager.INSTALL_SUCCEEDED
12996                            && mRequiredVerifierPackage != null) {
12997                        Trace.asyncTraceBegin(
12998                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12999                        /*
13000                         * Send the intent to the required verification agent,
13001                         * but only start the verification timeout after the
13002                         * target BroadcastReceivers have run.
13003                         */
13004                        verification.setComponent(requiredVerifierComponent);
13005                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13006                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13007                                new BroadcastReceiver() {
13008                                    @Override
13009                                    public void onReceive(Context context, Intent intent) {
13010                                        final Message msg = mHandler
13011                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13012                                        msg.arg1 = verificationId;
13013                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13014                                    }
13015                                }, null, 0, null, null);
13016
13017                        /*
13018                         * We don't want the copy to proceed until verification
13019                         * succeeds, so null out this field.
13020                         */
13021                        mArgs = null;
13022                    }
13023                } else {
13024                    /*
13025                     * No package verification is enabled, so immediately start
13026                     * the remote call to initiate copy using temporary file.
13027                     */
13028                    ret = args.copyApk(mContainerService, true);
13029                }
13030            }
13031
13032            mRet = ret;
13033        }
13034
13035        @Override
13036        void handleReturnCode() {
13037            // If mArgs is null, then MCS couldn't be reached. When it
13038            // reconnects, it will try again to install. At that point, this
13039            // will succeed.
13040            if (mArgs != null) {
13041                processPendingInstall(mArgs, mRet);
13042            }
13043        }
13044
13045        @Override
13046        void handleServiceError() {
13047            mArgs = createInstallArgs(this);
13048            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13049        }
13050
13051        public boolean isForwardLocked() {
13052            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13053        }
13054    }
13055
13056    /**
13057     * Used during creation of InstallArgs
13058     *
13059     * @param installFlags package installation flags
13060     * @return true if should be installed on external storage
13061     */
13062    private static boolean installOnExternalAsec(int installFlags) {
13063        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13064            return false;
13065        }
13066        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13067            return true;
13068        }
13069        return false;
13070    }
13071
13072    /**
13073     * Used during creation of InstallArgs
13074     *
13075     * @param installFlags package installation flags
13076     * @return true if should be installed as forward locked
13077     */
13078    private static boolean installForwardLocked(int installFlags) {
13079        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13080    }
13081
13082    private InstallArgs createInstallArgs(InstallParams params) {
13083        if (params.move != null) {
13084            return new MoveInstallArgs(params);
13085        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13086            return new AsecInstallArgs(params);
13087        } else {
13088            return new FileInstallArgs(params);
13089        }
13090    }
13091
13092    /**
13093     * Create args that describe an existing installed package. Typically used
13094     * when cleaning up old installs, or used as a move source.
13095     */
13096    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13097            String resourcePath, String[] instructionSets) {
13098        final boolean isInAsec;
13099        if (installOnExternalAsec(installFlags)) {
13100            /* Apps on SD card are always in ASEC containers. */
13101            isInAsec = true;
13102        } else if (installForwardLocked(installFlags)
13103                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13104            /*
13105             * Forward-locked apps are only in ASEC containers if they're the
13106             * new style
13107             */
13108            isInAsec = true;
13109        } else {
13110            isInAsec = false;
13111        }
13112
13113        if (isInAsec) {
13114            return new AsecInstallArgs(codePath, instructionSets,
13115                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13116        } else {
13117            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13118        }
13119    }
13120
13121    static abstract class InstallArgs {
13122        /** @see InstallParams#origin */
13123        final OriginInfo origin;
13124        /** @see InstallParams#move */
13125        final MoveInfo move;
13126
13127        final IPackageInstallObserver2 observer;
13128        // Always refers to PackageManager flags only
13129        final int installFlags;
13130        final String installerPackageName;
13131        final String volumeUuid;
13132        final UserHandle user;
13133        final String abiOverride;
13134        final String[] installGrantPermissions;
13135        /** If non-null, drop an async trace when the install completes */
13136        final String traceMethod;
13137        final int traceCookie;
13138        final Certificate[][] certificates;
13139
13140        // The list of instruction sets supported by this app. This is currently
13141        // only used during the rmdex() phase to clean up resources. We can get rid of this
13142        // if we move dex files under the common app path.
13143        /* nullable */ String[] instructionSets;
13144
13145        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13146                int installFlags, String installerPackageName, String volumeUuid,
13147                UserHandle user, String[] instructionSets,
13148                String abiOverride, String[] installGrantPermissions,
13149                String traceMethod, int traceCookie, Certificate[][] certificates) {
13150            this.origin = origin;
13151            this.move = move;
13152            this.installFlags = installFlags;
13153            this.observer = observer;
13154            this.installerPackageName = installerPackageName;
13155            this.volumeUuid = volumeUuid;
13156            this.user = user;
13157            this.instructionSets = instructionSets;
13158            this.abiOverride = abiOverride;
13159            this.installGrantPermissions = installGrantPermissions;
13160            this.traceMethod = traceMethod;
13161            this.traceCookie = traceCookie;
13162            this.certificates = certificates;
13163        }
13164
13165        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13166        abstract int doPreInstall(int status);
13167
13168        /**
13169         * Rename package into final resting place. All paths on the given
13170         * scanned package should be updated to reflect the rename.
13171         */
13172        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13173        abstract int doPostInstall(int status, int uid);
13174
13175        /** @see PackageSettingBase#codePathString */
13176        abstract String getCodePath();
13177        /** @see PackageSettingBase#resourcePathString */
13178        abstract String getResourcePath();
13179
13180        // Need installer lock especially for dex file removal.
13181        abstract void cleanUpResourcesLI();
13182        abstract boolean doPostDeleteLI(boolean delete);
13183
13184        /**
13185         * Called before the source arguments are copied. This is used mostly
13186         * for MoveParams when it needs to read the source file to put it in the
13187         * destination.
13188         */
13189        int doPreCopy() {
13190            return PackageManager.INSTALL_SUCCEEDED;
13191        }
13192
13193        /**
13194         * Called after the source arguments are copied. This is used mostly for
13195         * MoveParams when it needs to read the source file to put it in the
13196         * destination.
13197         */
13198        int doPostCopy(int uid) {
13199            return PackageManager.INSTALL_SUCCEEDED;
13200        }
13201
13202        protected boolean isFwdLocked() {
13203            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13204        }
13205
13206        protected boolean isExternalAsec() {
13207            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13208        }
13209
13210        protected boolean isEphemeral() {
13211            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13212        }
13213
13214        UserHandle getUser() {
13215            return user;
13216        }
13217    }
13218
13219    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13220        if (!allCodePaths.isEmpty()) {
13221            if (instructionSets == null) {
13222                throw new IllegalStateException("instructionSet == null");
13223            }
13224            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13225            for (String codePath : allCodePaths) {
13226                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13227                    try {
13228                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13229                    } catch (InstallerException ignored) {
13230                    }
13231                }
13232            }
13233        }
13234    }
13235
13236    /**
13237     * Logic to handle installation of non-ASEC applications, including copying
13238     * and renaming logic.
13239     */
13240    class FileInstallArgs extends InstallArgs {
13241        private File codeFile;
13242        private File resourceFile;
13243
13244        // Example topology:
13245        // /data/app/com.example/base.apk
13246        // /data/app/com.example/split_foo.apk
13247        // /data/app/com.example/lib/arm/libfoo.so
13248        // /data/app/com.example/lib/arm64/libfoo.so
13249        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13250
13251        /** New install */
13252        FileInstallArgs(InstallParams params) {
13253            super(params.origin, params.move, params.observer, params.installFlags,
13254                    params.installerPackageName, params.volumeUuid,
13255                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13256                    params.grantedRuntimePermissions,
13257                    params.traceMethod, params.traceCookie, params.certificates);
13258            if (isFwdLocked()) {
13259                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13260            }
13261        }
13262
13263        /** Existing install */
13264        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13265            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13266                    null, null, null, 0, null /*certificates*/);
13267            this.codeFile = (codePath != null) ? new File(codePath) : null;
13268            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13269        }
13270
13271        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13272            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13273            try {
13274                return doCopyApk(imcs, temp);
13275            } finally {
13276                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13277            }
13278        }
13279
13280        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13281            if (origin.staged) {
13282                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13283                codeFile = origin.file;
13284                resourceFile = origin.file;
13285                return PackageManager.INSTALL_SUCCEEDED;
13286            }
13287
13288            try {
13289                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13290                final File tempDir =
13291                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13292                codeFile = tempDir;
13293                resourceFile = tempDir;
13294            } catch (IOException e) {
13295                Slog.w(TAG, "Failed to create copy file: " + e);
13296                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13297            }
13298
13299            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13300                @Override
13301                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13302                    if (!FileUtils.isValidExtFilename(name)) {
13303                        throw new IllegalArgumentException("Invalid filename: " + name);
13304                    }
13305                    try {
13306                        final File file = new File(codeFile, name);
13307                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13308                                O_RDWR | O_CREAT, 0644);
13309                        Os.chmod(file.getAbsolutePath(), 0644);
13310                        return new ParcelFileDescriptor(fd);
13311                    } catch (ErrnoException e) {
13312                        throw new RemoteException("Failed to open: " + e.getMessage());
13313                    }
13314                }
13315            };
13316
13317            int ret = PackageManager.INSTALL_SUCCEEDED;
13318            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13319            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13320                Slog.e(TAG, "Failed to copy package");
13321                return ret;
13322            }
13323
13324            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13325            NativeLibraryHelper.Handle handle = null;
13326            try {
13327                handle = NativeLibraryHelper.Handle.create(codeFile);
13328                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13329                        abiOverride);
13330            } catch (IOException e) {
13331                Slog.e(TAG, "Copying native libraries failed", e);
13332                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13333            } finally {
13334                IoUtils.closeQuietly(handle);
13335            }
13336
13337            return ret;
13338        }
13339
13340        int doPreInstall(int status) {
13341            if (status != PackageManager.INSTALL_SUCCEEDED) {
13342                cleanUp();
13343            }
13344            return status;
13345        }
13346
13347        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13348            if (status != PackageManager.INSTALL_SUCCEEDED) {
13349                cleanUp();
13350                return false;
13351            }
13352
13353            final File targetDir = codeFile.getParentFile();
13354            final File beforeCodeFile = codeFile;
13355            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13356
13357            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13358            try {
13359                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13360            } catch (ErrnoException e) {
13361                Slog.w(TAG, "Failed to rename", e);
13362                return false;
13363            }
13364
13365            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13366                Slog.w(TAG, "Failed to restorecon");
13367                return false;
13368            }
13369
13370            // Reflect the rename internally
13371            codeFile = afterCodeFile;
13372            resourceFile = afterCodeFile;
13373
13374            // Reflect the rename in scanned details
13375            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13376            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13377                    afterCodeFile, pkg.baseCodePath));
13378            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13379                    afterCodeFile, pkg.splitCodePaths));
13380
13381            // Reflect the rename in app info
13382            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13383            pkg.setApplicationInfoCodePath(pkg.codePath);
13384            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13385            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13386            pkg.setApplicationInfoResourcePath(pkg.codePath);
13387            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13388            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13389
13390            return true;
13391        }
13392
13393        int doPostInstall(int status, int uid) {
13394            if (status != PackageManager.INSTALL_SUCCEEDED) {
13395                cleanUp();
13396            }
13397            return status;
13398        }
13399
13400        @Override
13401        String getCodePath() {
13402            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13403        }
13404
13405        @Override
13406        String getResourcePath() {
13407            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13408        }
13409
13410        private boolean cleanUp() {
13411            if (codeFile == null || !codeFile.exists()) {
13412                return false;
13413            }
13414
13415            removeCodePathLI(codeFile);
13416
13417            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13418                resourceFile.delete();
13419            }
13420
13421            return true;
13422        }
13423
13424        void cleanUpResourcesLI() {
13425            // Try enumerating all code paths before deleting
13426            List<String> allCodePaths = Collections.EMPTY_LIST;
13427            if (codeFile != null && codeFile.exists()) {
13428                try {
13429                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13430                    allCodePaths = pkg.getAllCodePaths();
13431                } catch (PackageParserException e) {
13432                    // Ignored; we tried our best
13433                }
13434            }
13435
13436            cleanUp();
13437            removeDexFiles(allCodePaths, instructionSets);
13438        }
13439
13440        boolean doPostDeleteLI(boolean delete) {
13441            // XXX err, shouldn't we respect the delete flag?
13442            cleanUpResourcesLI();
13443            return true;
13444        }
13445    }
13446
13447    private boolean isAsecExternal(String cid) {
13448        final String asecPath = PackageHelper.getSdFilesystem(cid);
13449        return !asecPath.startsWith(mAsecInternalPath);
13450    }
13451
13452    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13453            PackageManagerException {
13454        if (copyRet < 0) {
13455            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13456                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13457                throw new PackageManagerException(copyRet, message);
13458            }
13459        }
13460    }
13461
13462    /**
13463     * Extract the MountService "container ID" from the full code path of an
13464     * .apk.
13465     */
13466    static String cidFromCodePath(String fullCodePath) {
13467        int eidx = fullCodePath.lastIndexOf("/");
13468        String subStr1 = fullCodePath.substring(0, eidx);
13469        int sidx = subStr1.lastIndexOf("/");
13470        return subStr1.substring(sidx+1, eidx);
13471    }
13472
13473    /**
13474     * Logic to handle installation of ASEC applications, including copying and
13475     * renaming logic.
13476     */
13477    class AsecInstallArgs extends InstallArgs {
13478        static final String RES_FILE_NAME = "pkg.apk";
13479        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13480
13481        String cid;
13482        String packagePath;
13483        String resourcePath;
13484
13485        /** New install */
13486        AsecInstallArgs(InstallParams params) {
13487            super(params.origin, params.move, params.observer, params.installFlags,
13488                    params.installerPackageName, params.volumeUuid,
13489                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13490                    params.grantedRuntimePermissions,
13491                    params.traceMethod, params.traceCookie, params.certificates);
13492        }
13493
13494        /** Existing install */
13495        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13496                        boolean isExternal, boolean isForwardLocked) {
13497            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13498              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13499                    instructionSets, null, null, null, 0, null /*certificates*/);
13500            // Hackily pretend we're still looking at a full code path
13501            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13502                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13503            }
13504
13505            // Extract cid from fullCodePath
13506            int eidx = fullCodePath.lastIndexOf("/");
13507            String subStr1 = fullCodePath.substring(0, eidx);
13508            int sidx = subStr1.lastIndexOf("/");
13509            cid = subStr1.substring(sidx+1, eidx);
13510            setMountPath(subStr1);
13511        }
13512
13513        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13514            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13515              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13516                    instructionSets, null, null, null, 0, null /*certificates*/);
13517            this.cid = cid;
13518            setMountPath(PackageHelper.getSdDir(cid));
13519        }
13520
13521        void createCopyFile() {
13522            cid = mInstallerService.allocateExternalStageCidLegacy();
13523        }
13524
13525        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13526            if (origin.staged && origin.cid != null) {
13527                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13528                cid = origin.cid;
13529                setMountPath(PackageHelper.getSdDir(cid));
13530                return PackageManager.INSTALL_SUCCEEDED;
13531            }
13532
13533            if (temp) {
13534                createCopyFile();
13535            } else {
13536                /*
13537                 * Pre-emptively destroy the container since it's destroyed if
13538                 * copying fails due to it existing anyway.
13539                 */
13540                PackageHelper.destroySdDir(cid);
13541            }
13542
13543            final String newMountPath = imcs.copyPackageToContainer(
13544                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13545                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13546
13547            if (newMountPath != null) {
13548                setMountPath(newMountPath);
13549                return PackageManager.INSTALL_SUCCEEDED;
13550            } else {
13551                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13552            }
13553        }
13554
13555        @Override
13556        String getCodePath() {
13557            return packagePath;
13558        }
13559
13560        @Override
13561        String getResourcePath() {
13562            return resourcePath;
13563        }
13564
13565        int doPreInstall(int status) {
13566            if (status != PackageManager.INSTALL_SUCCEEDED) {
13567                // Destroy container
13568                PackageHelper.destroySdDir(cid);
13569            } else {
13570                boolean mounted = PackageHelper.isContainerMounted(cid);
13571                if (!mounted) {
13572                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13573                            Process.SYSTEM_UID);
13574                    if (newMountPath != null) {
13575                        setMountPath(newMountPath);
13576                    } else {
13577                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13578                    }
13579                }
13580            }
13581            return status;
13582        }
13583
13584        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13585            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13586            String newMountPath = null;
13587            if (PackageHelper.isContainerMounted(cid)) {
13588                // Unmount the container
13589                if (!PackageHelper.unMountSdDir(cid)) {
13590                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13591                    return false;
13592                }
13593            }
13594            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13595                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13596                        " which might be stale. Will try to clean up.");
13597                // Clean up the stale container and proceed to recreate.
13598                if (!PackageHelper.destroySdDir(newCacheId)) {
13599                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13600                    return false;
13601                }
13602                // Successfully cleaned up stale container. Try to rename again.
13603                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13604                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13605                            + " inspite of cleaning it up.");
13606                    return false;
13607                }
13608            }
13609            if (!PackageHelper.isContainerMounted(newCacheId)) {
13610                Slog.w(TAG, "Mounting container " + newCacheId);
13611                newMountPath = PackageHelper.mountSdDir(newCacheId,
13612                        getEncryptKey(), Process.SYSTEM_UID);
13613            } else {
13614                newMountPath = PackageHelper.getSdDir(newCacheId);
13615            }
13616            if (newMountPath == null) {
13617                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13618                return false;
13619            }
13620            Log.i(TAG, "Succesfully renamed " + cid +
13621                    " to " + newCacheId +
13622                    " at new path: " + newMountPath);
13623            cid = newCacheId;
13624
13625            final File beforeCodeFile = new File(packagePath);
13626            setMountPath(newMountPath);
13627            final File afterCodeFile = new File(packagePath);
13628
13629            // Reflect the rename in scanned details
13630            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13631            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13632                    afterCodeFile, pkg.baseCodePath));
13633            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13634                    afterCodeFile, pkg.splitCodePaths));
13635
13636            // Reflect the rename in app info
13637            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13638            pkg.setApplicationInfoCodePath(pkg.codePath);
13639            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13640            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13641            pkg.setApplicationInfoResourcePath(pkg.codePath);
13642            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13643            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13644
13645            return true;
13646        }
13647
13648        private void setMountPath(String mountPath) {
13649            final File mountFile = new File(mountPath);
13650
13651            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13652            if (monolithicFile.exists()) {
13653                packagePath = monolithicFile.getAbsolutePath();
13654                if (isFwdLocked()) {
13655                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13656                } else {
13657                    resourcePath = packagePath;
13658                }
13659            } else {
13660                packagePath = mountFile.getAbsolutePath();
13661                resourcePath = packagePath;
13662            }
13663        }
13664
13665        int doPostInstall(int status, int uid) {
13666            if (status != PackageManager.INSTALL_SUCCEEDED) {
13667                cleanUp();
13668            } else {
13669                final int groupOwner;
13670                final String protectedFile;
13671                if (isFwdLocked()) {
13672                    groupOwner = UserHandle.getSharedAppGid(uid);
13673                    protectedFile = RES_FILE_NAME;
13674                } else {
13675                    groupOwner = -1;
13676                    protectedFile = null;
13677                }
13678
13679                if (uid < Process.FIRST_APPLICATION_UID
13680                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13681                    Slog.e(TAG, "Failed to finalize " + cid);
13682                    PackageHelper.destroySdDir(cid);
13683                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13684                }
13685
13686                boolean mounted = PackageHelper.isContainerMounted(cid);
13687                if (!mounted) {
13688                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13689                }
13690            }
13691            return status;
13692        }
13693
13694        private void cleanUp() {
13695            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13696
13697            // Destroy secure container
13698            PackageHelper.destroySdDir(cid);
13699        }
13700
13701        private List<String> getAllCodePaths() {
13702            final File codeFile = new File(getCodePath());
13703            if (codeFile != null && codeFile.exists()) {
13704                try {
13705                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13706                    return pkg.getAllCodePaths();
13707                } catch (PackageParserException e) {
13708                    // Ignored; we tried our best
13709                }
13710            }
13711            return Collections.EMPTY_LIST;
13712        }
13713
13714        void cleanUpResourcesLI() {
13715            // Enumerate all code paths before deleting
13716            cleanUpResourcesLI(getAllCodePaths());
13717        }
13718
13719        private void cleanUpResourcesLI(List<String> allCodePaths) {
13720            cleanUp();
13721            removeDexFiles(allCodePaths, instructionSets);
13722        }
13723
13724        String getPackageName() {
13725            return getAsecPackageName(cid);
13726        }
13727
13728        boolean doPostDeleteLI(boolean delete) {
13729            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13730            final List<String> allCodePaths = getAllCodePaths();
13731            boolean mounted = PackageHelper.isContainerMounted(cid);
13732            if (mounted) {
13733                // Unmount first
13734                if (PackageHelper.unMountSdDir(cid)) {
13735                    mounted = false;
13736                }
13737            }
13738            if (!mounted && delete) {
13739                cleanUpResourcesLI(allCodePaths);
13740            }
13741            return !mounted;
13742        }
13743
13744        @Override
13745        int doPreCopy() {
13746            if (isFwdLocked()) {
13747                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13748                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13749                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13750                }
13751            }
13752
13753            return PackageManager.INSTALL_SUCCEEDED;
13754        }
13755
13756        @Override
13757        int doPostCopy(int uid) {
13758            if (isFwdLocked()) {
13759                if (uid < Process.FIRST_APPLICATION_UID
13760                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13761                                RES_FILE_NAME)) {
13762                    Slog.e(TAG, "Failed to finalize " + cid);
13763                    PackageHelper.destroySdDir(cid);
13764                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13765                }
13766            }
13767
13768            return PackageManager.INSTALL_SUCCEEDED;
13769        }
13770    }
13771
13772    /**
13773     * Logic to handle movement of existing installed applications.
13774     */
13775    class MoveInstallArgs extends InstallArgs {
13776        private File codeFile;
13777        private File resourceFile;
13778
13779        /** New install */
13780        MoveInstallArgs(InstallParams params) {
13781            super(params.origin, params.move, params.observer, params.installFlags,
13782                    params.installerPackageName, params.volumeUuid,
13783                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13784                    params.grantedRuntimePermissions,
13785                    params.traceMethod, params.traceCookie, params.certificates);
13786        }
13787
13788        int copyApk(IMediaContainerService imcs, boolean temp) {
13789            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13790                    + move.fromUuid + " to " + move.toUuid);
13791            synchronized (mInstaller) {
13792                try {
13793                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13794                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13795                } catch (InstallerException e) {
13796                    Slog.w(TAG, "Failed to move app", e);
13797                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13798                }
13799            }
13800
13801            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13802            resourceFile = codeFile;
13803            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13804
13805            return PackageManager.INSTALL_SUCCEEDED;
13806        }
13807
13808        int doPreInstall(int status) {
13809            if (status != PackageManager.INSTALL_SUCCEEDED) {
13810                cleanUp(move.toUuid);
13811            }
13812            return status;
13813        }
13814
13815        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13816            if (status != PackageManager.INSTALL_SUCCEEDED) {
13817                cleanUp(move.toUuid);
13818                return false;
13819            }
13820
13821            // Reflect the move in app info
13822            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13823            pkg.setApplicationInfoCodePath(pkg.codePath);
13824            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13825            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13826            pkg.setApplicationInfoResourcePath(pkg.codePath);
13827            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13828            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13829
13830            return true;
13831        }
13832
13833        int doPostInstall(int status, int uid) {
13834            if (status == PackageManager.INSTALL_SUCCEEDED) {
13835                cleanUp(move.fromUuid);
13836            } else {
13837                cleanUp(move.toUuid);
13838            }
13839            return status;
13840        }
13841
13842        @Override
13843        String getCodePath() {
13844            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13845        }
13846
13847        @Override
13848        String getResourcePath() {
13849            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13850        }
13851
13852        private boolean cleanUp(String volumeUuid) {
13853            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13854                    move.dataAppName);
13855            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13856            final int[] userIds = sUserManager.getUserIds();
13857            synchronized (mInstallLock) {
13858                // Clean up both app data and code
13859                // All package moves are frozen until finished
13860                for (int userId : userIds) {
13861                    try {
13862                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13863                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13864                    } catch (InstallerException e) {
13865                        Slog.w(TAG, String.valueOf(e));
13866                    }
13867                }
13868                removeCodePathLI(codeFile);
13869            }
13870            return true;
13871        }
13872
13873        void cleanUpResourcesLI() {
13874            throw new UnsupportedOperationException();
13875        }
13876
13877        boolean doPostDeleteLI(boolean delete) {
13878            throw new UnsupportedOperationException();
13879        }
13880    }
13881
13882    static String getAsecPackageName(String packageCid) {
13883        int idx = packageCid.lastIndexOf("-");
13884        if (idx == -1) {
13885            return packageCid;
13886        }
13887        return packageCid.substring(0, idx);
13888    }
13889
13890    // Utility method used to create code paths based on package name and available index.
13891    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13892        String idxStr = "";
13893        int idx = 1;
13894        // Fall back to default value of idx=1 if prefix is not
13895        // part of oldCodePath
13896        if (oldCodePath != null) {
13897            String subStr = oldCodePath;
13898            // Drop the suffix right away
13899            if (suffix != null && subStr.endsWith(suffix)) {
13900                subStr = subStr.substring(0, subStr.length() - suffix.length());
13901            }
13902            // If oldCodePath already contains prefix find out the
13903            // ending index to either increment or decrement.
13904            int sidx = subStr.lastIndexOf(prefix);
13905            if (sidx != -1) {
13906                subStr = subStr.substring(sidx + prefix.length());
13907                if (subStr != null) {
13908                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13909                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13910                    }
13911                    try {
13912                        idx = Integer.parseInt(subStr);
13913                        if (idx <= 1) {
13914                            idx++;
13915                        } else {
13916                            idx--;
13917                        }
13918                    } catch(NumberFormatException e) {
13919                    }
13920                }
13921            }
13922        }
13923        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13924        return prefix + idxStr;
13925    }
13926
13927    private File getNextCodePath(File targetDir, String packageName) {
13928        int suffix = 1;
13929        File result;
13930        do {
13931            result = new File(targetDir, packageName + "-" + suffix);
13932            suffix++;
13933        } while (result.exists());
13934        return result;
13935    }
13936
13937    // Utility method that returns the relative package path with respect
13938    // to the installation directory. Like say for /data/data/com.test-1.apk
13939    // string com.test-1 is returned.
13940    static String deriveCodePathName(String codePath) {
13941        if (codePath == null) {
13942            return null;
13943        }
13944        final File codeFile = new File(codePath);
13945        final String name = codeFile.getName();
13946        if (codeFile.isDirectory()) {
13947            return name;
13948        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13949            final int lastDot = name.lastIndexOf('.');
13950            return name.substring(0, lastDot);
13951        } else {
13952            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13953            return null;
13954        }
13955    }
13956
13957    static class PackageInstalledInfo {
13958        String name;
13959        int uid;
13960        // The set of users that originally had this package installed.
13961        int[] origUsers;
13962        // The set of users that now have this package installed.
13963        int[] newUsers;
13964        PackageParser.Package pkg;
13965        int returnCode;
13966        String returnMsg;
13967        PackageRemovedInfo removedInfo;
13968        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13969
13970        public void setError(int code, String msg) {
13971            setReturnCode(code);
13972            setReturnMessage(msg);
13973            Slog.w(TAG, msg);
13974        }
13975
13976        public void setError(String msg, PackageParserException e) {
13977            setReturnCode(e.error);
13978            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13979            Slog.w(TAG, msg, e);
13980        }
13981
13982        public void setError(String msg, PackageManagerException e) {
13983            returnCode = e.error;
13984            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13985            Slog.w(TAG, msg, e);
13986        }
13987
13988        public void setReturnCode(int returnCode) {
13989            this.returnCode = returnCode;
13990            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13991            for (int i = 0; i < childCount; i++) {
13992                addedChildPackages.valueAt(i).returnCode = returnCode;
13993            }
13994        }
13995
13996        private void setReturnMessage(String returnMsg) {
13997            this.returnMsg = returnMsg;
13998            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13999            for (int i = 0; i < childCount; i++) {
14000                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14001            }
14002        }
14003
14004        // In some error cases we want to convey more info back to the observer
14005        String origPackage;
14006        String origPermission;
14007    }
14008
14009    /*
14010     * Install a non-existing package.
14011     */
14012    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14013            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14014            PackageInstalledInfo res) {
14015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14016
14017        // Remember this for later, in case we need to rollback this install
14018        String pkgName = pkg.packageName;
14019
14020        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14021
14022        synchronized(mPackages) {
14023            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14024                // A package with the same name is already installed, though
14025                // it has been renamed to an older name.  The package we
14026                // are trying to install should be installed as an update to
14027                // the existing one, but that has not been requested, so bail.
14028                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14029                        + " without first uninstalling package running as "
14030                        + mSettings.mRenamedPackages.get(pkgName));
14031                return;
14032            }
14033            if (mPackages.containsKey(pkgName)) {
14034                // Don't allow installation over an existing package with the same name.
14035                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14036                        + " without first uninstalling.");
14037                return;
14038            }
14039        }
14040
14041        try {
14042            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14043                    System.currentTimeMillis(), user);
14044
14045            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14046
14047            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14048                prepareAppDataAfterInstallLIF(newPackage);
14049
14050            } else {
14051                // Remove package from internal structures, but keep around any
14052                // data that might have already existed
14053                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14054                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14055            }
14056        } catch (PackageManagerException e) {
14057            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14058        }
14059
14060        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14061    }
14062
14063    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14064        // Can't rotate keys during boot or if sharedUser.
14065        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14066                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14067            return false;
14068        }
14069        // app is using upgradeKeySets; make sure all are valid
14070        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14071        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14072        for (int i = 0; i < upgradeKeySets.length; i++) {
14073            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14074                Slog.wtf(TAG, "Package "
14075                         + (oldPs.name != null ? oldPs.name : "<null>")
14076                         + " contains upgrade-key-set reference to unknown key-set: "
14077                         + upgradeKeySets[i]
14078                         + " reverting to signatures check.");
14079                return false;
14080            }
14081        }
14082        return true;
14083    }
14084
14085    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14086        // Upgrade keysets are being used.  Determine if new package has a superset of the
14087        // required keys.
14088        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14089        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14090        for (int i = 0; i < upgradeKeySets.length; i++) {
14091            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14092            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14093                return true;
14094            }
14095        }
14096        return false;
14097    }
14098
14099    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14100        try (DigestInputStream digestStream =
14101                new DigestInputStream(new FileInputStream(file), digest)) {
14102            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14103        }
14104    }
14105
14106    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14107            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14108        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14109
14110        final PackageParser.Package oldPackage;
14111        final String pkgName = pkg.packageName;
14112        final int[] allUsers;
14113        final int[] installedUsers;
14114
14115        synchronized(mPackages) {
14116            oldPackage = mPackages.get(pkgName);
14117            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14118
14119            // don't allow upgrade to target a release SDK from a pre-release SDK
14120            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14121                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14122            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14123                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14124            if (oldTargetsPreRelease
14125                    && !newTargetsPreRelease
14126                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14127                Slog.w(TAG, "Can't install package targeting released sdk");
14128                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14129                return;
14130            }
14131
14132            // don't allow an upgrade from full to ephemeral
14133            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14134            if (isEphemeral && !oldIsEphemeral) {
14135                // can't downgrade from full to ephemeral
14136                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14137                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14138                return;
14139            }
14140
14141            // verify signatures are valid
14142            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14143            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14144                if (!checkUpgradeKeySetLP(ps, pkg)) {
14145                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14146                            "New package not signed by keys specified by upgrade-keysets: "
14147                                    + pkgName);
14148                    return;
14149                }
14150            } else {
14151                // default to original signature matching
14152                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14153                        != PackageManager.SIGNATURE_MATCH) {
14154                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14155                            "New package has a different signature: " + pkgName);
14156                    return;
14157                }
14158            }
14159
14160            // don't allow a system upgrade unless the upgrade hash matches
14161            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14162                byte[] digestBytes = null;
14163                try {
14164                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14165                    updateDigest(digest, new File(pkg.baseCodePath));
14166                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14167                        for (String path : pkg.splitCodePaths) {
14168                            updateDigest(digest, new File(path));
14169                        }
14170                    }
14171                    digestBytes = digest.digest();
14172                } catch (NoSuchAlgorithmException | IOException e) {
14173                    res.setError(INSTALL_FAILED_INVALID_APK,
14174                            "Could not compute hash: " + pkgName);
14175                    return;
14176                }
14177                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14178                    res.setError(INSTALL_FAILED_INVALID_APK,
14179                            "New package fails restrict-update check: " + pkgName);
14180                    return;
14181                }
14182                // retain upgrade restriction
14183                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14184            }
14185
14186            // Check for shared user id changes
14187            String invalidPackageName =
14188                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14189            if (invalidPackageName != null) {
14190                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14191                        "Package " + invalidPackageName + " tried to change user "
14192                                + oldPackage.mSharedUserId);
14193                return;
14194            }
14195
14196            // In case of rollback, remember per-user/profile install state
14197            allUsers = sUserManager.getUserIds();
14198            installedUsers = ps.queryInstalledUsers(allUsers, true);
14199        }
14200
14201        // Update what is removed
14202        res.removedInfo = new PackageRemovedInfo();
14203        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14204        res.removedInfo.removedPackage = oldPackage.packageName;
14205        res.removedInfo.isUpdate = true;
14206        res.removedInfo.origUsers = installedUsers;
14207        final int childCount = (oldPackage.childPackages != null)
14208                ? oldPackage.childPackages.size() : 0;
14209        for (int i = 0; i < childCount; i++) {
14210            boolean childPackageUpdated = false;
14211            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14212            if (res.addedChildPackages != null) {
14213                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14214                if (childRes != null) {
14215                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14216                    childRes.removedInfo.removedPackage = childPkg.packageName;
14217                    childRes.removedInfo.isUpdate = true;
14218                    childPackageUpdated = true;
14219                }
14220            }
14221            if (!childPackageUpdated) {
14222                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14223                childRemovedRes.removedPackage = childPkg.packageName;
14224                childRemovedRes.isUpdate = false;
14225                childRemovedRes.dataRemoved = true;
14226                synchronized (mPackages) {
14227                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14228                    if (childPs != null) {
14229                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14230                    }
14231                }
14232                if (res.removedInfo.removedChildPackages == null) {
14233                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14234                }
14235                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14236            }
14237        }
14238
14239        boolean sysPkg = (isSystemApp(oldPackage));
14240        if (sysPkg) {
14241            // Set the system/privileged flags as needed
14242            final boolean privileged =
14243                    (oldPackage.applicationInfo.privateFlags
14244                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14245            final int systemPolicyFlags = policyFlags
14246                    | PackageParser.PARSE_IS_SYSTEM
14247                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14248
14249            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14250                    user, allUsers, installerPackageName, res);
14251        } else {
14252            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14253                    user, allUsers, installerPackageName, res);
14254        }
14255    }
14256
14257    public List<String> getPreviousCodePaths(String packageName) {
14258        final PackageSetting ps = mSettings.mPackages.get(packageName);
14259        final List<String> result = new ArrayList<String>();
14260        if (ps != null && ps.oldCodePaths != null) {
14261            result.addAll(ps.oldCodePaths);
14262        }
14263        return result;
14264    }
14265
14266    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14267            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14268            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14269        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14270                + deletedPackage);
14271
14272        String pkgName = deletedPackage.packageName;
14273        boolean deletedPkg = true;
14274        boolean addedPkg = false;
14275        boolean updatedSettings = false;
14276        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14277        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14278                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14279
14280        final long origUpdateTime = (pkg.mExtras != null)
14281                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14282
14283        // First delete the existing package while retaining the data directory
14284        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14285                res.removedInfo, true, pkg)) {
14286            // If the existing package wasn't successfully deleted
14287            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14288            deletedPkg = false;
14289        } else {
14290            // Successfully deleted the old package; proceed with replace.
14291
14292            // If deleted package lived in a container, give users a chance to
14293            // relinquish resources before killing.
14294            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14295                if (DEBUG_INSTALL) {
14296                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14297                }
14298                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14299                final ArrayList<String> pkgList = new ArrayList<String>(1);
14300                pkgList.add(deletedPackage.applicationInfo.packageName);
14301                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14302            }
14303
14304            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14305                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14306            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14307
14308            try {
14309                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14310                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14311                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14312
14313                // Update the in-memory copy of the previous code paths.
14314                PackageSetting ps = mSettings.mPackages.get(pkgName);
14315                if (!killApp) {
14316                    if (ps.oldCodePaths == null) {
14317                        ps.oldCodePaths = new ArraySet<>();
14318                    }
14319                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14320                    if (deletedPackage.splitCodePaths != null) {
14321                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14322                    }
14323                } else {
14324                    ps.oldCodePaths = null;
14325                }
14326                if (ps.childPackageNames != null) {
14327                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14328                        final String childPkgName = ps.childPackageNames.get(i);
14329                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14330                        childPs.oldCodePaths = ps.oldCodePaths;
14331                    }
14332                }
14333                prepareAppDataAfterInstallLIF(newPackage);
14334                addedPkg = true;
14335            } catch (PackageManagerException e) {
14336                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14337            }
14338        }
14339
14340        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14341            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14342
14343            // Revert all internal state mutations and added folders for the failed install
14344            if (addedPkg) {
14345                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14346                        res.removedInfo, true, null);
14347            }
14348
14349            // Restore the old package
14350            if (deletedPkg) {
14351                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14352                File restoreFile = new File(deletedPackage.codePath);
14353                // Parse old package
14354                boolean oldExternal = isExternal(deletedPackage);
14355                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14356                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14357                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14358                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14359                try {
14360                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14361                            null);
14362                } catch (PackageManagerException e) {
14363                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14364                            + e.getMessage());
14365                    return;
14366                }
14367
14368                synchronized (mPackages) {
14369                    // Ensure the installer package name up to date
14370                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14371
14372                    // Update permissions for restored package
14373                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14374
14375                    mSettings.writeLPr();
14376                }
14377
14378                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14379            }
14380        } else {
14381            synchronized (mPackages) {
14382                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14383                if (ps != null) {
14384                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14385                    if (res.removedInfo.removedChildPackages != null) {
14386                        final int childCount = res.removedInfo.removedChildPackages.size();
14387                        // Iterate in reverse as we may modify the collection
14388                        for (int i = childCount - 1; i >= 0; i--) {
14389                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14390                            if (res.addedChildPackages.containsKey(childPackageName)) {
14391                                res.removedInfo.removedChildPackages.removeAt(i);
14392                            } else {
14393                                PackageRemovedInfo childInfo = res.removedInfo
14394                                        .removedChildPackages.valueAt(i);
14395                                childInfo.removedForAllUsers = mPackages.get(
14396                                        childInfo.removedPackage) == null;
14397                            }
14398                        }
14399                    }
14400                }
14401            }
14402        }
14403    }
14404
14405    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14406            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14407            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14408        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14409                + ", old=" + deletedPackage);
14410
14411        final boolean disabledSystem;
14412
14413        // Remove existing system package
14414        removePackageLI(deletedPackage, true);
14415
14416        synchronized (mPackages) {
14417            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14418        }
14419        if (!disabledSystem) {
14420            // We didn't need to disable the .apk as a current system package,
14421            // which means we are replacing another update that is already
14422            // installed.  We need to make sure to delete the older one's .apk.
14423            res.removedInfo.args = createInstallArgsForExisting(0,
14424                    deletedPackage.applicationInfo.getCodePath(),
14425                    deletedPackage.applicationInfo.getResourcePath(),
14426                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14427        } else {
14428            res.removedInfo.args = null;
14429        }
14430
14431        // Successfully disabled the old package. Now proceed with re-installation
14432        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14433                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14434        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14435
14436        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14437        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14438                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14439
14440        PackageParser.Package newPackage = null;
14441        try {
14442            // Add the package to the internal data structures
14443            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14444
14445            // Set the update and install times
14446            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14447            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14448                    System.currentTimeMillis());
14449
14450            // Update the package dynamic state if succeeded
14451            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14452                // Now that the install succeeded make sure we remove data
14453                // directories for any child package the update removed.
14454                final int deletedChildCount = (deletedPackage.childPackages != null)
14455                        ? deletedPackage.childPackages.size() : 0;
14456                final int newChildCount = (newPackage.childPackages != null)
14457                        ? newPackage.childPackages.size() : 0;
14458                for (int i = 0; i < deletedChildCount; i++) {
14459                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14460                    boolean childPackageDeleted = true;
14461                    for (int j = 0; j < newChildCount; j++) {
14462                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14463                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14464                            childPackageDeleted = false;
14465                            break;
14466                        }
14467                    }
14468                    if (childPackageDeleted) {
14469                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14470                                deletedChildPkg.packageName);
14471                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14472                            PackageRemovedInfo removedChildRes = res.removedInfo
14473                                    .removedChildPackages.get(deletedChildPkg.packageName);
14474                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14475                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14476                        }
14477                    }
14478                }
14479
14480                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14481                prepareAppDataAfterInstallLIF(newPackage);
14482            }
14483        } catch (PackageManagerException e) {
14484            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14485            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14486        }
14487
14488        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14489            // Re installation failed. Restore old information
14490            // Remove new pkg information
14491            if (newPackage != null) {
14492                removeInstalledPackageLI(newPackage, true);
14493            }
14494            // Add back the old system package
14495            try {
14496                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14497            } catch (PackageManagerException e) {
14498                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14499            }
14500
14501            synchronized (mPackages) {
14502                if (disabledSystem) {
14503                    enableSystemPackageLPw(deletedPackage);
14504                }
14505
14506                // Ensure the installer package name up to date
14507                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14508
14509                // Update permissions for restored package
14510                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14511
14512                mSettings.writeLPr();
14513            }
14514
14515            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14516                    + " after failed upgrade");
14517        }
14518    }
14519
14520    /**
14521     * Checks whether the parent or any of the child packages have a change shared
14522     * user. For a package to be a valid update the shred users of the parent and
14523     * the children should match. We may later support changing child shared users.
14524     * @param oldPkg The updated package.
14525     * @param newPkg The update package.
14526     * @return The shared user that change between the versions.
14527     */
14528    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14529            PackageParser.Package newPkg) {
14530        // Check parent shared user
14531        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14532            return newPkg.packageName;
14533        }
14534        // Check child shared users
14535        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14536        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14537        for (int i = 0; i < newChildCount; i++) {
14538            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14539            // If this child was present, did it have the same shared user?
14540            for (int j = 0; j < oldChildCount; j++) {
14541                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14542                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14543                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14544                    return newChildPkg.packageName;
14545                }
14546            }
14547        }
14548        return null;
14549    }
14550
14551    private void removeNativeBinariesLI(PackageSetting ps) {
14552        // Remove the lib path for the parent package
14553        if (ps != null) {
14554            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14555            // Remove the lib path for the child packages
14556            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14557            for (int i = 0; i < childCount; i++) {
14558                PackageSetting childPs = null;
14559                synchronized (mPackages) {
14560                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14561                }
14562                if (childPs != null) {
14563                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14564                            .legacyNativeLibraryPathString);
14565                }
14566            }
14567        }
14568    }
14569
14570    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14571        // Enable the parent package
14572        mSettings.enableSystemPackageLPw(pkg.packageName);
14573        // Enable the child packages
14574        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14575        for (int i = 0; i < childCount; i++) {
14576            PackageParser.Package childPkg = pkg.childPackages.get(i);
14577            mSettings.enableSystemPackageLPw(childPkg.packageName);
14578        }
14579    }
14580
14581    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14582            PackageParser.Package newPkg) {
14583        // Disable the parent package (parent always replaced)
14584        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14585        // Disable the child packages
14586        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14587        for (int i = 0; i < childCount; i++) {
14588            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14589            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14590            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14591        }
14592        return disabled;
14593    }
14594
14595    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14596            String installerPackageName) {
14597        // Enable the parent package
14598        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14599        // Enable the child packages
14600        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14601        for (int i = 0; i < childCount; i++) {
14602            PackageParser.Package childPkg = pkg.childPackages.get(i);
14603            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14604        }
14605    }
14606
14607    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14608        // Collect all used permissions in the UID
14609        ArraySet<String> usedPermissions = new ArraySet<>();
14610        final int packageCount = su.packages.size();
14611        for (int i = 0; i < packageCount; i++) {
14612            PackageSetting ps = su.packages.valueAt(i);
14613            if (ps.pkg == null) {
14614                continue;
14615            }
14616            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14617            for (int j = 0; j < requestedPermCount; j++) {
14618                String permission = ps.pkg.requestedPermissions.get(j);
14619                BasePermission bp = mSettings.mPermissions.get(permission);
14620                if (bp != null) {
14621                    usedPermissions.add(permission);
14622                }
14623            }
14624        }
14625
14626        PermissionsState permissionsState = su.getPermissionsState();
14627        // Prune install permissions
14628        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14629        final int installPermCount = installPermStates.size();
14630        for (int i = installPermCount - 1; i >= 0;  i--) {
14631            PermissionState permissionState = installPermStates.get(i);
14632            if (!usedPermissions.contains(permissionState.getName())) {
14633                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14634                if (bp != null) {
14635                    permissionsState.revokeInstallPermission(bp);
14636                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14637                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14638                }
14639            }
14640        }
14641
14642        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14643
14644        // Prune runtime permissions
14645        for (int userId : allUserIds) {
14646            List<PermissionState> runtimePermStates = permissionsState
14647                    .getRuntimePermissionStates(userId);
14648            final int runtimePermCount = runtimePermStates.size();
14649            for (int i = runtimePermCount - 1; i >= 0; i--) {
14650                PermissionState permissionState = runtimePermStates.get(i);
14651                if (!usedPermissions.contains(permissionState.getName())) {
14652                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14653                    if (bp != null) {
14654                        permissionsState.revokeRuntimePermission(bp, userId);
14655                        permissionsState.updatePermissionFlags(bp, userId,
14656                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14657                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14658                                runtimePermissionChangedUserIds, userId);
14659                    }
14660                }
14661            }
14662        }
14663
14664        return runtimePermissionChangedUserIds;
14665    }
14666
14667    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14668            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14669        // Update the parent package setting
14670        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14671                res, user);
14672        // Update the child packages setting
14673        final int childCount = (newPackage.childPackages != null)
14674                ? newPackage.childPackages.size() : 0;
14675        for (int i = 0; i < childCount; i++) {
14676            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14677            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14678            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14679                    childRes.origUsers, childRes, user);
14680        }
14681    }
14682
14683    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14684            String installerPackageName, int[] allUsers, int[] installedForUsers,
14685            PackageInstalledInfo res, UserHandle user) {
14686        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14687
14688        String pkgName = newPackage.packageName;
14689        synchronized (mPackages) {
14690            //write settings. the installStatus will be incomplete at this stage.
14691            //note that the new package setting would have already been
14692            //added to mPackages. It hasn't been persisted yet.
14693            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14694            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14695            mSettings.writeLPr();
14696            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14697        }
14698
14699        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14700        synchronized (mPackages) {
14701            updatePermissionsLPw(newPackage.packageName, newPackage,
14702                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14703                            ? UPDATE_PERMISSIONS_ALL : 0));
14704            // For system-bundled packages, we assume that installing an upgraded version
14705            // of the package implies that the user actually wants to run that new code,
14706            // so we enable the package.
14707            PackageSetting ps = mSettings.mPackages.get(pkgName);
14708            final int userId = user.getIdentifier();
14709            if (ps != null) {
14710                if (isSystemApp(newPackage)) {
14711                    if (DEBUG_INSTALL) {
14712                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14713                    }
14714                    // Enable system package for requested users
14715                    if (res.origUsers != null) {
14716                        for (int origUserId : res.origUsers) {
14717                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14718                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14719                                        origUserId, installerPackageName);
14720                            }
14721                        }
14722                    }
14723                    // Also convey the prior install/uninstall state
14724                    if (allUsers != null && installedForUsers != null) {
14725                        for (int currentUserId : allUsers) {
14726                            final boolean installed = ArrayUtils.contains(
14727                                    installedForUsers, currentUserId);
14728                            if (DEBUG_INSTALL) {
14729                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14730                            }
14731                            ps.setInstalled(installed, currentUserId);
14732                        }
14733                        // these install state changes will be persisted in the
14734                        // upcoming call to mSettings.writeLPr().
14735                    }
14736                }
14737                // It's implied that when a user requests installation, they want the app to be
14738                // installed and enabled.
14739                if (userId != UserHandle.USER_ALL) {
14740                    ps.setInstalled(true, userId);
14741                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14742                }
14743            }
14744            res.name = pkgName;
14745            res.uid = newPackage.applicationInfo.uid;
14746            res.pkg = newPackage;
14747            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14748            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14749            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14750            //to update install status
14751            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14752            mSettings.writeLPr();
14753            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14754        }
14755
14756        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14757    }
14758
14759    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14760        try {
14761            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14762            installPackageLI(args, res);
14763        } finally {
14764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14765        }
14766    }
14767
14768    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14769        final int installFlags = args.installFlags;
14770        final String installerPackageName = args.installerPackageName;
14771        final String volumeUuid = args.volumeUuid;
14772        final File tmpPackageFile = new File(args.getCodePath());
14773        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14774        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14775                || (args.volumeUuid != null));
14776        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14777        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14778        boolean replace = false;
14779        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14780        if (args.move != null) {
14781            // moving a complete application; perform an initial scan on the new install location
14782            scanFlags |= SCAN_INITIAL;
14783        }
14784        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14785            scanFlags |= SCAN_DONT_KILL_APP;
14786        }
14787
14788        // Result object to be returned
14789        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14790
14791        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14792
14793        // Sanity check
14794        if (ephemeral && (forwardLocked || onExternal)) {
14795            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14796                    + " external=" + onExternal);
14797            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14798            return;
14799        }
14800
14801        // Retrieve PackageSettings and parse package
14802        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14803                | PackageParser.PARSE_ENFORCE_CODE
14804                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14805                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14806                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14807                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14808        PackageParser pp = new PackageParser();
14809        pp.setSeparateProcesses(mSeparateProcesses);
14810        pp.setDisplayMetrics(mMetrics);
14811
14812        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14813        final PackageParser.Package pkg;
14814        try {
14815            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14816        } catch (PackageParserException e) {
14817            res.setError("Failed parse during installPackageLI", e);
14818            return;
14819        } finally {
14820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14821        }
14822
14823        // If we are installing a clustered package add results for the children
14824        if (pkg.childPackages != null) {
14825            synchronized (mPackages) {
14826                final int childCount = pkg.childPackages.size();
14827                for (int i = 0; i < childCount; i++) {
14828                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14829                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14830                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14831                    childRes.pkg = childPkg;
14832                    childRes.name = childPkg.packageName;
14833                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14834                    if (childPs != null) {
14835                        childRes.origUsers = childPs.queryInstalledUsers(
14836                                sUserManager.getUserIds(), true);
14837                    }
14838                    if ((mPackages.containsKey(childPkg.packageName))) {
14839                        childRes.removedInfo = new PackageRemovedInfo();
14840                        childRes.removedInfo.removedPackage = childPkg.packageName;
14841                    }
14842                    if (res.addedChildPackages == null) {
14843                        res.addedChildPackages = new ArrayMap<>();
14844                    }
14845                    res.addedChildPackages.put(childPkg.packageName, childRes);
14846                }
14847            }
14848        }
14849
14850        // If package doesn't declare API override, mark that we have an install
14851        // time CPU ABI override.
14852        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14853            pkg.cpuAbiOverride = args.abiOverride;
14854        }
14855
14856        String pkgName = res.name = pkg.packageName;
14857        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14858            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14859                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14860                return;
14861            }
14862        }
14863
14864        try {
14865            // either use what we've been given or parse directly from the APK
14866            if (args.certificates != null) {
14867                try {
14868                    PackageParser.populateCertificates(pkg, args.certificates);
14869                } catch (PackageParserException e) {
14870                    // there was something wrong with the certificates we were given;
14871                    // try to pull them from the APK
14872                    PackageParser.collectCertificates(pkg, parseFlags);
14873                }
14874            } else {
14875                PackageParser.collectCertificates(pkg, parseFlags);
14876            }
14877        } catch (PackageParserException e) {
14878            res.setError("Failed collect during installPackageLI", e);
14879            return;
14880        }
14881
14882        // Get rid of all references to package scan path via parser.
14883        pp = null;
14884        String oldCodePath = null;
14885        boolean systemApp = false;
14886        synchronized (mPackages) {
14887            // Check if installing already existing package
14888            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14889                String oldName = mSettings.mRenamedPackages.get(pkgName);
14890                if (pkg.mOriginalPackages != null
14891                        && pkg.mOriginalPackages.contains(oldName)
14892                        && mPackages.containsKey(oldName)) {
14893                    // This package is derived from an original package,
14894                    // and this device has been updating from that original
14895                    // name.  We must continue using the original name, so
14896                    // rename the new package here.
14897                    pkg.setPackageName(oldName);
14898                    pkgName = pkg.packageName;
14899                    replace = true;
14900                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14901                            + oldName + " pkgName=" + pkgName);
14902                } else if (mPackages.containsKey(pkgName)) {
14903                    // This package, under its official name, already exists
14904                    // on the device; we should replace it.
14905                    replace = true;
14906                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14907                }
14908
14909                // Child packages are installed through the parent package
14910                if (pkg.parentPackage != null) {
14911                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14912                            "Package " + pkg.packageName + " is child of package "
14913                                    + pkg.parentPackage.parentPackage + ". Child packages "
14914                                    + "can be updated only through the parent package.");
14915                    return;
14916                }
14917
14918                if (replace) {
14919                    // Prevent apps opting out from runtime permissions
14920                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14921                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14922                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14923                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14924                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14925                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14926                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14927                                        + " doesn't support runtime permissions but the old"
14928                                        + " target SDK " + oldTargetSdk + " does.");
14929                        return;
14930                    }
14931
14932                    // Prevent installing of child packages
14933                    if (oldPackage.parentPackage != null) {
14934                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14935                                "Package " + pkg.packageName + " is child of package "
14936                                        + oldPackage.parentPackage + ". Child packages "
14937                                        + "can be updated only through the parent package.");
14938                        return;
14939                    }
14940                }
14941            }
14942
14943            PackageSetting ps = mSettings.mPackages.get(pkgName);
14944            if (ps != null) {
14945                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14946
14947                // Quick sanity check that we're signed correctly if updating;
14948                // we'll check this again later when scanning, but we want to
14949                // bail early here before tripping over redefined permissions.
14950                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14951                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14952                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14953                                + pkg.packageName + " upgrade keys do not match the "
14954                                + "previously installed version");
14955                        return;
14956                    }
14957                } else {
14958                    try {
14959                        verifySignaturesLP(ps, pkg);
14960                    } catch (PackageManagerException e) {
14961                        res.setError(e.error, e.getMessage());
14962                        return;
14963                    }
14964                }
14965
14966                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14967                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14968                    systemApp = (ps.pkg.applicationInfo.flags &
14969                            ApplicationInfo.FLAG_SYSTEM) != 0;
14970                }
14971                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14972            }
14973
14974            // Check whether the newly-scanned package wants to define an already-defined perm
14975            int N = pkg.permissions.size();
14976            for (int i = N-1; i >= 0; i--) {
14977                PackageParser.Permission perm = pkg.permissions.get(i);
14978                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14979                if (bp != null) {
14980                    // If the defining package is signed with our cert, it's okay.  This
14981                    // also includes the "updating the same package" case, of course.
14982                    // "updating same package" could also involve key-rotation.
14983                    final boolean sigsOk;
14984                    if (bp.sourcePackage.equals(pkg.packageName)
14985                            && (bp.packageSetting instanceof PackageSetting)
14986                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14987                                    scanFlags))) {
14988                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14989                    } else {
14990                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14991                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14992                    }
14993                    if (!sigsOk) {
14994                        // If the owning package is the system itself, we log but allow
14995                        // install to proceed; we fail the install on all other permission
14996                        // redefinitions.
14997                        if (!bp.sourcePackage.equals("android")) {
14998                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14999                                    + pkg.packageName + " attempting to redeclare permission "
15000                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15001                            res.origPermission = perm.info.name;
15002                            res.origPackage = bp.sourcePackage;
15003                            return;
15004                        } else {
15005                            Slog.w(TAG, "Package " + pkg.packageName
15006                                    + " attempting to redeclare system permission "
15007                                    + perm.info.name + "; ignoring new declaration");
15008                            pkg.permissions.remove(i);
15009                        }
15010                    }
15011                }
15012            }
15013        }
15014
15015        if (systemApp) {
15016            if (onExternal) {
15017                // Abort update; system app can't be replaced with app on sdcard
15018                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15019                        "Cannot install updates to system apps on sdcard");
15020                return;
15021            } else if (ephemeral) {
15022                // Abort update; system app can't be replaced with an ephemeral app
15023                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15024                        "Cannot update a system app with an ephemeral app");
15025                return;
15026            }
15027        }
15028
15029        if (args.move != null) {
15030            // We did an in-place move, so dex is ready to roll
15031            scanFlags |= SCAN_NO_DEX;
15032            scanFlags |= SCAN_MOVE;
15033
15034            synchronized (mPackages) {
15035                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15036                if (ps == null) {
15037                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15038                            "Missing settings for moved package " + pkgName);
15039                }
15040
15041                // We moved the entire application as-is, so bring over the
15042                // previously derived ABI information.
15043                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15044                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15045            }
15046
15047        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15048            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15049            scanFlags |= SCAN_NO_DEX;
15050
15051            try {
15052                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15053                    args.abiOverride : pkg.cpuAbiOverride);
15054                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15055                        true /* extract libs */);
15056            } catch (PackageManagerException pme) {
15057                Slog.e(TAG, "Error deriving application ABI", pme);
15058                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15059                return;
15060            }
15061
15062            // Shared libraries for the package need to be updated.
15063            synchronized (mPackages) {
15064                try {
15065                    updateSharedLibrariesLPw(pkg, null);
15066                } catch (PackageManagerException e) {
15067                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15068                }
15069            }
15070            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15071            // Do not run PackageDexOptimizer through the local performDexOpt
15072            // method because `pkg` may not be in `mPackages` yet.
15073            //
15074            // Also, don't fail application installs if the dexopt step fails.
15075            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15076                    null /* instructionSets */, false /* checkProfiles */,
15077                    getCompilerFilterForReason(REASON_INSTALL),
15078                    getOrCreateCompilerPackageStats(pkg));
15079            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15080
15081            // Notify BackgroundDexOptService that the package has been changed.
15082            // If this is an update of a package which used to fail to compile,
15083            // BDOS will remove it from its blacklist.
15084            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15085        }
15086
15087        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15088            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15089            return;
15090        }
15091
15092        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15093
15094        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15095                "installPackageLI")) {
15096            if (replace) {
15097                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15098                        installerPackageName, res);
15099            } else {
15100                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15101                        args.user, installerPackageName, volumeUuid, res);
15102            }
15103        }
15104        synchronized (mPackages) {
15105            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15106            if (ps != null) {
15107                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15108            }
15109
15110            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15111            for (int i = 0; i < childCount; i++) {
15112                PackageParser.Package childPkg = pkg.childPackages.get(i);
15113                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15114                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15115                if (childPs != null) {
15116                    childRes.newUsers = childPs.queryInstalledUsers(
15117                            sUserManager.getUserIds(), true);
15118                }
15119            }
15120        }
15121    }
15122
15123    private void startIntentFilterVerifications(int userId, boolean replacing,
15124            PackageParser.Package pkg) {
15125        if (mIntentFilterVerifierComponent == null) {
15126            Slog.w(TAG, "No IntentFilter verification will not be done as "
15127                    + "there is no IntentFilterVerifier available!");
15128            return;
15129        }
15130
15131        final int verifierUid = getPackageUid(
15132                mIntentFilterVerifierComponent.getPackageName(),
15133                MATCH_DEBUG_TRIAGED_MISSING,
15134                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15135
15136        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15137        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15138        mHandler.sendMessage(msg);
15139
15140        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15141        for (int i = 0; i < childCount; i++) {
15142            PackageParser.Package childPkg = pkg.childPackages.get(i);
15143            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15144            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15145            mHandler.sendMessage(msg);
15146        }
15147    }
15148
15149    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15150            PackageParser.Package pkg) {
15151        int size = pkg.activities.size();
15152        if (size == 0) {
15153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15154                    "No activity, so no need to verify any IntentFilter!");
15155            return;
15156        }
15157
15158        final boolean hasDomainURLs = hasDomainURLs(pkg);
15159        if (!hasDomainURLs) {
15160            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15161                    "No domain URLs, so no need to verify any IntentFilter!");
15162            return;
15163        }
15164
15165        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15166                + " if any IntentFilter from the " + size
15167                + " Activities needs verification ...");
15168
15169        int count = 0;
15170        final String packageName = pkg.packageName;
15171
15172        synchronized (mPackages) {
15173            // If this is a new install and we see that we've already run verification for this
15174            // package, we have nothing to do: it means the state was restored from backup.
15175            if (!replacing) {
15176                IntentFilterVerificationInfo ivi =
15177                        mSettings.getIntentFilterVerificationLPr(packageName);
15178                if (ivi != null) {
15179                    if (DEBUG_DOMAIN_VERIFICATION) {
15180                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15181                                + ivi.getStatusString());
15182                    }
15183                    return;
15184                }
15185            }
15186
15187            // If any filters need to be verified, then all need to be.
15188            boolean needToVerify = false;
15189            for (PackageParser.Activity a : pkg.activities) {
15190                for (ActivityIntentInfo filter : a.intents) {
15191                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15192                        if (DEBUG_DOMAIN_VERIFICATION) {
15193                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15194                        }
15195                        needToVerify = true;
15196                        break;
15197                    }
15198                }
15199            }
15200
15201            if (needToVerify) {
15202                final int verificationId = mIntentFilterVerificationToken++;
15203                for (PackageParser.Activity a : pkg.activities) {
15204                    for (ActivityIntentInfo filter : a.intents) {
15205                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15206                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15207                                    "Verification needed for IntentFilter:" + filter.toString());
15208                            mIntentFilterVerifier.addOneIntentFilterVerification(
15209                                    verifierUid, userId, verificationId, filter, packageName);
15210                            count++;
15211                        }
15212                    }
15213                }
15214            }
15215        }
15216
15217        if (count > 0) {
15218            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15219                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15220                    +  " for userId:" + userId);
15221            mIntentFilterVerifier.startVerifications(userId);
15222        } else {
15223            if (DEBUG_DOMAIN_VERIFICATION) {
15224                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15225            }
15226        }
15227    }
15228
15229    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15230        final ComponentName cn  = filter.activity.getComponentName();
15231        final String packageName = cn.getPackageName();
15232
15233        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15234                packageName);
15235        if (ivi == null) {
15236            return true;
15237        }
15238        int status = ivi.getStatus();
15239        switch (status) {
15240            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15241            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15242                return true;
15243
15244            default:
15245                // Nothing to do
15246                return false;
15247        }
15248    }
15249
15250    private static boolean isMultiArch(ApplicationInfo info) {
15251        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15252    }
15253
15254    private static boolean isExternal(PackageParser.Package pkg) {
15255        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15256    }
15257
15258    private static boolean isExternal(PackageSetting ps) {
15259        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15260    }
15261
15262    private static boolean isEphemeral(PackageParser.Package pkg) {
15263        return pkg.applicationInfo.isEphemeralApp();
15264    }
15265
15266    private static boolean isEphemeral(PackageSetting ps) {
15267        return ps.pkg != null && isEphemeral(ps.pkg);
15268    }
15269
15270    private static boolean isSystemApp(PackageParser.Package pkg) {
15271        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15272    }
15273
15274    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15275        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15276    }
15277
15278    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15279        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15280    }
15281
15282    private static boolean isSystemApp(PackageSetting ps) {
15283        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15284    }
15285
15286    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15287        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15288    }
15289
15290    private int packageFlagsToInstallFlags(PackageSetting ps) {
15291        int installFlags = 0;
15292        if (isEphemeral(ps)) {
15293            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15294        }
15295        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15296            // This existing package was an external ASEC install when we have
15297            // the external flag without a UUID
15298            installFlags |= PackageManager.INSTALL_EXTERNAL;
15299        }
15300        if (ps.isForwardLocked()) {
15301            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15302        }
15303        return installFlags;
15304    }
15305
15306    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15307        if (isExternal(pkg)) {
15308            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15309                return StorageManager.UUID_PRIMARY_PHYSICAL;
15310            } else {
15311                return pkg.volumeUuid;
15312            }
15313        } else {
15314            return StorageManager.UUID_PRIVATE_INTERNAL;
15315        }
15316    }
15317
15318    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15319        if (isExternal(pkg)) {
15320            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15321                return mSettings.getExternalVersion();
15322            } else {
15323                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15324            }
15325        } else {
15326            return mSettings.getInternalVersion();
15327        }
15328    }
15329
15330    private void deleteTempPackageFiles() {
15331        final FilenameFilter filter = new FilenameFilter() {
15332            public boolean accept(File dir, String name) {
15333                return name.startsWith("vmdl") && name.endsWith(".tmp");
15334            }
15335        };
15336        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15337            file.delete();
15338        }
15339    }
15340
15341    @Override
15342    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15343            int flags) {
15344        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15345                flags);
15346    }
15347
15348    @Override
15349    public void deletePackage(final String packageName,
15350            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15351        mContext.enforceCallingOrSelfPermission(
15352                android.Manifest.permission.DELETE_PACKAGES, null);
15353        Preconditions.checkNotNull(packageName);
15354        Preconditions.checkNotNull(observer);
15355        final int uid = Binder.getCallingUid();
15356        if (!isOrphaned(packageName)
15357                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15358            try {
15359                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15360                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15361                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15362                observer.onUserActionRequired(intent);
15363            } catch (RemoteException re) {
15364            }
15365            return;
15366        }
15367        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15368        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15369        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15370            mContext.enforceCallingOrSelfPermission(
15371                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15372                    "deletePackage for user " + userId);
15373        }
15374
15375        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15376            try {
15377                observer.onPackageDeleted(packageName,
15378                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15379            } catch (RemoteException re) {
15380            }
15381            return;
15382        }
15383
15384        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15385            try {
15386                observer.onPackageDeleted(packageName,
15387                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15388            } catch (RemoteException re) {
15389            }
15390            return;
15391        }
15392
15393        if (DEBUG_REMOVE) {
15394            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15395                    + " deleteAllUsers: " + deleteAllUsers );
15396        }
15397        // Queue up an async operation since the package deletion may take a little while.
15398        mHandler.post(new Runnable() {
15399            public void run() {
15400                mHandler.removeCallbacks(this);
15401                int returnCode;
15402                if (!deleteAllUsers) {
15403                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15404                } else {
15405                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15406                    // If nobody is blocking uninstall, proceed with delete for all users
15407                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15408                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15409                    } else {
15410                        // Otherwise uninstall individually for users with blockUninstalls=false
15411                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15412                        for (int userId : users) {
15413                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15414                                returnCode = deletePackageX(packageName, userId, userFlags);
15415                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15416                                    Slog.w(TAG, "Package delete failed for user " + userId
15417                                            + ", returnCode " + returnCode);
15418                                }
15419                            }
15420                        }
15421                        // The app has only been marked uninstalled for certain users.
15422                        // We still need to report that delete was blocked
15423                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15424                    }
15425                }
15426                try {
15427                    observer.onPackageDeleted(packageName, returnCode, null);
15428                } catch (RemoteException e) {
15429                    Log.i(TAG, "Observer no longer exists.");
15430                } //end catch
15431            } //end run
15432        });
15433    }
15434
15435    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15436        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15437              || callingUid == Process.SYSTEM_UID) {
15438            return true;
15439        }
15440        final int callingUserId = UserHandle.getUserId(callingUid);
15441        // If the caller installed the pkgName, then allow it to silently uninstall.
15442        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15443            return true;
15444        }
15445
15446        // Allow package verifier to silently uninstall.
15447        if (mRequiredVerifierPackage != null &&
15448                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15449            return true;
15450        }
15451
15452        // Allow package uninstaller to silently uninstall.
15453        if (mRequiredUninstallerPackage != null &&
15454                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15455            return true;
15456        }
15457        return false;
15458    }
15459
15460    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15461        int[] result = EMPTY_INT_ARRAY;
15462        for (int userId : userIds) {
15463            if (getBlockUninstallForUser(packageName, userId)) {
15464                result = ArrayUtils.appendInt(result, userId);
15465            }
15466        }
15467        return result;
15468    }
15469
15470    @Override
15471    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15472        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15473    }
15474
15475    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15476        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15477                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15478        try {
15479            if (dpm != null) {
15480                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15481                        /* callingUserOnly =*/ false);
15482                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15483                        : deviceOwnerComponentName.getPackageName();
15484                // Does the package contains the device owner?
15485                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15486                // this check is probably not needed, since DO should be registered as a device
15487                // admin on some user too. (Original bug for this: b/17657954)
15488                if (packageName.equals(deviceOwnerPackageName)) {
15489                    return true;
15490                }
15491                // Does it contain a device admin for any user?
15492                int[] users;
15493                if (userId == UserHandle.USER_ALL) {
15494                    users = sUserManager.getUserIds();
15495                } else {
15496                    users = new int[]{userId};
15497                }
15498                for (int i = 0; i < users.length; ++i) {
15499                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15500                        return true;
15501                    }
15502                }
15503            }
15504        } catch (RemoteException e) {
15505        }
15506        return false;
15507    }
15508
15509    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15510        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15511    }
15512
15513    /**
15514     *  This method is an internal method that could be get invoked either
15515     *  to delete an installed package or to clean up a failed installation.
15516     *  After deleting an installed package, a broadcast is sent to notify any
15517     *  listeners that the package has been removed. For cleaning up a failed
15518     *  installation, the broadcast is not necessary since the package's
15519     *  installation wouldn't have sent the initial broadcast either
15520     *  The key steps in deleting a package are
15521     *  deleting the package information in internal structures like mPackages,
15522     *  deleting the packages base directories through installd
15523     *  updating mSettings to reflect current status
15524     *  persisting settings for later use
15525     *  sending a broadcast if necessary
15526     */
15527    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15528        final PackageRemovedInfo info = new PackageRemovedInfo();
15529        final boolean res;
15530
15531        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15532                ? UserHandle.USER_ALL : userId;
15533
15534        if (isPackageDeviceAdmin(packageName, removeUser)) {
15535            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15536            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15537        }
15538
15539        PackageSetting uninstalledPs = null;
15540
15541        // for the uninstall-updates case and restricted profiles, remember the per-
15542        // user handle installed state
15543        int[] allUsers;
15544        synchronized (mPackages) {
15545            uninstalledPs = mSettings.mPackages.get(packageName);
15546            if (uninstalledPs == null) {
15547                Slog.w(TAG, "Not removing non-existent package " + packageName);
15548                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15549            }
15550            allUsers = sUserManager.getUserIds();
15551            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15552        }
15553
15554        final int freezeUser;
15555        if (isUpdatedSystemApp(uninstalledPs)
15556                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15557            // We're downgrading a system app, which will apply to all users, so
15558            // freeze them all during the downgrade
15559            freezeUser = UserHandle.USER_ALL;
15560        } else {
15561            freezeUser = removeUser;
15562        }
15563
15564        synchronized (mInstallLock) {
15565            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15566            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15567                    deleteFlags, "deletePackageX")) {
15568                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15569                        deleteFlags | REMOVE_CHATTY, info, true, null);
15570            }
15571            synchronized (mPackages) {
15572                if (res) {
15573                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15574                }
15575            }
15576        }
15577
15578        if (res) {
15579            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15580            info.sendPackageRemovedBroadcasts(killApp);
15581            info.sendSystemPackageUpdatedBroadcasts();
15582            info.sendSystemPackageAppearedBroadcasts();
15583        }
15584        // Force a gc here.
15585        Runtime.getRuntime().gc();
15586        // Delete the resources here after sending the broadcast to let
15587        // other processes clean up before deleting resources.
15588        if (info.args != null) {
15589            synchronized (mInstallLock) {
15590                info.args.doPostDeleteLI(true);
15591            }
15592        }
15593
15594        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15595    }
15596
15597    class PackageRemovedInfo {
15598        String removedPackage;
15599        int uid = -1;
15600        int removedAppId = -1;
15601        int[] origUsers;
15602        int[] removedUsers = null;
15603        boolean isRemovedPackageSystemUpdate = false;
15604        boolean isUpdate;
15605        boolean dataRemoved;
15606        boolean removedForAllUsers;
15607        // Clean up resources deleted packages.
15608        InstallArgs args = null;
15609        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15610        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15611
15612        void sendPackageRemovedBroadcasts(boolean killApp) {
15613            sendPackageRemovedBroadcastInternal(killApp);
15614            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15615            for (int i = 0; i < childCount; i++) {
15616                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15617                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15618            }
15619        }
15620
15621        void sendSystemPackageUpdatedBroadcasts() {
15622            if (isRemovedPackageSystemUpdate) {
15623                sendSystemPackageUpdatedBroadcastsInternal();
15624                final int childCount = (removedChildPackages != null)
15625                        ? removedChildPackages.size() : 0;
15626                for (int i = 0; i < childCount; i++) {
15627                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15628                    if (childInfo.isRemovedPackageSystemUpdate) {
15629                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15630                    }
15631                }
15632            }
15633        }
15634
15635        void sendSystemPackageAppearedBroadcasts() {
15636            final int packageCount = (appearedChildPackages != null)
15637                    ? appearedChildPackages.size() : 0;
15638            for (int i = 0; i < packageCount; i++) {
15639                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15640                for (int userId : installedInfo.newUsers) {
15641                    sendPackageAddedForUser(installedInfo.name, true,
15642                            UserHandle.getAppId(installedInfo.uid), userId);
15643                }
15644            }
15645        }
15646
15647        private void sendSystemPackageUpdatedBroadcastsInternal() {
15648            Bundle extras = new Bundle(2);
15649            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15650            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15651            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15652                    extras, 0, null, null, null);
15653            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15654                    extras, 0, null, null, null);
15655            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15656                    null, 0, removedPackage, null, null);
15657        }
15658
15659        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15660            Bundle extras = new Bundle(2);
15661            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15662            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15663            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15664            if (isUpdate || isRemovedPackageSystemUpdate) {
15665                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15666            }
15667            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15668            if (removedPackage != null) {
15669                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15670                        extras, 0, null, null, removedUsers);
15671                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15672                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15673                            removedPackage, extras, 0, null, null, removedUsers);
15674                }
15675            }
15676            if (removedAppId >= 0) {
15677                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15678                        removedUsers);
15679            }
15680        }
15681    }
15682
15683    /*
15684     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15685     * flag is not set, the data directory is removed as well.
15686     * make sure this flag is set for partially installed apps. If not its meaningless to
15687     * delete a partially installed application.
15688     */
15689    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15690            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15691        String packageName = ps.name;
15692        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15693        // Retrieve object to delete permissions for shared user later on
15694        final PackageParser.Package deletedPkg;
15695        final PackageSetting deletedPs;
15696        // reader
15697        synchronized (mPackages) {
15698            deletedPkg = mPackages.get(packageName);
15699            deletedPs = mSettings.mPackages.get(packageName);
15700            if (outInfo != null) {
15701                outInfo.removedPackage = packageName;
15702                outInfo.removedUsers = deletedPs != null
15703                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15704                        : null;
15705            }
15706        }
15707
15708        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15709
15710        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15711            final PackageParser.Package resolvedPkg;
15712            if (deletedPkg != null) {
15713                resolvedPkg = deletedPkg;
15714            } else {
15715                // We don't have a parsed package when it lives on an ejected
15716                // adopted storage device, so fake something together
15717                resolvedPkg = new PackageParser.Package(ps.name);
15718                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15719            }
15720            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15721                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15722            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15723            if (outInfo != null) {
15724                outInfo.dataRemoved = true;
15725            }
15726            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15727        }
15728
15729        // writer
15730        synchronized (mPackages) {
15731            if (deletedPs != null) {
15732                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15733                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15734                    clearDefaultBrowserIfNeeded(packageName);
15735                    if (outInfo != null) {
15736                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15737                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15738                    }
15739                    updatePermissionsLPw(deletedPs.name, null, 0);
15740                    if (deletedPs.sharedUser != null) {
15741                        // Remove permissions associated with package. Since runtime
15742                        // permissions are per user we have to kill the removed package
15743                        // or packages running under the shared user of the removed
15744                        // package if revoking the permissions requested only by the removed
15745                        // package is successful and this causes a change in gids.
15746                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15747                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15748                                    userId);
15749                            if (userIdToKill == UserHandle.USER_ALL
15750                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15751                                // If gids changed for this user, kill all affected packages.
15752                                mHandler.post(new Runnable() {
15753                                    @Override
15754                                    public void run() {
15755                                        // This has to happen with no lock held.
15756                                        killApplication(deletedPs.name, deletedPs.appId,
15757                                                KILL_APP_REASON_GIDS_CHANGED);
15758                                    }
15759                                });
15760                                break;
15761                            }
15762                        }
15763                    }
15764                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15765                }
15766                // make sure to preserve per-user disabled state if this removal was just
15767                // a downgrade of a system app to the factory package
15768                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15769                    if (DEBUG_REMOVE) {
15770                        Slog.d(TAG, "Propagating install state across downgrade");
15771                    }
15772                    for (int userId : allUserHandles) {
15773                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15774                        if (DEBUG_REMOVE) {
15775                            Slog.d(TAG, "    user " + userId + " => " + installed);
15776                        }
15777                        ps.setInstalled(installed, userId);
15778                    }
15779                }
15780            }
15781            // can downgrade to reader
15782            if (writeSettings) {
15783                // Save settings now
15784                mSettings.writeLPr();
15785            }
15786        }
15787        if (outInfo != null) {
15788            // A user ID was deleted here. Go through all users and remove it
15789            // from KeyStore.
15790            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15791        }
15792    }
15793
15794    static boolean locationIsPrivileged(File path) {
15795        try {
15796            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15797                    .getCanonicalPath();
15798            return path.getCanonicalPath().startsWith(privilegedAppDir);
15799        } catch (IOException e) {
15800            Slog.e(TAG, "Unable to access code path " + path);
15801        }
15802        return false;
15803    }
15804
15805    /*
15806     * Tries to delete system package.
15807     */
15808    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15809            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15810            boolean writeSettings) {
15811        if (deletedPs.parentPackageName != null) {
15812            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15813            return false;
15814        }
15815
15816        final boolean applyUserRestrictions
15817                = (allUserHandles != null) && (outInfo.origUsers != null);
15818        final PackageSetting disabledPs;
15819        // Confirm if the system package has been updated
15820        // An updated system app can be deleted. This will also have to restore
15821        // the system pkg from system partition
15822        // reader
15823        synchronized (mPackages) {
15824            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15825        }
15826
15827        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15828                + " disabledPs=" + disabledPs);
15829
15830        if (disabledPs == null) {
15831            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15832            return false;
15833        } else if (DEBUG_REMOVE) {
15834            Slog.d(TAG, "Deleting system pkg from data partition");
15835        }
15836
15837        if (DEBUG_REMOVE) {
15838            if (applyUserRestrictions) {
15839                Slog.d(TAG, "Remembering install states:");
15840                for (int userId : allUserHandles) {
15841                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15842                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15843                }
15844            }
15845        }
15846
15847        // Delete the updated package
15848        outInfo.isRemovedPackageSystemUpdate = true;
15849        if (outInfo.removedChildPackages != null) {
15850            final int childCount = (deletedPs.childPackageNames != null)
15851                    ? deletedPs.childPackageNames.size() : 0;
15852            for (int i = 0; i < childCount; i++) {
15853                String childPackageName = deletedPs.childPackageNames.get(i);
15854                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15855                        .contains(childPackageName)) {
15856                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15857                            childPackageName);
15858                    if (childInfo != null) {
15859                        childInfo.isRemovedPackageSystemUpdate = true;
15860                    }
15861                }
15862            }
15863        }
15864
15865        if (disabledPs.versionCode < deletedPs.versionCode) {
15866            // Delete data for downgrades
15867            flags &= ~PackageManager.DELETE_KEEP_DATA;
15868        } else {
15869            // Preserve data by setting flag
15870            flags |= PackageManager.DELETE_KEEP_DATA;
15871        }
15872
15873        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15874                outInfo, writeSettings, disabledPs.pkg);
15875        if (!ret) {
15876            return false;
15877        }
15878
15879        // writer
15880        synchronized (mPackages) {
15881            // Reinstate the old system package
15882            enableSystemPackageLPw(disabledPs.pkg);
15883            // Remove any native libraries from the upgraded package.
15884            removeNativeBinariesLI(deletedPs);
15885        }
15886
15887        // Install the system package
15888        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15889        int parseFlags = mDefParseFlags
15890                | PackageParser.PARSE_MUST_BE_APK
15891                | PackageParser.PARSE_IS_SYSTEM
15892                | PackageParser.PARSE_IS_SYSTEM_DIR;
15893        if (locationIsPrivileged(disabledPs.codePath)) {
15894            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15895        }
15896
15897        final PackageParser.Package newPkg;
15898        try {
15899            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15900        } catch (PackageManagerException e) {
15901            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15902                    + e.getMessage());
15903            return false;
15904        }
15905        try {
15906            // update shared libraries for the newly re-installed system package
15907            updateSharedLibrariesLPw(newPkg, null);
15908        } catch (PackageManagerException e) {
15909            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15910        }
15911
15912        prepareAppDataAfterInstallLIF(newPkg);
15913
15914        // writer
15915        synchronized (mPackages) {
15916            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15917
15918            // Propagate the permissions state as we do not want to drop on the floor
15919            // runtime permissions. The update permissions method below will take
15920            // care of removing obsolete permissions and grant install permissions.
15921            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15922            updatePermissionsLPw(newPkg.packageName, newPkg,
15923                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15924
15925            if (applyUserRestrictions) {
15926                if (DEBUG_REMOVE) {
15927                    Slog.d(TAG, "Propagating install state across reinstall");
15928                }
15929                for (int userId : allUserHandles) {
15930                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15931                    if (DEBUG_REMOVE) {
15932                        Slog.d(TAG, "    user " + userId + " => " + installed);
15933                    }
15934                    ps.setInstalled(installed, userId);
15935
15936                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15937                }
15938                // Regardless of writeSettings we need to ensure that this restriction
15939                // state propagation is persisted
15940                mSettings.writeAllUsersPackageRestrictionsLPr();
15941            }
15942            // can downgrade to reader here
15943            if (writeSettings) {
15944                mSettings.writeLPr();
15945            }
15946        }
15947        return true;
15948    }
15949
15950    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15951            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15952            PackageRemovedInfo outInfo, boolean writeSettings,
15953            PackageParser.Package replacingPackage) {
15954        synchronized (mPackages) {
15955            if (outInfo != null) {
15956                outInfo.uid = ps.appId;
15957            }
15958
15959            if (outInfo != null && outInfo.removedChildPackages != null) {
15960                final int childCount = (ps.childPackageNames != null)
15961                        ? ps.childPackageNames.size() : 0;
15962                for (int i = 0; i < childCount; i++) {
15963                    String childPackageName = ps.childPackageNames.get(i);
15964                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15965                    if (childPs == null) {
15966                        return false;
15967                    }
15968                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15969                            childPackageName);
15970                    if (childInfo != null) {
15971                        childInfo.uid = childPs.appId;
15972                    }
15973                }
15974            }
15975        }
15976
15977        // Delete package data from internal structures and also remove data if flag is set
15978        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15979
15980        // Delete the child packages data
15981        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15982        for (int i = 0; i < childCount; i++) {
15983            PackageSetting childPs;
15984            synchronized (mPackages) {
15985                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15986            }
15987            if (childPs != null) {
15988                PackageRemovedInfo childOutInfo = (outInfo != null
15989                        && outInfo.removedChildPackages != null)
15990                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15991                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15992                        && (replacingPackage != null
15993                        && !replacingPackage.hasChildPackage(childPs.name))
15994                        ? flags & ~DELETE_KEEP_DATA : flags;
15995                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15996                        deleteFlags, writeSettings);
15997            }
15998        }
15999
16000        // Delete application code and resources only for parent packages
16001        if (ps.parentPackageName == null) {
16002            if (deleteCodeAndResources && (outInfo != null)) {
16003                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16004                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16005                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16006            }
16007        }
16008
16009        return true;
16010    }
16011
16012    @Override
16013    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16014            int userId) {
16015        mContext.enforceCallingOrSelfPermission(
16016                android.Manifest.permission.DELETE_PACKAGES, null);
16017        synchronized (mPackages) {
16018            PackageSetting ps = mSettings.mPackages.get(packageName);
16019            if (ps == null) {
16020                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16021                return false;
16022            }
16023            if (!ps.getInstalled(userId)) {
16024                // Can't block uninstall for an app that is not installed or enabled.
16025                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16026                return false;
16027            }
16028            ps.setBlockUninstall(blockUninstall, userId);
16029            mSettings.writePackageRestrictionsLPr(userId);
16030        }
16031        return true;
16032    }
16033
16034    @Override
16035    public boolean getBlockUninstallForUser(String packageName, int userId) {
16036        synchronized (mPackages) {
16037            PackageSetting ps = mSettings.mPackages.get(packageName);
16038            if (ps == null) {
16039                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16040                return false;
16041            }
16042            return ps.getBlockUninstall(userId);
16043        }
16044    }
16045
16046    @Override
16047    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16048        int callingUid = Binder.getCallingUid();
16049        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16050            throw new SecurityException(
16051                    "setRequiredForSystemUser can only be run by the system or root");
16052        }
16053        synchronized (mPackages) {
16054            PackageSetting ps = mSettings.mPackages.get(packageName);
16055            if (ps == null) {
16056                Log.w(TAG, "Package doesn't exist: " + packageName);
16057                return false;
16058            }
16059            if (systemUserApp) {
16060                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16061            } else {
16062                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16063            }
16064            mSettings.writeLPr();
16065        }
16066        return true;
16067    }
16068
16069    /*
16070     * This method handles package deletion in general
16071     */
16072    private boolean deletePackageLIF(String packageName, UserHandle user,
16073            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16074            PackageRemovedInfo outInfo, boolean writeSettings,
16075            PackageParser.Package replacingPackage) {
16076        if (packageName == null) {
16077            Slog.w(TAG, "Attempt to delete null packageName.");
16078            return false;
16079        }
16080
16081        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16082
16083        PackageSetting ps;
16084
16085        synchronized (mPackages) {
16086            ps = mSettings.mPackages.get(packageName);
16087            if (ps == null) {
16088                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16089                return false;
16090            }
16091
16092            if (ps.parentPackageName != null && (!isSystemApp(ps)
16093                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16094                if (DEBUG_REMOVE) {
16095                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16096                            + ((user == null) ? UserHandle.USER_ALL : user));
16097                }
16098                final int removedUserId = (user != null) ? user.getIdentifier()
16099                        : UserHandle.USER_ALL;
16100                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16101                    return false;
16102                }
16103                markPackageUninstalledForUserLPw(ps, user);
16104                scheduleWritePackageRestrictionsLocked(user);
16105                return true;
16106            }
16107        }
16108
16109        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16110                && user.getIdentifier() != UserHandle.USER_ALL)) {
16111            // The caller is asking that the package only be deleted for a single
16112            // user.  To do this, we just mark its uninstalled state and delete
16113            // its data. If this is a system app, we only allow this to happen if
16114            // they have set the special DELETE_SYSTEM_APP which requests different
16115            // semantics than normal for uninstalling system apps.
16116            markPackageUninstalledForUserLPw(ps, user);
16117
16118            if (!isSystemApp(ps)) {
16119                // Do not uninstall the APK if an app should be cached
16120                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16121                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16122                    // Other user still have this package installed, so all
16123                    // we need to do is clear this user's data and save that
16124                    // it is uninstalled.
16125                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16126                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16127                        return false;
16128                    }
16129                    scheduleWritePackageRestrictionsLocked(user);
16130                    return true;
16131                } else {
16132                    // We need to set it back to 'installed' so the uninstall
16133                    // broadcasts will be sent correctly.
16134                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16135                    ps.setInstalled(true, user.getIdentifier());
16136                }
16137            } else {
16138                // This is a system app, so we assume that the
16139                // other users still have this package installed, so all
16140                // we need to do is clear this user's data and save that
16141                // it is uninstalled.
16142                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16143                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16144                    return false;
16145                }
16146                scheduleWritePackageRestrictionsLocked(user);
16147                return true;
16148            }
16149        }
16150
16151        // If we are deleting a composite package for all users, keep track
16152        // of result for each child.
16153        if (ps.childPackageNames != null && outInfo != null) {
16154            synchronized (mPackages) {
16155                final int childCount = ps.childPackageNames.size();
16156                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16157                for (int i = 0; i < childCount; i++) {
16158                    String childPackageName = ps.childPackageNames.get(i);
16159                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16160                    childInfo.removedPackage = childPackageName;
16161                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16162                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16163                    if (childPs != null) {
16164                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16165                    }
16166                }
16167            }
16168        }
16169
16170        boolean ret = false;
16171        if (isSystemApp(ps)) {
16172            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16173            // When an updated system application is deleted we delete the existing resources
16174            // as well and fall back to existing code in system partition
16175            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16176        } else {
16177            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16178            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16179                    outInfo, writeSettings, replacingPackage);
16180        }
16181
16182        // Take a note whether we deleted the package for all users
16183        if (outInfo != null) {
16184            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16185            if (outInfo.removedChildPackages != null) {
16186                synchronized (mPackages) {
16187                    final int childCount = outInfo.removedChildPackages.size();
16188                    for (int i = 0; i < childCount; i++) {
16189                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16190                        if (childInfo != null) {
16191                            childInfo.removedForAllUsers = mPackages.get(
16192                                    childInfo.removedPackage) == null;
16193                        }
16194                    }
16195                }
16196            }
16197            // If we uninstalled an update to a system app there may be some
16198            // child packages that appeared as they are declared in the system
16199            // app but were not declared in the update.
16200            if (isSystemApp(ps)) {
16201                synchronized (mPackages) {
16202                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16203                    final int childCount = (updatedPs.childPackageNames != null)
16204                            ? updatedPs.childPackageNames.size() : 0;
16205                    for (int i = 0; i < childCount; i++) {
16206                        String childPackageName = updatedPs.childPackageNames.get(i);
16207                        if (outInfo.removedChildPackages == null
16208                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16209                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16210                            if (childPs == null) {
16211                                continue;
16212                            }
16213                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16214                            installRes.name = childPackageName;
16215                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16216                            installRes.pkg = mPackages.get(childPackageName);
16217                            installRes.uid = childPs.pkg.applicationInfo.uid;
16218                            if (outInfo.appearedChildPackages == null) {
16219                                outInfo.appearedChildPackages = new ArrayMap<>();
16220                            }
16221                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16222                        }
16223                    }
16224                }
16225            }
16226        }
16227
16228        return ret;
16229    }
16230
16231    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16232        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16233                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16234        for (int nextUserId : userIds) {
16235            if (DEBUG_REMOVE) {
16236                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16237            }
16238            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16239                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16240                    false /*hidden*/, false /*suspended*/, null, null, null,
16241                    false /*blockUninstall*/,
16242                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16243        }
16244    }
16245
16246    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16247            PackageRemovedInfo outInfo) {
16248        final PackageParser.Package pkg;
16249        synchronized (mPackages) {
16250            pkg = mPackages.get(ps.name);
16251        }
16252
16253        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16254                : new int[] {userId};
16255        for (int nextUserId : userIds) {
16256            if (DEBUG_REMOVE) {
16257                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16258                        + nextUserId);
16259            }
16260
16261            destroyAppDataLIF(pkg, userId,
16262                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16263            destroyAppProfilesLIF(pkg, userId);
16264            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16265            schedulePackageCleaning(ps.name, nextUserId, false);
16266            synchronized (mPackages) {
16267                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16268                    scheduleWritePackageRestrictionsLocked(nextUserId);
16269                }
16270                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16271            }
16272        }
16273
16274        if (outInfo != null) {
16275            outInfo.removedPackage = ps.name;
16276            outInfo.removedAppId = ps.appId;
16277            outInfo.removedUsers = userIds;
16278        }
16279
16280        return true;
16281    }
16282
16283    private final class ClearStorageConnection implements ServiceConnection {
16284        IMediaContainerService mContainerService;
16285
16286        @Override
16287        public void onServiceConnected(ComponentName name, IBinder service) {
16288            synchronized (this) {
16289                mContainerService = IMediaContainerService.Stub.asInterface(service);
16290                notifyAll();
16291            }
16292        }
16293
16294        @Override
16295        public void onServiceDisconnected(ComponentName name) {
16296        }
16297    }
16298
16299    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16300        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16301
16302        final boolean mounted;
16303        if (Environment.isExternalStorageEmulated()) {
16304            mounted = true;
16305        } else {
16306            final String status = Environment.getExternalStorageState();
16307
16308            mounted = status.equals(Environment.MEDIA_MOUNTED)
16309                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16310        }
16311
16312        if (!mounted) {
16313            return;
16314        }
16315
16316        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16317        int[] users;
16318        if (userId == UserHandle.USER_ALL) {
16319            users = sUserManager.getUserIds();
16320        } else {
16321            users = new int[] { userId };
16322        }
16323        final ClearStorageConnection conn = new ClearStorageConnection();
16324        if (mContext.bindServiceAsUser(
16325                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16326            try {
16327                for (int curUser : users) {
16328                    long timeout = SystemClock.uptimeMillis() + 5000;
16329                    synchronized (conn) {
16330                        long now;
16331                        while (conn.mContainerService == null &&
16332                                (now = SystemClock.uptimeMillis()) < timeout) {
16333                            try {
16334                                conn.wait(timeout - now);
16335                            } catch (InterruptedException e) {
16336                            }
16337                        }
16338                    }
16339                    if (conn.mContainerService == null) {
16340                        return;
16341                    }
16342
16343                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16344                    clearDirectory(conn.mContainerService,
16345                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16346                    if (allData) {
16347                        clearDirectory(conn.mContainerService,
16348                                userEnv.buildExternalStorageAppDataDirs(packageName));
16349                        clearDirectory(conn.mContainerService,
16350                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16351                    }
16352                }
16353            } finally {
16354                mContext.unbindService(conn);
16355            }
16356        }
16357    }
16358
16359    @Override
16360    public void clearApplicationProfileData(String packageName) {
16361        enforceSystemOrRoot("Only the system can clear all profile data");
16362
16363        final PackageParser.Package pkg;
16364        synchronized (mPackages) {
16365            pkg = mPackages.get(packageName);
16366        }
16367
16368        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16369            synchronized (mInstallLock) {
16370                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16371                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16372                        true /* removeBaseMarker */);
16373            }
16374        }
16375    }
16376
16377    @Override
16378    public void clearApplicationUserData(final String packageName,
16379            final IPackageDataObserver observer, final int userId) {
16380        mContext.enforceCallingOrSelfPermission(
16381                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16382
16383        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16384                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16385
16386        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16387            throw new SecurityException("Cannot clear data for a protected package: "
16388                    + packageName);
16389        }
16390        // Queue up an async operation since the package deletion may take a little while.
16391        mHandler.post(new Runnable() {
16392            public void run() {
16393                mHandler.removeCallbacks(this);
16394                final boolean succeeded;
16395                try (PackageFreezer freezer = freezePackage(packageName,
16396                        "clearApplicationUserData")) {
16397                    synchronized (mInstallLock) {
16398                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16399                    }
16400                    clearExternalStorageDataSync(packageName, userId, true);
16401                }
16402                if (succeeded) {
16403                    // invoke DeviceStorageMonitor's update method to clear any notifications
16404                    DeviceStorageMonitorInternal dsm = LocalServices
16405                            .getService(DeviceStorageMonitorInternal.class);
16406                    if (dsm != null) {
16407                        dsm.checkMemory();
16408                    }
16409                }
16410                if(observer != null) {
16411                    try {
16412                        observer.onRemoveCompleted(packageName, succeeded);
16413                    } catch (RemoteException e) {
16414                        Log.i(TAG, "Observer no longer exists.");
16415                    }
16416                } //end if observer
16417            } //end run
16418        });
16419    }
16420
16421    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16422        if (packageName == null) {
16423            Slog.w(TAG, "Attempt to delete null packageName.");
16424            return false;
16425        }
16426
16427        // Try finding details about the requested package
16428        PackageParser.Package pkg;
16429        synchronized (mPackages) {
16430            pkg = mPackages.get(packageName);
16431            if (pkg == null) {
16432                final PackageSetting ps = mSettings.mPackages.get(packageName);
16433                if (ps != null) {
16434                    pkg = ps.pkg;
16435                }
16436            }
16437
16438            if (pkg == null) {
16439                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16440                return false;
16441            }
16442
16443            PackageSetting ps = (PackageSetting) pkg.mExtras;
16444            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16445        }
16446
16447        clearAppDataLIF(pkg, userId,
16448                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16449
16450        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16451        removeKeystoreDataIfNeeded(userId, appId);
16452
16453        UserManagerInternal umInternal = getUserManagerInternal();
16454        final int flags;
16455        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16456            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16457        } else if (umInternal.isUserRunning(userId)) {
16458            flags = StorageManager.FLAG_STORAGE_DE;
16459        } else {
16460            flags = 0;
16461        }
16462        prepareAppDataContentsLIF(pkg, userId, flags);
16463
16464        return true;
16465    }
16466
16467    /**
16468     * Reverts user permission state changes (permissions and flags) in
16469     * all packages for a given user.
16470     *
16471     * @param userId The device user for which to do a reset.
16472     */
16473    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16474        final int packageCount = mPackages.size();
16475        for (int i = 0; i < packageCount; i++) {
16476            PackageParser.Package pkg = mPackages.valueAt(i);
16477            PackageSetting ps = (PackageSetting) pkg.mExtras;
16478            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16479        }
16480    }
16481
16482    private void resetNetworkPolicies(int userId) {
16483        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16484    }
16485
16486    /**
16487     * Reverts user permission state changes (permissions and flags).
16488     *
16489     * @param ps The package for which to reset.
16490     * @param userId The device user for which to do a reset.
16491     */
16492    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16493            final PackageSetting ps, final int userId) {
16494        if (ps.pkg == null) {
16495            return;
16496        }
16497
16498        // These are flags that can change base on user actions.
16499        final int userSettableMask = FLAG_PERMISSION_USER_SET
16500                | FLAG_PERMISSION_USER_FIXED
16501                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16502                | FLAG_PERMISSION_REVIEW_REQUIRED;
16503
16504        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16505                | FLAG_PERMISSION_POLICY_FIXED;
16506
16507        boolean writeInstallPermissions = false;
16508        boolean writeRuntimePermissions = false;
16509
16510        final int permissionCount = ps.pkg.requestedPermissions.size();
16511        for (int i = 0; i < permissionCount; i++) {
16512            String permission = ps.pkg.requestedPermissions.get(i);
16513
16514            BasePermission bp = mSettings.mPermissions.get(permission);
16515            if (bp == null) {
16516                continue;
16517            }
16518
16519            // If shared user we just reset the state to which only this app contributed.
16520            if (ps.sharedUser != null) {
16521                boolean used = false;
16522                final int packageCount = ps.sharedUser.packages.size();
16523                for (int j = 0; j < packageCount; j++) {
16524                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16525                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16526                            && pkg.pkg.requestedPermissions.contains(permission)) {
16527                        used = true;
16528                        break;
16529                    }
16530                }
16531                if (used) {
16532                    continue;
16533                }
16534            }
16535
16536            PermissionsState permissionsState = ps.getPermissionsState();
16537
16538            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16539
16540            // Always clear the user settable flags.
16541            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16542                    bp.name) != null;
16543            // If permission review is enabled and this is a legacy app, mark the
16544            // permission as requiring a review as this is the initial state.
16545            int flags = 0;
16546            if (Build.PERMISSIONS_REVIEW_REQUIRED
16547                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16548                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16549            }
16550            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16551                if (hasInstallState) {
16552                    writeInstallPermissions = true;
16553                } else {
16554                    writeRuntimePermissions = true;
16555                }
16556            }
16557
16558            // Below is only runtime permission handling.
16559            if (!bp.isRuntime()) {
16560                continue;
16561            }
16562
16563            // Never clobber system or policy.
16564            if ((oldFlags & policyOrSystemFlags) != 0) {
16565                continue;
16566            }
16567
16568            // If this permission was granted by default, make sure it is.
16569            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16570                if (permissionsState.grantRuntimePermission(bp, userId)
16571                        != PERMISSION_OPERATION_FAILURE) {
16572                    writeRuntimePermissions = true;
16573                }
16574            // If permission review is enabled the permissions for a legacy apps
16575            // are represented as constantly granted runtime ones, so don't revoke.
16576            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16577                // Otherwise, reset the permission.
16578                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16579                switch (revokeResult) {
16580                    case PERMISSION_OPERATION_SUCCESS:
16581                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16582                        writeRuntimePermissions = true;
16583                        final int appId = ps.appId;
16584                        mHandler.post(new Runnable() {
16585                            @Override
16586                            public void run() {
16587                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16588                            }
16589                        });
16590                    } break;
16591                }
16592            }
16593        }
16594
16595        // Synchronously write as we are taking permissions away.
16596        if (writeRuntimePermissions) {
16597            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16598        }
16599
16600        // Synchronously write as we are taking permissions away.
16601        if (writeInstallPermissions) {
16602            mSettings.writeLPr();
16603        }
16604    }
16605
16606    /**
16607     * Remove entries from the keystore daemon. Will only remove it if the
16608     * {@code appId} is valid.
16609     */
16610    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16611        if (appId < 0) {
16612            return;
16613        }
16614
16615        final KeyStore keyStore = KeyStore.getInstance();
16616        if (keyStore != null) {
16617            if (userId == UserHandle.USER_ALL) {
16618                for (final int individual : sUserManager.getUserIds()) {
16619                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16620                }
16621            } else {
16622                keyStore.clearUid(UserHandle.getUid(userId, appId));
16623            }
16624        } else {
16625            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16626        }
16627    }
16628
16629    @Override
16630    public void deleteApplicationCacheFiles(final String packageName,
16631            final IPackageDataObserver observer) {
16632        final int userId = UserHandle.getCallingUserId();
16633        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16634    }
16635
16636    @Override
16637    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16638            final IPackageDataObserver observer) {
16639        mContext.enforceCallingOrSelfPermission(
16640                android.Manifest.permission.DELETE_CACHE_FILES, null);
16641        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16642                /* requireFullPermission= */ true, /* checkShell= */ false,
16643                "delete application cache files");
16644
16645        final PackageParser.Package pkg;
16646        synchronized (mPackages) {
16647            pkg = mPackages.get(packageName);
16648        }
16649
16650        // Queue up an async operation since the package deletion may take a little while.
16651        mHandler.post(new Runnable() {
16652            public void run() {
16653                synchronized (mInstallLock) {
16654                    final int flags = StorageManager.FLAG_STORAGE_DE
16655                            | StorageManager.FLAG_STORAGE_CE;
16656                    // We're only clearing cache files, so we don't care if the
16657                    // app is unfrozen and still able to run
16658                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16659                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16660                }
16661                clearExternalStorageDataSync(packageName, userId, false);
16662                if (observer != null) {
16663                    try {
16664                        observer.onRemoveCompleted(packageName, true);
16665                    } catch (RemoteException e) {
16666                        Log.i(TAG, "Observer no longer exists.");
16667                    }
16668                }
16669            }
16670        });
16671    }
16672
16673    @Override
16674    public void getPackageSizeInfo(final String packageName, int userHandle,
16675            final IPackageStatsObserver observer) {
16676        mContext.enforceCallingOrSelfPermission(
16677                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16678        if (packageName == null) {
16679            throw new IllegalArgumentException("Attempt to get size of null packageName");
16680        }
16681
16682        PackageStats stats = new PackageStats(packageName, userHandle);
16683
16684        /*
16685         * Queue up an async operation since the package measurement may take a
16686         * little while.
16687         */
16688        Message msg = mHandler.obtainMessage(INIT_COPY);
16689        msg.obj = new MeasureParams(stats, observer);
16690        mHandler.sendMessage(msg);
16691    }
16692
16693    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16694        final PackageSetting ps;
16695        synchronized (mPackages) {
16696            ps = mSettings.mPackages.get(packageName);
16697            if (ps == null) {
16698                Slog.w(TAG, "Failed to find settings for " + packageName);
16699                return false;
16700            }
16701        }
16702        try {
16703            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16704                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16705                    ps.getCeDataInode(userId), ps.codePathString, stats);
16706        } catch (InstallerException e) {
16707            Slog.w(TAG, String.valueOf(e));
16708            return false;
16709        }
16710
16711        // For now, ignore code size of packages on system partition
16712        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16713            stats.codeSize = 0;
16714        }
16715
16716        return true;
16717    }
16718
16719    private int getUidTargetSdkVersionLockedLPr(int uid) {
16720        Object obj = mSettings.getUserIdLPr(uid);
16721        if (obj instanceof SharedUserSetting) {
16722            final SharedUserSetting sus = (SharedUserSetting) obj;
16723            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16724            final Iterator<PackageSetting> it = sus.packages.iterator();
16725            while (it.hasNext()) {
16726                final PackageSetting ps = it.next();
16727                if (ps.pkg != null) {
16728                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16729                    if (v < vers) vers = v;
16730                }
16731            }
16732            return vers;
16733        } else if (obj instanceof PackageSetting) {
16734            final PackageSetting ps = (PackageSetting) obj;
16735            if (ps.pkg != null) {
16736                return ps.pkg.applicationInfo.targetSdkVersion;
16737            }
16738        }
16739        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16740    }
16741
16742    @Override
16743    public void addPreferredActivity(IntentFilter filter, int match,
16744            ComponentName[] set, ComponentName activity, int userId) {
16745        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16746                "Adding preferred");
16747    }
16748
16749    private void addPreferredActivityInternal(IntentFilter filter, int match,
16750            ComponentName[] set, ComponentName activity, boolean always, int userId,
16751            String opname) {
16752        // writer
16753        int callingUid = Binder.getCallingUid();
16754        enforceCrossUserPermission(callingUid, userId,
16755                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16756        if (filter.countActions() == 0) {
16757            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16758            return;
16759        }
16760        synchronized (mPackages) {
16761            if (mContext.checkCallingOrSelfPermission(
16762                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16763                    != PackageManager.PERMISSION_GRANTED) {
16764                if (getUidTargetSdkVersionLockedLPr(callingUid)
16765                        < Build.VERSION_CODES.FROYO) {
16766                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16767                            + callingUid);
16768                    return;
16769                }
16770                mContext.enforceCallingOrSelfPermission(
16771                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16772            }
16773
16774            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16775            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16776                    + userId + ":");
16777            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16778            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16779            scheduleWritePackageRestrictionsLocked(userId);
16780            postPreferredActivityChangedBroadcast(userId);
16781        }
16782    }
16783
16784    private void postPreferredActivityChangedBroadcast(int userId) {
16785        mHandler.post(() -> {
16786            final IActivityManager am = ActivityManagerNative.getDefault();
16787            if (am == null) {
16788                return;
16789            }
16790
16791            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16792            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16793            try {
16794                am.broadcastIntent(null, intent, null, null,
16795                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16796                        null, false, false, userId);
16797            } catch (RemoteException e) {
16798            }
16799        });
16800    }
16801
16802    @Override
16803    public void replacePreferredActivity(IntentFilter filter, int match,
16804            ComponentName[] set, ComponentName activity, int userId) {
16805        if (filter.countActions() != 1) {
16806            throw new IllegalArgumentException(
16807                    "replacePreferredActivity expects filter to have only 1 action.");
16808        }
16809        if (filter.countDataAuthorities() != 0
16810                || filter.countDataPaths() != 0
16811                || filter.countDataSchemes() > 1
16812                || filter.countDataTypes() != 0) {
16813            throw new IllegalArgumentException(
16814                    "replacePreferredActivity expects filter to have no data authorities, " +
16815                    "paths, or types; and at most one scheme.");
16816        }
16817
16818        final int callingUid = Binder.getCallingUid();
16819        enforceCrossUserPermission(callingUid, userId,
16820                true /* requireFullPermission */, false /* checkShell */,
16821                "replace preferred activity");
16822        synchronized (mPackages) {
16823            if (mContext.checkCallingOrSelfPermission(
16824                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16825                    != PackageManager.PERMISSION_GRANTED) {
16826                if (getUidTargetSdkVersionLockedLPr(callingUid)
16827                        < Build.VERSION_CODES.FROYO) {
16828                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16829                            + Binder.getCallingUid());
16830                    return;
16831                }
16832                mContext.enforceCallingOrSelfPermission(
16833                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16834            }
16835
16836            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16837            if (pir != null) {
16838                // Get all of the existing entries that exactly match this filter.
16839                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16840                if (existing != null && existing.size() == 1) {
16841                    PreferredActivity cur = existing.get(0);
16842                    if (DEBUG_PREFERRED) {
16843                        Slog.i(TAG, "Checking replace of preferred:");
16844                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16845                        if (!cur.mPref.mAlways) {
16846                            Slog.i(TAG, "  -- CUR; not mAlways!");
16847                        } else {
16848                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16849                            Slog.i(TAG, "  -- CUR: mSet="
16850                                    + Arrays.toString(cur.mPref.mSetComponents));
16851                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16852                            Slog.i(TAG, "  -- NEW: mMatch="
16853                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16854                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16855                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16856                        }
16857                    }
16858                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16859                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16860                            && cur.mPref.sameSet(set)) {
16861                        // Setting the preferred activity to what it happens to be already
16862                        if (DEBUG_PREFERRED) {
16863                            Slog.i(TAG, "Replacing with same preferred activity "
16864                                    + cur.mPref.mShortComponent + " for user "
16865                                    + userId + ":");
16866                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16867                        }
16868                        return;
16869                    }
16870                }
16871
16872                if (existing != null) {
16873                    if (DEBUG_PREFERRED) {
16874                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16875                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16876                    }
16877                    for (int i = 0; i < existing.size(); i++) {
16878                        PreferredActivity pa = existing.get(i);
16879                        if (DEBUG_PREFERRED) {
16880                            Slog.i(TAG, "Removing existing preferred activity "
16881                                    + pa.mPref.mComponent + ":");
16882                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16883                        }
16884                        pir.removeFilter(pa);
16885                    }
16886                }
16887            }
16888            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16889                    "Replacing preferred");
16890        }
16891    }
16892
16893    @Override
16894    public void clearPackagePreferredActivities(String packageName) {
16895        final int uid = Binder.getCallingUid();
16896        // writer
16897        synchronized (mPackages) {
16898            PackageParser.Package pkg = mPackages.get(packageName);
16899            if (pkg == null || pkg.applicationInfo.uid != uid) {
16900                if (mContext.checkCallingOrSelfPermission(
16901                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16902                        != PackageManager.PERMISSION_GRANTED) {
16903                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16904                            < Build.VERSION_CODES.FROYO) {
16905                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16906                                + Binder.getCallingUid());
16907                        return;
16908                    }
16909                    mContext.enforceCallingOrSelfPermission(
16910                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16911                }
16912            }
16913
16914            int user = UserHandle.getCallingUserId();
16915            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16916                scheduleWritePackageRestrictionsLocked(user);
16917            }
16918        }
16919    }
16920
16921    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16922    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16923        ArrayList<PreferredActivity> removed = null;
16924        boolean changed = false;
16925        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16926            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16927            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16928            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16929                continue;
16930            }
16931            Iterator<PreferredActivity> it = pir.filterIterator();
16932            while (it.hasNext()) {
16933                PreferredActivity pa = it.next();
16934                // Mark entry for removal only if it matches the package name
16935                // and the entry is of type "always".
16936                if (packageName == null ||
16937                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16938                                && pa.mPref.mAlways)) {
16939                    if (removed == null) {
16940                        removed = new ArrayList<PreferredActivity>();
16941                    }
16942                    removed.add(pa);
16943                }
16944            }
16945            if (removed != null) {
16946                for (int j=0; j<removed.size(); j++) {
16947                    PreferredActivity pa = removed.get(j);
16948                    pir.removeFilter(pa);
16949                }
16950                changed = true;
16951            }
16952        }
16953        if (changed) {
16954            postPreferredActivityChangedBroadcast(userId);
16955        }
16956        return changed;
16957    }
16958
16959    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16960    private void clearIntentFilterVerificationsLPw(int userId) {
16961        final int packageCount = mPackages.size();
16962        for (int i = 0; i < packageCount; i++) {
16963            PackageParser.Package pkg = mPackages.valueAt(i);
16964            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16965        }
16966    }
16967
16968    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16969    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16970        if (userId == UserHandle.USER_ALL) {
16971            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16972                    sUserManager.getUserIds())) {
16973                for (int oneUserId : sUserManager.getUserIds()) {
16974                    scheduleWritePackageRestrictionsLocked(oneUserId);
16975                }
16976            }
16977        } else {
16978            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16979                scheduleWritePackageRestrictionsLocked(userId);
16980            }
16981        }
16982    }
16983
16984    void clearDefaultBrowserIfNeeded(String packageName) {
16985        for (int oneUserId : sUserManager.getUserIds()) {
16986            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16987            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16988            if (packageName.equals(defaultBrowserPackageName)) {
16989                setDefaultBrowserPackageName(null, oneUserId);
16990            }
16991        }
16992    }
16993
16994    @Override
16995    public void resetApplicationPreferences(int userId) {
16996        mContext.enforceCallingOrSelfPermission(
16997                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16998        final long identity = Binder.clearCallingIdentity();
16999        // writer
17000        try {
17001            synchronized (mPackages) {
17002                clearPackagePreferredActivitiesLPw(null, userId);
17003                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17004                // TODO: We have to reset the default SMS and Phone. This requires
17005                // significant refactoring to keep all default apps in the package
17006                // manager (cleaner but more work) or have the services provide
17007                // callbacks to the package manager to request a default app reset.
17008                applyFactoryDefaultBrowserLPw(userId);
17009                clearIntentFilterVerificationsLPw(userId);
17010                primeDomainVerificationsLPw(userId);
17011                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17012                scheduleWritePackageRestrictionsLocked(userId);
17013            }
17014            resetNetworkPolicies(userId);
17015        } finally {
17016            Binder.restoreCallingIdentity(identity);
17017        }
17018    }
17019
17020    @Override
17021    public int getPreferredActivities(List<IntentFilter> outFilters,
17022            List<ComponentName> outActivities, String packageName) {
17023
17024        int num = 0;
17025        final int userId = UserHandle.getCallingUserId();
17026        // reader
17027        synchronized (mPackages) {
17028            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17029            if (pir != null) {
17030                final Iterator<PreferredActivity> it = pir.filterIterator();
17031                while (it.hasNext()) {
17032                    final PreferredActivity pa = it.next();
17033                    if (packageName == null
17034                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17035                                    && pa.mPref.mAlways)) {
17036                        if (outFilters != null) {
17037                            outFilters.add(new IntentFilter(pa));
17038                        }
17039                        if (outActivities != null) {
17040                            outActivities.add(pa.mPref.mComponent);
17041                        }
17042                    }
17043                }
17044            }
17045        }
17046
17047        return num;
17048    }
17049
17050    @Override
17051    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17052            int userId) {
17053        int callingUid = Binder.getCallingUid();
17054        if (callingUid != Process.SYSTEM_UID) {
17055            throw new SecurityException(
17056                    "addPersistentPreferredActivity can only be run by the system");
17057        }
17058        if (filter.countActions() == 0) {
17059            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17060            return;
17061        }
17062        synchronized (mPackages) {
17063            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17064                    ":");
17065            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17066            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17067                    new PersistentPreferredActivity(filter, activity));
17068            scheduleWritePackageRestrictionsLocked(userId);
17069            postPreferredActivityChangedBroadcast(userId);
17070        }
17071    }
17072
17073    @Override
17074    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17075        int callingUid = Binder.getCallingUid();
17076        if (callingUid != Process.SYSTEM_UID) {
17077            throw new SecurityException(
17078                    "clearPackagePersistentPreferredActivities can only be run by the system");
17079        }
17080        ArrayList<PersistentPreferredActivity> removed = null;
17081        boolean changed = false;
17082        synchronized (mPackages) {
17083            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17084                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17085                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17086                        .valueAt(i);
17087                if (userId != thisUserId) {
17088                    continue;
17089                }
17090                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17091                while (it.hasNext()) {
17092                    PersistentPreferredActivity ppa = it.next();
17093                    // Mark entry for removal only if it matches the package name.
17094                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17095                        if (removed == null) {
17096                            removed = new ArrayList<PersistentPreferredActivity>();
17097                        }
17098                        removed.add(ppa);
17099                    }
17100                }
17101                if (removed != null) {
17102                    for (int j=0; j<removed.size(); j++) {
17103                        PersistentPreferredActivity ppa = removed.get(j);
17104                        ppir.removeFilter(ppa);
17105                    }
17106                    changed = true;
17107                }
17108            }
17109
17110            if (changed) {
17111                scheduleWritePackageRestrictionsLocked(userId);
17112                postPreferredActivityChangedBroadcast(userId);
17113            }
17114        }
17115    }
17116
17117    /**
17118     * Common machinery for picking apart a restored XML blob and passing
17119     * it to a caller-supplied functor to be applied to the running system.
17120     */
17121    private void restoreFromXml(XmlPullParser parser, int userId,
17122            String expectedStartTag, BlobXmlRestorer functor)
17123            throws IOException, XmlPullParserException {
17124        int type;
17125        while ((type = parser.next()) != XmlPullParser.START_TAG
17126                && type != XmlPullParser.END_DOCUMENT) {
17127        }
17128        if (type != XmlPullParser.START_TAG) {
17129            // oops didn't find a start tag?!
17130            if (DEBUG_BACKUP) {
17131                Slog.e(TAG, "Didn't find start tag during restore");
17132            }
17133            return;
17134        }
17135Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17136        // this is supposed to be TAG_PREFERRED_BACKUP
17137        if (!expectedStartTag.equals(parser.getName())) {
17138            if (DEBUG_BACKUP) {
17139                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17140            }
17141            return;
17142        }
17143
17144        // skip interfering stuff, then we're aligned with the backing implementation
17145        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17146Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17147        functor.apply(parser, userId);
17148    }
17149
17150    private interface BlobXmlRestorer {
17151        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17152    }
17153
17154    /**
17155     * Non-Binder method, support for the backup/restore mechanism: write the
17156     * full set of preferred activities in its canonical XML format.  Returns the
17157     * XML output as a byte array, or null if there is none.
17158     */
17159    @Override
17160    public byte[] getPreferredActivityBackup(int userId) {
17161        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17162            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17163        }
17164
17165        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17166        try {
17167            final XmlSerializer serializer = new FastXmlSerializer();
17168            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17169            serializer.startDocument(null, true);
17170            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17171
17172            synchronized (mPackages) {
17173                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17174            }
17175
17176            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17177            serializer.endDocument();
17178            serializer.flush();
17179        } catch (Exception e) {
17180            if (DEBUG_BACKUP) {
17181                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17182            }
17183            return null;
17184        }
17185
17186        return dataStream.toByteArray();
17187    }
17188
17189    @Override
17190    public void restorePreferredActivities(byte[] backup, int userId) {
17191        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17192            throw new SecurityException("Only the system may call restorePreferredActivities()");
17193        }
17194
17195        try {
17196            final XmlPullParser parser = Xml.newPullParser();
17197            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17198            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17199                    new BlobXmlRestorer() {
17200                        @Override
17201                        public void apply(XmlPullParser parser, int userId)
17202                                throws XmlPullParserException, IOException {
17203                            synchronized (mPackages) {
17204                                mSettings.readPreferredActivitiesLPw(parser, userId);
17205                            }
17206                        }
17207                    } );
17208        } catch (Exception e) {
17209            if (DEBUG_BACKUP) {
17210                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17211            }
17212        }
17213    }
17214
17215    /**
17216     * Non-Binder method, support for the backup/restore mechanism: write the
17217     * default browser (etc) settings in its canonical XML format.  Returns the default
17218     * browser XML representation as a byte array, or null if there is none.
17219     */
17220    @Override
17221    public byte[] getDefaultAppsBackup(int userId) {
17222        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17223            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17224        }
17225
17226        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17227        try {
17228            final XmlSerializer serializer = new FastXmlSerializer();
17229            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17230            serializer.startDocument(null, true);
17231            serializer.startTag(null, TAG_DEFAULT_APPS);
17232
17233            synchronized (mPackages) {
17234                mSettings.writeDefaultAppsLPr(serializer, userId);
17235            }
17236
17237            serializer.endTag(null, TAG_DEFAULT_APPS);
17238            serializer.endDocument();
17239            serializer.flush();
17240        } catch (Exception e) {
17241            if (DEBUG_BACKUP) {
17242                Slog.e(TAG, "Unable to write default apps for backup", e);
17243            }
17244            return null;
17245        }
17246
17247        return dataStream.toByteArray();
17248    }
17249
17250    @Override
17251    public void restoreDefaultApps(byte[] backup, int userId) {
17252        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17253            throw new SecurityException("Only the system may call restoreDefaultApps()");
17254        }
17255
17256        try {
17257            final XmlPullParser parser = Xml.newPullParser();
17258            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17259            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17260                    new BlobXmlRestorer() {
17261                        @Override
17262                        public void apply(XmlPullParser parser, int userId)
17263                                throws XmlPullParserException, IOException {
17264                            synchronized (mPackages) {
17265                                mSettings.readDefaultAppsLPw(parser, userId);
17266                            }
17267                        }
17268                    } );
17269        } catch (Exception e) {
17270            if (DEBUG_BACKUP) {
17271                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17272            }
17273        }
17274    }
17275
17276    @Override
17277    public byte[] getIntentFilterVerificationBackup(int userId) {
17278        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17279            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17280        }
17281
17282        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17283        try {
17284            final XmlSerializer serializer = new FastXmlSerializer();
17285            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17286            serializer.startDocument(null, true);
17287            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17288
17289            synchronized (mPackages) {
17290                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17291            }
17292
17293            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17294            serializer.endDocument();
17295            serializer.flush();
17296        } catch (Exception e) {
17297            if (DEBUG_BACKUP) {
17298                Slog.e(TAG, "Unable to write default apps for backup", e);
17299            }
17300            return null;
17301        }
17302
17303        return dataStream.toByteArray();
17304    }
17305
17306    @Override
17307    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17308        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17309            throw new SecurityException("Only the system may call restorePreferredActivities()");
17310        }
17311
17312        try {
17313            final XmlPullParser parser = Xml.newPullParser();
17314            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17315            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17316                    new BlobXmlRestorer() {
17317                        @Override
17318                        public void apply(XmlPullParser parser, int userId)
17319                                throws XmlPullParserException, IOException {
17320                            synchronized (mPackages) {
17321                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17322                                mSettings.writeLPr();
17323                            }
17324                        }
17325                    } );
17326        } catch (Exception e) {
17327            if (DEBUG_BACKUP) {
17328                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17329            }
17330        }
17331    }
17332
17333    @Override
17334    public byte[] getPermissionGrantBackup(int userId) {
17335        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17336            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17337        }
17338
17339        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17340        try {
17341            final XmlSerializer serializer = new FastXmlSerializer();
17342            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17343            serializer.startDocument(null, true);
17344            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17345
17346            synchronized (mPackages) {
17347                serializeRuntimePermissionGrantsLPr(serializer, userId);
17348            }
17349
17350            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17351            serializer.endDocument();
17352            serializer.flush();
17353        } catch (Exception e) {
17354            if (DEBUG_BACKUP) {
17355                Slog.e(TAG, "Unable to write default apps for backup", e);
17356            }
17357            return null;
17358        }
17359
17360        return dataStream.toByteArray();
17361    }
17362
17363    @Override
17364    public void restorePermissionGrants(byte[] backup, int userId) {
17365        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17366            throw new SecurityException("Only the system may call restorePermissionGrants()");
17367        }
17368
17369        try {
17370            final XmlPullParser parser = Xml.newPullParser();
17371            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17372            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17373                    new BlobXmlRestorer() {
17374                        @Override
17375                        public void apply(XmlPullParser parser, int userId)
17376                                throws XmlPullParserException, IOException {
17377                            synchronized (mPackages) {
17378                                processRestoredPermissionGrantsLPr(parser, userId);
17379                            }
17380                        }
17381                    } );
17382        } catch (Exception e) {
17383            if (DEBUG_BACKUP) {
17384                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17385            }
17386        }
17387    }
17388
17389    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17390            throws IOException {
17391        serializer.startTag(null, TAG_ALL_GRANTS);
17392
17393        final int N = mSettings.mPackages.size();
17394        for (int i = 0; i < N; i++) {
17395            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17396            boolean pkgGrantsKnown = false;
17397
17398            PermissionsState packagePerms = ps.getPermissionsState();
17399
17400            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17401                final int grantFlags = state.getFlags();
17402                // only look at grants that are not system/policy fixed
17403                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17404                    final boolean isGranted = state.isGranted();
17405                    // And only back up the user-twiddled state bits
17406                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17407                        final String packageName = mSettings.mPackages.keyAt(i);
17408                        if (!pkgGrantsKnown) {
17409                            serializer.startTag(null, TAG_GRANT);
17410                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17411                            pkgGrantsKnown = true;
17412                        }
17413
17414                        final boolean userSet =
17415                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17416                        final boolean userFixed =
17417                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17418                        final boolean revoke =
17419                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17420
17421                        serializer.startTag(null, TAG_PERMISSION);
17422                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17423                        if (isGranted) {
17424                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17425                        }
17426                        if (userSet) {
17427                            serializer.attribute(null, ATTR_USER_SET, "true");
17428                        }
17429                        if (userFixed) {
17430                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17431                        }
17432                        if (revoke) {
17433                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17434                        }
17435                        serializer.endTag(null, TAG_PERMISSION);
17436                    }
17437                }
17438            }
17439
17440            if (pkgGrantsKnown) {
17441                serializer.endTag(null, TAG_GRANT);
17442            }
17443        }
17444
17445        serializer.endTag(null, TAG_ALL_GRANTS);
17446    }
17447
17448    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17449            throws XmlPullParserException, IOException {
17450        String pkgName = null;
17451        int outerDepth = parser.getDepth();
17452        int type;
17453        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17454                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17455            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17456                continue;
17457            }
17458
17459            final String tagName = parser.getName();
17460            if (tagName.equals(TAG_GRANT)) {
17461                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17462                if (DEBUG_BACKUP) {
17463                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17464                }
17465            } else if (tagName.equals(TAG_PERMISSION)) {
17466
17467                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17468                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17469
17470                int newFlagSet = 0;
17471                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17472                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17473                }
17474                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17475                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17476                }
17477                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17478                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17479                }
17480                if (DEBUG_BACKUP) {
17481                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17482                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17483                }
17484                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17485                if (ps != null) {
17486                    // Already installed so we apply the grant immediately
17487                    if (DEBUG_BACKUP) {
17488                        Slog.v(TAG, "        + already installed; applying");
17489                    }
17490                    PermissionsState perms = ps.getPermissionsState();
17491                    BasePermission bp = mSettings.mPermissions.get(permName);
17492                    if (bp != null) {
17493                        if (isGranted) {
17494                            perms.grantRuntimePermission(bp, userId);
17495                        }
17496                        if (newFlagSet != 0) {
17497                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17498                        }
17499                    }
17500                } else {
17501                    // Need to wait for post-restore install to apply the grant
17502                    if (DEBUG_BACKUP) {
17503                        Slog.v(TAG, "        - not yet installed; saving for later");
17504                    }
17505                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17506                            isGranted, newFlagSet, userId);
17507                }
17508            } else {
17509                PackageManagerService.reportSettingsProblem(Log.WARN,
17510                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17511                XmlUtils.skipCurrentTag(parser);
17512            }
17513        }
17514
17515        scheduleWriteSettingsLocked();
17516        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17517    }
17518
17519    @Override
17520    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17521            int sourceUserId, int targetUserId, int flags) {
17522        mContext.enforceCallingOrSelfPermission(
17523                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17524        int callingUid = Binder.getCallingUid();
17525        enforceOwnerRights(ownerPackage, callingUid);
17526        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17527        if (intentFilter.countActions() == 0) {
17528            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17529            return;
17530        }
17531        synchronized (mPackages) {
17532            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17533                    ownerPackage, targetUserId, flags);
17534            CrossProfileIntentResolver resolver =
17535                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17536            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17537            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17538            if (existing != null) {
17539                int size = existing.size();
17540                for (int i = 0; i < size; i++) {
17541                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17542                        return;
17543                    }
17544                }
17545            }
17546            resolver.addFilter(newFilter);
17547            scheduleWritePackageRestrictionsLocked(sourceUserId);
17548        }
17549    }
17550
17551    @Override
17552    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17553        mContext.enforceCallingOrSelfPermission(
17554                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17555        int callingUid = Binder.getCallingUid();
17556        enforceOwnerRights(ownerPackage, callingUid);
17557        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17558        synchronized (mPackages) {
17559            CrossProfileIntentResolver resolver =
17560                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17561            ArraySet<CrossProfileIntentFilter> set =
17562                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17563            for (CrossProfileIntentFilter filter : set) {
17564                if (filter.getOwnerPackage().equals(ownerPackage)) {
17565                    resolver.removeFilter(filter);
17566                }
17567            }
17568            scheduleWritePackageRestrictionsLocked(sourceUserId);
17569        }
17570    }
17571
17572    // Enforcing that callingUid is owning pkg on userId
17573    private void enforceOwnerRights(String pkg, int callingUid) {
17574        // The system owns everything.
17575        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17576            return;
17577        }
17578        int callingUserId = UserHandle.getUserId(callingUid);
17579        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17580        if (pi == null) {
17581            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17582                    + callingUserId);
17583        }
17584        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17585            throw new SecurityException("Calling uid " + callingUid
17586                    + " does not own package " + pkg);
17587        }
17588    }
17589
17590    @Override
17591    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17592        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17593    }
17594
17595    private Intent getHomeIntent() {
17596        Intent intent = new Intent(Intent.ACTION_MAIN);
17597        intent.addCategory(Intent.CATEGORY_HOME);
17598        intent.addCategory(Intent.CATEGORY_DEFAULT);
17599        return intent;
17600    }
17601
17602    private IntentFilter getHomeFilter() {
17603        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17604        filter.addCategory(Intent.CATEGORY_HOME);
17605        filter.addCategory(Intent.CATEGORY_DEFAULT);
17606        return filter;
17607    }
17608
17609    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17610            int userId) {
17611        Intent intent  = getHomeIntent();
17612        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17613                PackageManager.GET_META_DATA, userId);
17614        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17615                true, false, false, userId);
17616
17617        allHomeCandidates.clear();
17618        if (list != null) {
17619            for (ResolveInfo ri : list) {
17620                allHomeCandidates.add(ri);
17621            }
17622        }
17623        return (preferred == null || preferred.activityInfo == null)
17624                ? null
17625                : new ComponentName(preferred.activityInfo.packageName,
17626                        preferred.activityInfo.name);
17627    }
17628
17629    @Override
17630    public void setHomeActivity(ComponentName comp, int userId) {
17631        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17632        getHomeActivitiesAsUser(homeActivities, userId);
17633
17634        boolean found = false;
17635
17636        final int size = homeActivities.size();
17637        final ComponentName[] set = new ComponentName[size];
17638        for (int i = 0; i < size; i++) {
17639            final ResolveInfo candidate = homeActivities.get(i);
17640            final ActivityInfo info = candidate.activityInfo;
17641            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17642            set[i] = activityName;
17643            if (!found && activityName.equals(comp)) {
17644                found = true;
17645            }
17646        }
17647        if (!found) {
17648            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17649                    + userId);
17650        }
17651        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17652                set, comp, userId);
17653    }
17654
17655    private @Nullable String getSetupWizardPackageName() {
17656        final Intent intent = new Intent(Intent.ACTION_MAIN);
17657        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17658
17659        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17660                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17661                        | MATCH_DISABLED_COMPONENTS,
17662                UserHandle.myUserId());
17663        if (matches.size() == 1) {
17664            return matches.get(0).getComponentInfo().packageName;
17665        } else {
17666            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17667                    + ": matches=" + matches);
17668            return null;
17669        }
17670    }
17671
17672    @Override
17673    public void setApplicationEnabledSetting(String appPackageName,
17674            int newState, int flags, int userId, String callingPackage) {
17675        if (!sUserManager.exists(userId)) return;
17676        if (callingPackage == null) {
17677            callingPackage = Integer.toString(Binder.getCallingUid());
17678        }
17679        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17680    }
17681
17682    @Override
17683    public void setComponentEnabledSetting(ComponentName componentName,
17684            int newState, int flags, int userId) {
17685        if (!sUserManager.exists(userId)) return;
17686        setEnabledSetting(componentName.getPackageName(),
17687                componentName.getClassName(), newState, flags, userId, null);
17688    }
17689
17690    private void setEnabledSetting(final String packageName, String className, int newState,
17691            final int flags, int userId, String callingPackage) {
17692        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17693              || newState == COMPONENT_ENABLED_STATE_ENABLED
17694              || newState == COMPONENT_ENABLED_STATE_DISABLED
17695              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17696              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17697            throw new IllegalArgumentException("Invalid new component state: "
17698                    + newState);
17699        }
17700        PackageSetting pkgSetting;
17701        final int uid = Binder.getCallingUid();
17702        final int permission;
17703        if (uid == Process.SYSTEM_UID) {
17704            permission = PackageManager.PERMISSION_GRANTED;
17705        } else {
17706            permission = mContext.checkCallingOrSelfPermission(
17707                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17708        }
17709        enforceCrossUserPermission(uid, userId,
17710                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17711        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17712        boolean sendNow = false;
17713        boolean isApp = (className == null);
17714        String componentName = isApp ? packageName : className;
17715        int packageUid = -1;
17716        ArrayList<String> components;
17717
17718        // writer
17719        synchronized (mPackages) {
17720            pkgSetting = mSettings.mPackages.get(packageName);
17721            if (pkgSetting == null) {
17722                if (className == null) {
17723                    throw new IllegalArgumentException("Unknown package: " + packageName);
17724                }
17725                throw new IllegalArgumentException(
17726                        "Unknown component: " + packageName + "/" + className);
17727            }
17728        }
17729
17730        // Limit who can change which apps
17731        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17732            // Don't allow apps that don't have permission to modify other apps
17733            if (!allowedByPermission) {
17734                throw new SecurityException(
17735                        "Permission Denial: attempt to change component state from pid="
17736                        + Binder.getCallingPid()
17737                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17738            }
17739            // Don't allow changing protected packages.
17740            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17741                throw new SecurityException("Cannot disable a protected package: " + packageName);
17742            }
17743        }
17744
17745        synchronized (mPackages) {
17746            if (uid == Process.SHELL_UID) {
17747                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17748                int oldState = pkgSetting.getEnabled(userId);
17749                if (className == null
17750                    &&
17751                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17752                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17753                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17754                    &&
17755                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17756                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17757                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17758                    // ok
17759                } else {
17760                    throw new SecurityException(
17761                            "Shell cannot change component state for " + packageName + "/"
17762                            + className + " to " + newState);
17763                }
17764            }
17765            if (className == null) {
17766                // We're dealing with an application/package level state change
17767                if (pkgSetting.getEnabled(userId) == newState) {
17768                    // Nothing to do
17769                    return;
17770                }
17771                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17772                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17773                    // Don't care about who enables an app.
17774                    callingPackage = null;
17775                }
17776                pkgSetting.setEnabled(newState, userId, callingPackage);
17777                // pkgSetting.pkg.mSetEnabled = newState;
17778            } else {
17779                // We're dealing with a component level state change
17780                // First, verify that this is a valid class name.
17781                PackageParser.Package pkg = pkgSetting.pkg;
17782                if (pkg == null || !pkg.hasComponentClassName(className)) {
17783                    if (pkg != null &&
17784                            pkg.applicationInfo.targetSdkVersion >=
17785                                    Build.VERSION_CODES.JELLY_BEAN) {
17786                        throw new IllegalArgumentException("Component class " + className
17787                                + " does not exist in " + packageName);
17788                    } else {
17789                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17790                                + className + " does not exist in " + packageName);
17791                    }
17792                }
17793                switch (newState) {
17794                case COMPONENT_ENABLED_STATE_ENABLED:
17795                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17796                        return;
17797                    }
17798                    break;
17799                case COMPONENT_ENABLED_STATE_DISABLED:
17800                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17801                        return;
17802                    }
17803                    break;
17804                case COMPONENT_ENABLED_STATE_DEFAULT:
17805                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17806                        return;
17807                    }
17808                    break;
17809                default:
17810                    Slog.e(TAG, "Invalid new component state: " + newState);
17811                    return;
17812                }
17813            }
17814            scheduleWritePackageRestrictionsLocked(userId);
17815            components = mPendingBroadcasts.get(userId, packageName);
17816            final boolean newPackage = components == null;
17817            if (newPackage) {
17818                components = new ArrayList<String>();
17819            }
17820            if (!components.contains(componentName)) {
17821                components.add(componentName);
17822            }
17823            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17824                sendNow = true;
17825                // Purge entry from pending broadcast list if another one exists already
17826                // since we are sending one right away.
17827                mPendingBroadcasts.remove(userId, packageName);
17828            } else {
17829                if (newPackage) {
17830                    mPendingBroadcasts.put(userId, packageName, components);
17831                }
17832                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17833                    // Schedule a message
17834                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17835                }
17836            }
17837        }
17838
17839        long callingId = Binder.clearCallingIdentity();
17840        try {
17841            if (sendNow) {
17842                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17843                sendPackageChangedBroadcast(packageName,
17844                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17845            }
17846        } finally {
17847            Binder.restoreCallingIdentity(callingId);
17848        }
17849    }
17850
17851    @Override
17852    public void flushPackageRestrictionsAsUser(int userId) {
17853        if (!sUserManager.exists(userId)) {
17854            return;
17855        }
17856        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17857                false /* checkShell */, "flushPackageRestrictions");
17858        synchronized (mPackages) {
17859            mSettings.writePackageRestrictionsLPr(userId);
17860            mDirtyUsers.remove(userId);
17861            if (mDirtyUsers.isEmpty()) {
17862                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17863            }
17864        }
17865    }
17866
17867    private void sendPackageChangedBroadcast(String packageName,
17868            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17869        if (DEBUG_INSTALL)
17870            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17871                    + componentNames);
17872        Bundle extras = new Bundle(4);
17873        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17874        String nameList[] = new String[componentNames.size()];
17875        componentNames.toArray(nameList);
17876        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17877        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17878        extras.putInt(Intent.EXTRA_UID, packageUid);
17879        // If this is not reporting a change of the overall package, then only send it
17880        // to registered receivers.  We don't want to launch a swath of apps for every
17881        // little component state change.
17882        final int flags = !componentNames.contains(packageName)
17883                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17884        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17885                new int[] {UserHandle.getUserId(packageUid)});
17886    }
17887
17888    @Override
17889    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17890        if (!sUserManager.exists(userId)) return;
17891        final int uid = Binder.getCallingUid();
17892        final int permission = mContext.checkCallingOrSelfPermission(
17893                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17894        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17895        enforceCrossUserPermission(uid, userId,
17896                true /* requireFullPermission */, true /* checkShell */, "stop package");
17897        // writer
17898        synchronized (mPackages) {
17899            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17900                    allowedByPermission, uid, userId)) {
17901                scheduleWritePackageRestrictionsLocked(userId);
17902            }
17903        }
17904    }
17905
17906    @Override
17907    public String getInstallerPackageName(String packageName) {
17908        // reader
17909        synchronized (mPackages) {
17910            return mSettings.getInstallerPackageNameLPr(packageName);
17911        }
17912    }
17913
17914    public boolean isOrphaned(String packageName) {
17915        // reader
17916        synchronized (mPackages) {
17917            return mSettings.isOrphaned(packageName);
17918        }
17919    }
17920
17921    @Override
17922    public int getApplicationEnabledSetting(String packageName, int userId) {
17923        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17924        int uid = Binder.getCallingUid();
17925        enforceCrossUserPermission(uid, userId,
17926                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17927        // reader
17928        synchronized (mPackages) {
17929            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17930        }
17931    }
17932
17933    @Override
17934    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17935        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17936        int uid = Binder.getCallingUid();
17937        enforceCrossUserPermission(uid, userId,
17938                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17939        // reader
17940        synchronized (mPackages) {
17941            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17942        }
17943    }
17944
17945    @Override
17946    public void enterSafeMode() {
17947        enforceSystemOrRoot("Only the system can request entering safe mode");
17948
17949        if (!mSystemReady) {
17950            mSafeMode = true;
17951        }
17952    }
17953
17954    @Override
17955    public void systemReady() {
17956        mSystemReady = true;
17957
17958        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
17959        // disabled after already being started.
17960        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
17961                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
17962
17963        // Read the compatibilty setting when the system is ready.
17964        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17965                mContext.getContentResolver(),
17966                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17967        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17968        if (DEBUG_SETTINGS) {
17969            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17970        }
17971
17972        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17973
17974        synchronized (mPackages) {
17975            // Verify that all of the preferred activity components actually
17976            // exist.  It is possible for applications to be updated and at
17977            // that point remove a previously declared activity component that
17978            // had been set as a preferred activity.  We try to clean this up
17979            // the next time we encounter that preferred activity, but it is
17980            // possible for the user flow to never be able to return to that
17981            // situation so here we do a sanity check to make sure we haven't
17982            // left any junk around.
17983            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17984            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17985                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17986                removed.clear();
17987                for (PreferredActivity pa : pir.filterSet()) {
17988                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17989                        removed.add(pa);
17990                    }
17991                }
17992                if (removed.size() > 0) {
17993                    for (int r=0; r<removed.size(); r++) {
17994                        PreferredActivity pa = removed.get(r);
17995                        Slog.w(TAG, "Removing dangling preferred activity: "
17996                                + pa.mPref.mComponent);
17997                        pir.removeFilter(pa);
17998                    }
17999                    mSettings.writePackageRestrictionsLPr(
18000                            mSettings.mPreferredActivities.keyAt(i));
18001                }
18002            }
18003
18004            for (int userId : UserManagerService.getInstance().getUserIds()) {
18005                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18006                    grantPermissionsUserIds = ArrayUtils.appendInt(
18007                            grantPermissionsUserIds, userId);
18008                }
18009            }
18010        }
18011        sUserManager.systemReady();
18012
18013        // If we upgraded grant all default permissions before kicking off.
18014        for (int userId : grantPermissionsUserIds) {
18015            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18016        }
18017
18018        // If we did not grant default permissions, we preload from this the
18019        // default permission exceptions lazily to ensure we don't hit the
18020        // disk on a new user creation.
18021        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18022            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18023        }
18024
18025        // Kick off any messages waiting for system ready
18026        if (mPostSystemReadyMessages != null) {
18027            for (Message msg : mPostSystemReadyMessages) {
18028                msg.sendToTarget();
18029            }
18030            mPostSystemReadyMessages = null;
18031        }
18032
18033        // Watch for external volumes that come and go over time
18034        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18035        storage.registerListener(mStorageListener);
18036
18037        mInstallerService.systemReady();
18038        mPackageDexOptimizer.systemReady();
18039
18040        MountServiceInternal mountServiceInternal = LocalServices.getService(
18041                MountServiceInternal.class);
18042        mountServiceInternal.addExternalStoragePolicy(
18043                new MountServiceInternal.ExternalStorageMountPolicy() {
18044            @Override
18045            public int getMountMode(int uid, String packageName) {
18046                if (Process.isIsolated(uid)) {
18047                    return Zygote.MOUNT_EXTERNAL_NONE;
18048                }
18049                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18050                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18051                }
18052                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18053                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18054                }
18055                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18056                    return Zygote.MOUNT_EXTERNAL_READ;
18057                }
18058                return Zygote.MOUNT_EXTERNAL_WRITE;
18059            }
18060
18061            @Override
18062            public boolean hasExternalStorage(int uid, String packageName) {
18063                return true;
18064            }
18065        });
18066
18067        // Now that we're mostly running, clean up stale users and apps
18068        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18069        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18070    }
18071
18072    @Override
18073    public boolean isSafeMode() {
18074        return mSafeMode;
18075    }
18076
18077    @Override
18078    public boolean hasSystemUidErrors() {
18079        return mHasSystemUidErrors;
18080    }
18081
18082    static String arrayToString(int[] array) {
18083        StringBuffer buf = new StringBuffer(128);
18084        buf.append('[');
18085        if (array != null) {
18086            for (int i=0; i<array.length; i++) {
18087                if (i > 0) buf.append(", ");
18088                buf.append(array[i]);
18089            }
18090        }
18091        buf.append(']');
18092        return buf.toString();
18093    }
18094
18095    static class DumpState {
18096        public static final int DUMP_LIBS = 1 << 0;
18097        public static final int DUMP_FEATURES = 1 << 1;
18098        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18099        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18100        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18101        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18102        public static final int DUMP_PERMISSIONS = 1 << 6;
18103        public static final int DUMP_PACKAGES = 1 << 7;
18104        public static final int DUMP_SHARED_USERS = 1 << 8;
18105        public static final int DUMP_MESSAGES = 1 << 9;
18106        public static final int DUMP_PROVIDERS = 1 << 10;
18107        public static final int DUMP_VERIFIERS = 1 << 11;
18108        public static final int DUMP_PREFERRED = 1 << 12;
18109        public static final int DUMP_PREFERRED_XML = 1 << 13;
18110        public static final int DUMP_KEYSETS = 1 << 14;
18111        public static final int DUMP_VERSION = 1 << 15;
18112        public static final int DUMP_INSTALLS = 1 << 16;
18113        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18114        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18115        public static final int DUMP_FROZEN = 1 << 19;
18116        public static final int DUMP_DEXOPT = 1 << 20;
18117        public static final int DUMP_COMPILER_STATS = 1 << 21;
18118
18119        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18120
18121        private int mTypes;
18122
18123        private int mOptions;
18124
18125        private boolean mTitlePrinted;
18126
18127        private SharedUserSetting mSharedUser;
18128
18129        public boolean isDumping(int type) {
18130            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18131                return true;
18132            }
18133
18134            return (mTypes & type) != 0;
18135        }
18136
18137        public void setDump(int type) {
18138            mTypes |= type;
18139        }
18140
18141        public boolean isOptionEnabled(int option) {
18142            return (mOptions & option) != 0;
18143        }
18144
18145        public void setOptionEnabled(int option) {
18146            mOptions |= option;
18147        }
18148
18149        public boolean onTitlePrinted() {
18150            final boolean printed = mTitlePrinted;
18151            mTitlePrinted = true;
18152            return printed;
18153        }
18154
18155        public boolean getTitlePrinted() {
18156            return mTitlePrinted;
18157        }
18158
18159        public void setTitlePrinted(boolean enabled) {
18160            mTitlePrinted = enabled;
18161        }
18162
18163        public SharedUserSetting getSharedUser() {
18164            return mSharedUser;
18165        }
18166
18167        public void setSharedUser(SharedUserSetting user) {
18168            mSharedUser = user;
18169        }
18170    }
18171
18172    @Override
18173    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18174            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18175        (new PackageManagerShellCommand(this)).exec(
18176                this, in, out, err, args, resultReceiver);
18177    }
18178
18179    @Override
18180    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18181        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18182                != PackageManager.PERMISSION_GRANTED) {
18183            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18184                    + Binder.getCallingPid()
18185                    + ", uid=" + Binder.getCallingUid()
18186                    + " without permission "
18187                    + android.Manifest.permission.DUMP);
18188            return;
18189        }
18190
18191        DumpState dumpState = new DumpState();
18192        boolean fullPreferred = false;
18193        boolean checkin = false;
18194
18195        String packageName = null;
18196        ArraySet<String> permissionNames = null;
18197
18198        int opti = 0;
18199        while (opti < args.length) {
18200            String opt = args[opti];
18201            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18202                break;
18203            }
18204            opti++;
18205
18206            if ("-a".equals(opt)) {
18207                // Right now we only know how to print all.
18208            } else if ("-h".equals(opt)) {
18209                pw.println("Package manager dump options:");
18210                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18211                pw.println("    --checkin: dump for a checkin");
18212                pw.println("    -f: print details of intent filters");
18213                pw.println("    -h: print this help");
18214                pw.println("  cmd may be one of:");
18215                pw.println("    l[ibraries]: list known shared libraries");
18216                pw.println("    f[eatures]: list device features");
18217                pw.println("    k[eysets]: print known keysets");
18218                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18219                pw.println("    perm[issions]: dump permissions");
18220                pw.println("    permission [name ...]: dump declaration and use of given permission");
18221                pw.println("    pref[erred]: print preferred package settings");
18222                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18223                pw.println("    prov[iders]: dump content providers");
18224                pw.println("    p[ackages]: dump installed packages");
18225                pw.println("    s[hared-users]: dump shared user IDs");
18226                pw.println("    m[essages]: print collected runtime messages");
18227                pw.println("    v[erifiers]: print package verifier info");
18228                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18229                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18230                pw.println("    version: print database version info");
18231                pw.println("    write: write current settings now");
18232                pw.println("    installs: details about install sessions");
18233                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18234                pw.println("    dexopt: dump dexopt state");
18235                pw.println("    compiler-stats: dump compiler statistics");
18236                pw.println("    <package.name>: info about given package");
18237                return;
18238            } else if ("--checkin".equals(opt)) {
18239                checkin = true;
18240            } else if ("-f".equals(opt)) {
18241                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18242            } else {
18243                pw.println("Unknown argument: " + opt + "; use -h for help");
18244            }
18245        }
18246
18247        // Is the caller requesting to dump a particular piece of data?
18248        if (opti < args.length) {
18249            String cmd = args[opti];
18250            opti++;
18251            // Is this a package name?
18252            if ("android".equals(cmd) || cmd.contains(".")) {
18253                packageName = cmd;
18254                // When dumping a single package, we always dump all of its
18255                // filter information since the amount of data will be reasonable.
18256                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18257            } else if ("check-permission".equals(cmd)) {
18258                if (opti >= args.length) {
18259                    pw.println("Error: check-permission missing permission argument");
18260                    return;
18261                }
18262                String perm = args[opti];
18263                opti++;
18264                if (opti >= args.length) {
18265                    pw.println("Error: check-permission missing package argument");
18266                    return;
18267                }
18268                String pkg = args[opti];
18269                opti++;
18270                int user = UserHandle.getUserId(Binder.getCallingUid());
18271                if (opti < args.length) {
18272                    try {
18273                        user = Integer.parseInt(args[opti]);
18274                    } catch (NumberFormatException e) {
18275                        pw.println("Error: check-permission user argument is not a number: "
18276                                + args[opti]);
18277                        return;
18278                    }
18279                }
18280                pw.println(checkPermission(perm, pkg, user));
18281                return;
18282            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18283                dumpState.setDump(DumpState.DUMP_LIBS);
18284            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18285                dumpState.setDump(DumpState.DUMP_FEATURES);
18286            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18287                if (opti >= args.length) {
18288                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18289                            | DumpState.DUMP_SERVICE_RESOLVERS
18290                            | DumpState.DUMP_RECEIVER_RESOLVERS
18291                            | DumpState.DUMP_CONTENT_RESOLVERS);
18292                } else {
18293                    while (opti < args.length) {
18294                        String name = args[opti];
18295                        if ("a".equals(name) || "activity".equals(name)) {
18296                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18297                        } else if ("s".equals(name) || "service".equals(name)) {
18298                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18299                        } else if ("r".equals(name) || "receiver".equals(name)) {
18300                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18301                        } else if ("c".equals(name) || "content".equals(name)) {
18302                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18303                        } else {
18304                            pw.println("Error: unknown resolver table type: " + name);
18305                            return;
18306                        }
18307                        opti++;
18308                    }
18309                }
18310            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18311                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18312            } else if ("permission".equals(cmd)) {
18313                if (opti >= args.length) {
18314                    pw.println("Error: permission requires permission name");
18315                    return;
18316                }
18317                permissionNames = new ArraySet<>();
18318                while (opti < args.length) {
18319                    permissionNames.add(args[opti]);
18320                    opti++;
18321                }
18322                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18323                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18324            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18325                dumpState.setDump(DumpState.DUMP_PREFERRED);
18326            } else if ("preferred-xml".equals(cmd)) {
18327                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18328                if (opti < args.length && "--full".equals(args[opti])) {
18329                    fullPreferred = true;
18330                    opti++;
18331                }
18332            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18333                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18334            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18335                dumpState.setDump(DumpState.DUMP_PACKAGES);
18336            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18337                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18338            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18339                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18340            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18341                dumpState.setDump(DumpState.DUMP_MESSAGES);
18342            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18343                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18344            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18345                    || "intent-filter-verifiers".equals(cmd)) {
18346                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18347            } else if ("version".equals(cmd)) {
18348                dumpState.setDump(DumpState.DUMP_VERSION);
18349            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18350                dumpState.setDump(DumpState.DUMP_KEYSETS);
18351            } else if ("installs".equals(cmd)) {
18352                dumpState.setDump(DumpState.DUMP_INSTALLS);
18353            } else if ("frozen".equals(cmd)) {
18354                dumpState.setDump(DumpState.DUMP_FROZEN);
18355            } else if ("dexopt".equals(cmd)) {
18356                dumpState.setDump(DumpState.DUMP_DEXOPT);
18357            } else if ("compiler-stats".equals(cmd)) {
18358                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18359            } else if ("write".equals(cmd)) {
18360                synchronized (mPackages) {
18361                    mSettings.writeLPr();
18362                    pw.println("Settings written.");
18363                    return;
18364                }
18365            }
18366        }
18367
18368        if (checkin) {
18369            pw.println("vers,1");
18370        }
18371
18372        // reader
18373        synchronized (mPackages) {
18374            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18375                if (!checkin) {
18376                    if (dumpState.onTitlePrinted())
18377                        pw.println();
18378                    pw.println("Database versions:");
18379                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18380                }
18381            }
18382
18383            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18384                if (!checkin) {
18385                    if (dumpState.onTitlePrinted())
18386                        pw.println();
18387                    pw.println("Verifiers:");
18388                    pw.print("  Required: ");
18389                    pw.print(mRequiredVerifierPackage);
18390                    pw.print(" (uid=");
18391                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18392                            UserHandle.USER_SYSTEM));
18393                    pw.println(")");
18394                } else if (mRequiredVerifierPackage != null) {
18395                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18396                    pw.print(",");
18397                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18398                            UserHandle.USER_SYSTEM));
18399                }
18400            }
18401
18402            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18403                    packageName == null) {
18404                if (mIntentFilterVerifierComponent != null) {
18405                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18406                    if (!checkin) {
18407                        if (dumpState.onTitlePrinted())
18408                            pw.println();
18409                        pw.println("Intent Filter Verifier:");
18410                        pw.print("  Using: ");
18411                        pw.print(verifierPackageName);
18412                        pw.print(" (uid=");
18413                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18414                                UserHandle.USER_SYSTEM));
18415                        pw.println(")");
18416                    } else if (verifierPackageName != null) {
18417                        pw.print("ifv,"); pw.print(verifierPackageName);
18418                        pw.print(",");
18419                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18420                                UserHandle.USER_SYSTEM));
18421                    }
18422                } else {
18423                    pw.println();
18424                    pw.println("No Intent Filter Verifier available!");
18425                }
18426            }
18427
18428            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18429                boolean printedHeader = false;
18430                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18431                while (it.hasNext()) {
18432                    String name = it.next();
18433                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18434                    if (!checkin) {
18435                        if (!printedHeader) {
18436                            if (dumpState.onTitlePrinted())
18437                                pw.println();
18438                            pw.println("Libraries:");
18439                            printedHeader = true;
18440                        }
18441                        pw.print("  ");
18442                    } else {
18443                        pw.print("lib,");
18444                    }
18445                    pw.print(name);
18446                    if (!checkin) {
18447                        pw.print(" -> ");
18448                    }
18449                    if (ent.path != null) {
18450                        if (!checkin) {
18451                            pw.print("(jar) ");
18452                            pw.print(ent.path);
18453                        } else {
18454                            pw.print(",jar,");
18455                            pw.print(ent.path);
18456                        }
18457                    } else {
18458                        if (!checkin) {
18459                            pw.print("(apk) ");
18460                            pw.print(ent.apk);
18461                        } else {
18462                            pw.print(",apk,");
18463                            pw.print(ent.apk);
18464                        }
18465                    }
18466                    pw.println();
18467                }
18468            }
18469
18470            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18471                if (dumpState.onTitlePrinted())
18472                    pw.println();
18473                if (!checkin) {
18474                    pw.println("Features:");
18475                }
18476
18477                for (FeatureInfo feat : mAvailableFeatures.values()) {
18478                    if (checkin) {
18479                        pw.print("feat,");
18480                        pw.print(feat.name);
18481                        pw.print(",");
18482                        pw.println(feat.version);
18483                    } else {
18484                        pw.print("  ");
18485                        pw.print(feat.name);
18486                        if (feat.version > 0) {
18487                            pw.print(" version=");
18488                            pw.print(feat.version);
18489                        }
18490                        pw.println();
18491                    }
18492                }
18493            }
18494
18495            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18496                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18497                        : "Activity Resolver Table:", "  ", packageName,
18498                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18499                    dumpState.setTitlePrinted(true);
18500                }
18501            }
18502            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18503                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18504                        : "Receiver Resolver Table:", "  ", packageName,
18505                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18506                    dumpState.setTitlePrinted(true);
18507                }
18508            }
18509            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18510                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18511                        : "Service Resolver Table:", "  ", packageName,
18512                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18513                    dumpState.setTitlePrinted(true);
18514                }
18515            }
18516            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18517                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18518                        : "Provider Resolver Table:", "  ", packageName,
18519                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18520                    dumpState.setTitlePrinted(true);
18521                }
18522            }
18523
18524            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18525                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18526                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18527                    int user = mSettings.mPreferredActivities.keyAt(i);
18528                    if (pir.dump(pw,
18529                            dumpState.getTitlePrinted()
18530                                ? "\nPreferred Activities User " + user + ":"
18531                                : "Preferred Activities User " + user + ":", "  ",
18532                            packageName, true, false)) {
18533                        dumpState.setTitlePrinted(true);
18534                    }
18535                }
18536            }
18537
18538            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18539                pw.flush();
18540                FileOutputStream fout = new FileOutputStream(fd);
18541                BufferedOutputStream str = new BufferedOutputStream(fout);
18542                XmlSerializer serializer = new FastXmlSerializer();
18543                try {
18544                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18545                    serializer.startDocument(null, true);
18546                    serializer.setFeature(
18547                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18548                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18549                    serializer.endDocument();
18550                    serializer.flush();
18551                } catch (IllegalArgumentException e) {
18552                    pw.println("Failed writing: " + e);
18553                } catch (IllegalStateException e) {
18554                    pw.println("Failed writing: " + e);
18555                } catch (IOException e) {
18556                    pw.println("Failed writing: " + e);
18557                }
18558            }
18559
18560            if (!checkin
18561                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18562                    && packageName == null) {
18563                pw.println();
18564                int count = mSettings.mPackages.size();
18565                if (count == 0) {
18566                    pw.println("No applications!");
18567                    pw.println();
18568                } else {
18569                    final String prefix = "  ";
18570                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18571                    if (allPackageSettings.size() == 0) {
18572                        pw.println("No domain preferred apps!");
18573                        pw.println();
18574                    } else {
18575                        pw.println("App verification status:");
18576                        pw.println();
18577                        count = 0;
18578                        for (PackageSetting ps : allPackageSettings) {
18579                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18580                            if (ivi == null || ivi.getPackageName() == null) continue;
18581                            pw.println(prefix + "Package: " + ivi.getPackageName());
18582                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18583                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18584                            pw.println();
18585                            count++;
18586                        }
18587                        if (count == 0) {
18588                            pw.println(prefix + "No app verification established.");
18589                            pw.println();
18590                        }
18591                        for (int userId : sUserManager.getUserIds()) {
18592                            pw.println("App linkages for user " + userId + ":");
18593                            pw.println();
18594                            count = 0;
18595                            for (PackageSetting ps : allPackageSettings) {
18596                                final long status = ps.getDomainVerificationStatusForUser(userId);
18597                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18598                                    continue;
18599                                }
18600                                pw.println(prefix + "Package: " + ps.name);
18601                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18602                                String statusStr = IntentFilterVerificationInfo.
18603                                        getStatusStringFromValue(status);
18604                                pw.println(prefix + "Status:  " + statusStr);
18605                                pw.println();
18606                                count++;
18607                            }
18608                            if (count == 0) {
18609                                pw.println(prefix + "No configured app linkages.");
18610                                pw.println();
18611                            }
18612                        }
18613                    }
18614                }
18615            }
18616
18617            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18618                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18619                if (packageName == null && permissionNames == null) {
18620                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18621                        if (iperm == 0) {
18622                            if (dumpState.onTitlePrinted())
18623                                pw.println();
18624                            pw.println("AppOp Permissions:");
18625                        }
18626                        pw.print("  AppOp Permission ");
18627                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18628                        pw.println(":");
18629                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18630                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18631                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18632                        }
18633                    }
18634                }
18635            }
18636
18637            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18638                boolean printedSomething = false;
18639                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18640                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18641                        continue;
18642                    }
18643                    if (!printedSomething) {
18644                        if (dumpState.onTitlePrinted())
18645                            pw.println();
18646                        pw.println("Registered ContentProviders:");
18647                        printedSomething = true;
18648                    }
18649                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18650                    pw.print("    "); pw.println(p.toString());
18651                }
18652                printedSomething = false;
18653                for (Map.Entry<String, PackageParser.Provider> entry :
18654                        mProvidersByAuthority.entrySet()) {
18655                    PackageParser.Provider p = entry.getValue();
18656                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18657                        continue;
18658                    }
18659                    if (!printedSomething) {
18660                        if (dumpState.onTitlePrinted())
18661                            pw.println();
18662                        pw.println("ContentProvider Authorities:");
18663                        printedSomething = true;
18664                    }
18665                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18666                    pw.print("    "); pw.println(p.toString());
18667                    if (p.info != null && p.info.applicationInfo != null) {
18668                        final String appInfo = p.info.applicationInfo.toString();
18669                        pw.print("      applicationInfo="); pw.println(appInfo);
18670                    }
18671                }
18672            }
18673
18674            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18675                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18676            }
18677
18678            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18679                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18680            }
18681
18682            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18683                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18684            }
18685
18686            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18687                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18688            }
18689
18690            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18691                // XXX should handle packageName != null by dumping only install data that
18692                // the given package is involved with.
18693                if (dumpState.onTitlePrinted()) pw.println();
18694                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18695            }
18696
18697            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18698                // XXX should handle packageName != null by dumping only install data that
18699                // the given package is involved with.
18700                if (dumpState.onTitlePrinted()) pw.println();
18701
18702                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18703                ipw.println();
18704                ipw.println("Frozen packages:");
18705                ipw.increaseIndent();
18706                if (mFrozenPackages.size() == 0) {
18707                    ipw.println("(none)");
18708                } else {
18709                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18710                        ipw.println(mFrozenPackages.valueAt(i));
18711                    }
18712                }
18713                ipw.decreaseIndent();
18714            }
18715
18716            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18717                if (dumpState.onTitlePrinted()) pw.println();
18718                dumpDexoptStateLPr(pw, packageName);
18719            }
18720
18721            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18722                if (dumpState.onTitlePrinted()) pw.println();
18723                dumpCompilerStatsLPr(pw, packageName);
18724            }
18725
18726            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18727                if (dumpState.onTitlePrinted()) pw.println();
18728                mSettings.dumpReadMessagesLPr(pw, dumpState);
18729
18730                pw.println();
18731                pw.println("Package warning messages:");
18732                BufferedReader in = null;
18733                String line = null;
18734                try {
18735                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18736                    while ((line = in.readLine()) != null) {
18737                        if (line.contains("ignored: updated version")) continue;
18738                        pw.println(line);
18739                    }
18740                } catch (IOException ignored) {
18741                } finally {
18742                    IoUtils.closeQuietly(in);
18743                }
18744            }
18745
18746            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18747                BufferedReader in = null;
18748                String line = null;
18749                try {
18750                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18751                    while ((line = in.readLine()) != null) {
18752                        if (line.contains("ignored: updated version")) continue;
18753                        pw.print("msg,");
18754                        pw.println(line);
18755                    }
18756                } catch (IOException ignored) {
18757                } finally {
18758                    IoUtils.closeQuietly(in);
18759                }
18760            }
18761        }
18762    }
18763
18764    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18765        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18766        ipw.println();
18767        ipw.println("Dexopt state:");
18768        ipw.increaseIndent();
18769        Collection<PackageParser.Package> packages = null;
18770        if (packageName != null) {
18771            PackageParser.Package targetPackage = mPackages.get(packageName);
18772            if (targetPackage != null) {
18773                packages = Collections.singletonList(targetPackage);
18774            } else {
18775                ipw.println("Unable to find package: " + packageName);
18776                return;
18777            }
18778        } else {
18779            packages = mPackages.values();
18780        }
18781
18782        for (PackageParser.Package pkg : packages) {
18783            ipw.println("[" + pkg.packageName + "]");
18784            ipw.increaseIndent();
18785            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18786            ipw.decreaseIndent();
18787        }
18788    }
18789
18790    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18791        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18792        ipw.println();
18793        ipw.println("Compiler stats:");
18794        ipw.increaseIndent();
18795        Collection<PackageParser.Package> packages = null;
18796        if (packageName != null) {
18797            PackageParser.Package targetPackage = mPackages.get(packageName);
18798            if (targetPackage != null) {
18799                packages = Collections.singletonList(targetPackage);
18800            } else {
18801                ipw.println("Unable to find package: " + packageName);
18802                return;
18803            }
18804        } else {
18805            packages = mPackages.values();
18806        }
18807
18808        for (PackageParser.Package pkg : packages) {
18809            ipw.println("[" + pkg.packageName + "]");
18810            ipw.increaseIndent();
18811
18812            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18813            if (stats == null) {
18814                ipw.println("(No recorded stats)");
18815            } else {
18816                stats.dump(ipw);
18817            }
18818            ipw.decreaseIndent();
18819        }
18820    }
18821
18822    private String dumpDomainString(String packageName) {
18823        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18824                .getList();
18825        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18826
18827        ArraySet<String> result = new ArraySet<>();
18828        if (iviList.size() > 0) {
18829            for (IntentFilterVerificationInfo ivi : iviList) {
18830                for (String host : ivi.getDomains()) {
18831                    result.add(host);
18832                }
18833            }
18834        }
18835        if (filters != null && filters.size() > 0) {
18836            for (IntentFilter filter : filters) {
18837                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18838                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18839                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18840                    result.addAll(filter.getHostsList());
18841                }
18842            }
18843        }
18844
18845        StringBuilder sb = new StringBuilder(result.size() * 16);
18846        for (String domain : result) {
18847            if (sb.length() > 0) sb.append(" ");
18848            sb.append(domain);
18849        }
18850        return sb.toString();
18851    }
18852
18853    // ------- apps on sdcard specific code -------
18854    static final boolean DEBUG_SD_INSTALL = false;
18855
18856    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18857
18858    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18859
18860    private boolean mMediaMounted = false;
18861
18862    static String getEncryptKey() {
18863        try {
18864            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18865                    SD_ENCRYPTION_KEYSTORE_NAME);
18866            if (sdEncKey == null) {
18867                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18868                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18869                if (sdEncKey == null) {
18870                    Slog.e(TAG, "Failed to create encryption keys");
18871                    return null;
18872                }
18873            }
18874            return sdEncKey;
18875        } catch (NoSuchAlgorithmException nsae) {
18876            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18877            return null;
18878        } catch (IOException ioe) {
18879            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18880            return null;
18881        }
18882    }
18883
18884    /*
18885     * Update media status on PackageManager.
18886     */
18887    @Override
18888    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18889        int callingUid = Binder.getCallingUid();
18890        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18891            throw new SecurityException("Media status can only be updated by the system");
18892        }
18893        // reader; this apparently protects mMediaMounted, but should probably
18894        // be a different lock in that case.
18895        synchronized (mPackages) {
18896            Log.i(TAG, "Updating external media status from "
18897                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18898                    + (mediaStatus ? "mounted" : "unmounted"));
18899            if (DEBUG_SD_INSTALL)
18900                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18901                        + ", mMediaMounted=" + mMediaMounted);
18902            if (mediaStatus == mMediaMounted) {
18903                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18904                        : 0, -1);
18905                mHandler.sendMessage(msg);
18906                return;
18907            }
18908            mMediaMounted = mediaStatus;
18909        }
18910        // Queue up an async operation since the package installation may take a
18911        // little while.
18912        mHandler.post(new Runnable() {
18913            public void run() {
18914                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18915            }
18916        });
18917    }
18918
18919    /**
18920     * Called by MountService when the initial ASECs to scan are available.
18921     * Should block until all the ASEC containers are finished being scanned.
18922     */
18923    public void scanAvailableAsecs() {
18924        updateExternalMediaStatusInner(true, false, false);
18925    }
18926
18927    /*
18928     * Collect information of applications on external media, map them against
18929     * existing containers and update information based on current mount status.
18930     * Please note that we always have to report status if reportStatus has been
18931     * set to true especially when unloading packages.
18932     */
18933    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18934            boolean externalStorage) {
18935        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18936        int[] uidArr = EmptyArray.INT;
18937
18938        final String[] list = PackageHelper.getSecureContainerList();
18939        if (ArrayUtils.isEmpty(list)) {
18940            Log.i(TAG, "No secure containers found");
18941        } else {
18942            // Process list of secure containers and categorize them
18943            // as active or stale based on their package internal state.
18944
18945            // reader
18946            synchronized (mPackages) {
18947                for (String cid : list) {
18948                    // Leave stages untouched for now; installer service owns them
18949                    if (PackageInstallerService.isStageName(cid)) continue;
18950
18951                    if (DEBUG_SD_INSTALL)
18952                        Log.i(TAG, "Processing container " + cid);
18953                    String pkgName = getAsecPackageName(cid);
18954                    if (pkgName == null) {
18955                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18956                        continue;
18957                    }
18958                    if (DEBUG_SD_INSTALL)
18959                        Log.i(TAG, "Looking for pkg : " + pkgName);
18960
18961                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18962                    if (ps == null) {
18963                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18964                        continue;
18965                    }
18966
18967                    /*
18968                     * Skip packages that are not external if we're unmounting
18969                     * external storage.
18970                     */
18971                    if (externalStorage && !isMounted && !isExternal(ps)) {
18972                        continue;
18973                    }
18974
18975                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18976                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18977                    // The package status is changed only if the code path
18978                    // matches between settings and the container id.
18979                    if (ps.codePathString != null
18980                            && ps.codePathString.startsWith(args.getCodePath())) {
18981                        if (DEBUG_SD_INSTALL) {
18982                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18983                                    + " at code path: " + ps.codePathString);
18984                        }
18985
18986                        // We do have a valid package installed on sdcard
18987                        processCids.put(args, ps.codePathString);
18988                        final int uid = ps.appId;
18989                        if (uid != -1) {
18990                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18991                        }
18992                    } else {
18993                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18994                                + ps.codePathString);
18995                    }
18996                }
18997            }
18998
18999            Arrays.sort(uidArr);
19000        }
19001
19002        // Process packages with valid entries.
19003        if (isMounted) {
19004            if (DEBUG_SD_INSTALL)
19005                Log.i(TAG, "Loading packages");
19006            loadMediaPackages(processCids, uidArr, externalStorage);
19007            startCleaningPackages();
19008            mInstallerService.onSecureContainersAvailable();
19009        } else {
19010            if (DEBUG_SD_INSTALL)
19011                Log.i(TAG, "Unloading packages");
19012            unloadMediaPackages(processCids, uidArr, reportStatus);
19013        }
19014    }
19015
19016    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19017            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19018        final int size = infos.size();
19019        final String[] packageNames = new String[size];
19020        final int[] packageUids = new int[size];
19021        for (int i = 0; i < size; i++) {
19022            final ApplicationInfo info = infos.get(i);
19023            packageNames[i] = info.packageName;
19024            packageUids[i] = info.uid;
19025        }
19026        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19027                finishedReceiver);
19028    }
19029
19030    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19031            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19032        sendResourcesChangedBroadcast(mediaStatus, replacing,
19033                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19034    }
19035
19036    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19037            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19038        int size = pkgList.length;
19039        if (size > 0) {
19040            // Send broadcasts here
19041            Bundle extras = new Bundle();
19042            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19043            if (uidArr != null) {
19044                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19045            }
19046            if (replacing) {
19047                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19048            }
19049            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19050                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19051            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19052        }
19053    }
19054
19055   /*
19056     * Look at potentially valid container ids from processCids If package
19057     * information doesn't match the one on record or package scanning fails,
19058     * the cid is added to list of removeCids. We currently don't delete stale
19059     * containers.
19060     */
19061    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19062            boolean externalStorage) {
19063        ArrayList<String> pkgList = new ArrayList<String>();
19064        Set<AsecInstallArgs> keys = processCids.keySet();
19065
19066        for (AsecInstallArgs args : keys) {
19067            String codePath = processCids.get(args);
19068            if (DEBUG_SD_INSTALL)
19069                Log.i(TAG, "Loading container : " + args.cid);
19070            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19071            try {
19072                // Make sure there are no container errors first.
19073                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19074                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19075                            + " when installing from sdcard");
19076                    continue;
19077                }
19078                // Check code path here.
19079                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19080                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19081                            + " does not match one in settings " + codePath);
19082                    continue;
19083                }
19084                // Parse package
19085                int parseFlags = mDefParseFlags;
19086                if (args.isExternalAsec()) {
19087                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19088                }
19089                if (args.isFwdLocked()) {
19090                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19091                }
19092
19093                synchronized (mInstallLock) {
19094                    PackageParser.Package pkg = null;
19095                    try {
19096                        // Sadly we don't know the package name yet to freeze it
19097                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19098                                SCAN_IGNORE_FROZEN, 0, null);
19099                    } catch (PackageManagerException e) {
19100                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19101                    }
19102                    // Scan the package
19103                    if (pkg != null) {
19104                        /*
19105                         * TODO why is the lock being held? doPostInstall is
19106                         * called in other places without the lock. This needs
19107                         * to be straightened out.
19108                         */
19109                        // writer
19110                        synchronized (mPackages) {
19111                            retCode = PackageManager.INSTALL_SUCCEEDED;
19112                            pkgList.add(pkg.packageName);
19113                            // Post process args
19114                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19115                                    pkg.applicationInfo.uid);
19116                        }
19117                    } else {
19118                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19119                    }
19120                }
19121
19122            } finally {
19123                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19124                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19125                }
19126            }
19127        }
19128        // writer
19129        synchronized (mPackages) {
19130            // If the platform SDK has changed since the last time we booted,
19131            // we need to re-grant app permission to catch any new ones that
19132            // appear. This is really a hack, and means that apps can in some
19133            // cases get permissions that the user didn't initially explicitly
19134            // allow... it would be nice to have some better way to handle
19135            // this situation.
19136            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19137                    : mSettings.getInternalVersion();
19138            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19139                    : StorageManager.UUID_PRIVATE_INTERNAL;
19140
19141            int updateFlags = UPDATE_PERMISSIONS_ALL;
19142            if (ver.sdkVersion != mSdkVersion) {
19143                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19144                        + mSdkVersion + "; regranting permissions for external");
19145                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19146            }
19147            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19148
19149            // Yay, everything is now upgraded
19150            ver.forceCurrent();
19151
19152            // can downgrade to reader
19153            // Persist settings
19154            mSettings.writeLPr();
19155        }
19156        // Send a broadcast to let everyone know we are done processing
19157        if (pkgList.size() > 0) {
19158            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19159        }
19160    }
19161
19162   /*
19163     * Utility method to unload a list of specified containers
19164     */
19165    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19166        // Just unmount all valid containers.
19167        for (AsecInstallArgs arg : cidArgs) {
19168            synchronized (mInstallLock) {
19169                arg.doPostDeleteLI(false);
19170           }
19171       }
19172   }
19173
19174    /*
19175     * Unload packages mounted on external media. This involves deleting package
19176     * data from internal structures, sending broadcasts about disabled packages,
19177     * gc'ing to free up references, unmounting all secure containers
19178     * corresponding to packages on external media, and posting a
19179     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19180     * that we always have to post this message if status has been requested no
19181     * matter what.
19182     */
19183    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19184            final boolean reportStatus) {
19185        if (DEBUG_SD_INSTALL)
19186            Log.i(TAG, "unloading media packages");
19187        ArrayList<String> pkgList = new ArrayList<String>();
19188        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19189        final Set<AsecInstallArgs> keys = processCids.keySet();
19190        for (AsecInstallArgs args : keys) {
19191            String pkgName = args.getPackageName();
19192            if (DEBUG_SD_INSTALL)
19193                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19194            // Delete package internally
19195            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19196            synchronized (mInstallLock) {
19197                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19198                final boolean res;
19199                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19200                        "unloadMediaPackages")) {
19201                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19202                            null);
19203                }
19204                if (res) {
19205                    pkgList.add(pkgName);
19206                } else {
19207                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19208                    failedList.add(args);
19209                }
19210            }
19211        }
19212
19213        // reader
19214        synchronized (mPackages) {
19215            // We didn't update the settings after removing each package;
19216            // write them now for all packages.
19217            mSettings.writeLPr();
19218        }
19219
19220        // We have to absolutely send UPDATED_MEDIA_STATUS only
19221        // after confirming that all the receivers processed the ordered
19222        // broadcast when packages get disabled, force a gc to clean things up.
19223        // and unload all the containers.
19224        if (pkgList.size() > 0) {
19225            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19226                    new IIntentReceiver.Stub() {
19227                public void performReceive(Intent intent, int resultCode, String data,
19228                        Bundle extras, boolean ordered, boolean sticky,
19229                        int sendingUser) throws RemoteException {
19230                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19231                            reportStatus ? 1 : 0, 1, keys);
19232                    mHandler.sendMessage(msg);
19233                }
19234            });
19235        } else {
19236            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19237                    keys);
19238            mHandler.sendMessage(msg);
19239        }
19240    }
19241
19242    private void loadPrivatePackages(final VolumeInfo vol) {
19243        mHandler.post(new Runnable() {
19244            @Override
19245            public void run() {
19246                loadPrivatePackagesInner(vol);
19247            }
19248        });
19249    }
19250
19251    private void loadPrivatePackagesInner(VolumeInfo vol) {
19252        final String volumeUuid = vol.fsUuid;
19253        if (TextUtils.isEmpty(volumeUuid)) {
19254            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19255            return;
19256        }
19257
19258        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19259        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19260        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19261
19262        final VersionInfo ver;
19263        final List<PackageSetting> packages;
19264        synchronized (mPackages) {
19265            ver = mSettings.findOrCreateVersion(volumeUuid);
19266            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19267        }
19268
19269        for (PackageSetting ps : packages) {
19270            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19271            synchronized (mInstallLock) {
19272                final PackageParser.Package pkg;
19273                try {
19274                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19275                    loaded.add(pkg.applicationInfo);
19276
19277                } catch (PackageManagerException e) {
19278                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19279                }
19280
19281                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19282                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19283                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19284                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19285                }
19286            }
19287        }
19288
19289        // Reconcile app data for all started/unlocked users
19290        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19291        final UserManager um = mContext.getSystemService(UserManager.class);
19292        UserManagerInternal umInternal = getUserManagerInternal();
19293        for (UserInfo user : um.getUsers()) {
19294            final int flags;
19295            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19296                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19297            } else if (umInternal.isUserRunning(user.id)) {
19298                flags = StorageManager.FLAG_STORAGE_DE;
19299            } else {
19300                continue;
19301            }
19302
19303            try {
19304                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19305                synchronized (mInstallLock) {
19306                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19307                }
19308            } catch (IllegalStateException e) {
19309                // Device was probably ejected, and we'll process that event momentarily
19310                Slog.w(TAG, "Failed to prepare storage: " + e);
19311            }
19312        }
19313
19314        synchronized (mPackages) {
19315            int updateFlags = UPDATE_PERMISSIONS_ALL;
19316            if (ver.sdkVersion != mSdkVersion) {
19317                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19318                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19319                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19320            }
19321            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19322
19323            // Yay, everything is now upgraded
19324            ver.forceCurrent();
19325
19326            mSettings.writeLPr();
19327        }
19328
19329        for (PackageFreezer freezer : freezers) {
19330            freezer.close();
19331        }
19332
19333        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19334        sendResourcesChangedBroadcast(true, false, loaded, null);
19335    }
19336
19337    private void unloadPrivatePackages(final VolumeInfo vol) {
19338        mHandler.post(new Runnable() {
19339            @Override
19340            public void run() {
19341                unloadPrivatePackagesInner(vol);
19342            }
19343        });
19344    }
19345
19346    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19347        final String volumeUuid = vol.fsUuid;
19348        if (TextUtils.isEmpty(volumeUuid)) {
19349            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19350            return;
19351        }
19352
19353        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19354        synchronized (mInstallLock) {
19355        synchronized (mPackages) {
19356            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19357            for (PackageSetting ps : packages) {
19358                if (ps.pkg == null) continue;
19359
19360                final ApplicationInfo info = ps.pkg.applicationInfo;
19361                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19362                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19363
19364                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19365                        "unloadPrivatePackagesInner")) {
19366                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19367                            false, null)) {
19368                        unloaded.add(info);
19369                    } else {
19370                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19371                    }
19372                }
19373
19374                // Try very hard to release any references to this package
19375                // so we don't risk the system server being killed due to
19376                // open FDs
19377                AttributeCache.instance().removePackage(ps.name);
19378            }
19379
19380            mSettings.writeLPr();
19381        }
19382        }
19383
19384        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19385        sendResourcesChangedBroadcast(false, false, unloaded, null);
19386
19387        // Try very hard to release any references to this path so we don't risk
19388        // the system server being killed due to open FDs
19389        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19390
19391        for (int i = 0; i < 3; i++) {
19392            System.gc();
19393            System.runFinalization();
19394        }
19395    }
19396
19397    /**
19398     * Prepare storage areas for given user on all mounted devices.
19399     */
19400    void prepareUserData(int userId, int userSerial, int flags) {
19401        synchronized (mInstallLock) {
19402            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19403            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19404                final String volumeUuid = vol.getFsUuid();
19405                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19406            }
19407        }
19408    }
19409
19410    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19411            boolean allowRecover) {
19412        // Prepare storage and verify that serial numbers are consistent; if
19413        // there's a mismatch we need to destroy to avoid leaking data
19414        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19415        try {
19416            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19417
19418            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19419                UserManagerService.enforceSerialNumber(
19420                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19421                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19422                    UserManagerService.enforceSerialNumber(
19423                            Environment.getDataSystemDeDirectory(userId), userSerial);
19424                }
19425            }
19426            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19427                UserManagerService.enforceSerialNumber(
19428                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19429                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19430                    UserManagerService.enforceSerialNumber(
19431                            Environment.getDataSystemCeDirectory(userId), userSerial);
19432                }
19433            }
19434
19435            synchronized (mInstallLock) {
19436                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19437            }
19438        } catch (Exception e) {
19439            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19440                    + " because we failed to prepare: " + e);
19441            destroyUserDataLI(volumeUuid, userId,
19442                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19443
19444            if (allowRecover) {
19445                // Try one last time; if we fail again we're really in trouble
19446                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19447            }
19448        }
19449    }
19450
19451    /**
19452     * Destroy storage areas for given user on all mounted devices.
19453     */
19454    void destroyUserData(int userId, int flags) {
19455        synchronized (mInstallLock) {
19456            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19457            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19458                final String volumeUuid = vol.getFsUuid();
19459                destroyUserDataLI(volumeUuid, userId, flags);
19460            }
19461        }
19462    }
19463
19464    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19465        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19466        try {
19467            // Clean up app data, profile data, and media data
19468            mInstaller.destroyUserData(volumeUuid, userId, flags);
19469
19470            // Clean up system data
19471            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19472                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19473                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19474                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19475                }
19476                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19477                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19478                }
19479            }
19480
19481            // Data with special labels is now gone, so finish the job
19482            storage.destroyUserStorage(volumeUuid, userId, flags);
19483
19484        } catch (Exception e) {
19485            logCriticalInfo(Log.WARN,
19486                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19487        }
19488    }
19489
19490    /**
19491     * Examine all users present on given mounted volume, and destroy data
19492     * belonging to users that are no longer valid, or whose user ID has been
19493     * recycled.
19494     */
19495    private void reconcileUsers(String volumeUuid) {
19496        final List<File> files = new ArrayList<>();
19497        Collections.addAll(files, FileUtils
19498                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19499        Collections.addAll(files, FileUtils
19500                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19501        Collections.addAll(files, FileUtils
19502                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19503        Collections.addAll(files, FileUtils
19504                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19505        for (File file : files) {
19506            if (!file.isDirectory()) continue;
19507
19508            final int userId;
19509            final UserInfo info;
19510            try {
19511                userId = Integer.parseInt(file.getName());
19512                info = sUserManager.getUserInfo(userId);
19513            } catch (NumberFormatException e) {
19514                Slog.w(TAG, "Invalid user directory " + file);
19515                continue;
19516            }
19517
19518            boolean destroyUser = false;
19519            if (info == null) {
19520                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19521                        + " because no matching user was found");
19522                destroyUser = true;
19523            } else if (!mOnlyCore) {
19524                try {
19525                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19526                } catch (IOException e) {
19527                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19528                            + " because we failed to enforce serial number: " + e);
19529                    destroyUser = true;
19530                }
19531            }
19532
19533            if (destroyUser) {
19534                synchronized (mInstallLock) {
19535                    destroyUserDataLI(volumeUuid, userId,
19536                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19537                }
19538            }
19539        }
19540    }
19541
19542    private void assertPackageKnown(String volumeUuid, String packageName)
19543            throws PackageManagerException {
19544        synchronized (mPackages) {
19545            final PackageSetting ps = mSettings.mPackages.get(packageName);
19546            if (ps == null) {
19547                throw new PackageManagerException("Package " + packageName + " is unknown");
19548            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19549                throw new PackageManagerException(
19550                        "Package " + packageName + " found on unknown volume " + volumeUuid
19551                                + "; expected volume " + ps.volumeUuid);
19552            }
19553        }
19554    }
19555
19556    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19557            throws PackageManagerException {
19558        synchronized (mPackages) {
19559            final PackageSetting ps = mSettings.mPackages.get(packageName);
19560            if (ps == null) {
19561                throw new PackageManagerException("Package " + packageName + " is unknown");
19562            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19563                throw new PackageManagerException(
19564                        "Package " + packageName + " found on unknown volume " + volumeUuid
19565                                + "; expected volume " + ps.volumeUuid);
19566            } else if (!ps.getInstalled(userId)) {
19567                throw new PackageManagerException(
19568                        "Package " + packageName + " not installed for user " + userId);
19569            }
19570        }
19571    }
19572
19573    /**
19574     * Examine all apps present on given mounted volume, and destroy apps that
19575     * aren't expected, either due to uninstallation or reinstallation on
19576     * another volume.
19577     */
19578    private void reconcileApps(String volumeUuid) {
19579        final File[] files = FileUtils
19580                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19581        for (File file : files) {
19582            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19583                    && !PackageInstallerService.isStageName(file.getName());
19584            if (!isPackage) {
19585                // Ignore entries which are not packages
19586                continue;
19587            }
19588
19589            try {
19590                final PackageLite pkg = PackageParser.parsePackageLite(file,
19591                        PackageParser.PARSE_MUST_BE_APK);
19592                assertPackageKnown(volumeUuid, pkg.packageName);
19593
19594            } catch (PackageParserException | PackageManagerException e) {
19595                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19596                synchronized (mInstallLock) {
19597                    removeCodePathLI(file);
19598                }
19599            }
19600        }
19601    }
19602
19603    /**
19604     * Reconcile all app data for the given user.
19605     * <p>
19606     * Verifies that directories exist and that ownership and labeling is
19607     * correct for all installed apps on all mounted volumes.
19608     */
19609    void reconcileAppsData(int userId, int flags) {
19610        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19611        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19612            final String volumeUuid = vol.getFsUuid();
19613            synchronized (mInstallLock) {
19614                reconcileAppsDataLI(volumeUuid, userId, flags);
19615            }
19616        }
19617    }
19618
19619    /**
19620     * Reconcile all app data on given mounted volume.
19621     * <p>
19622     * Destroys app data that isn't expected, either due to uninstallation or
19623     * reinstallation on another volume.
19624     * <p>
19625     * Verifies that directories exist and that ownership and labeling is
19626     * correct for all installed apps.
19627     */
19628    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19629        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19630                + Integer.toHexString(flags));
19631
19632        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19633        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19634
19635        boolean restoreconNeeded = false;
19636
19637        // First look for stale data that doesn't belong, and check if things
19638        // have changed since we did our last restorecon
19639        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19640            if (StorageManager.isFileEncryptedNativeOrEmulated()
19641                    && !StorageManager.isUserKeyUnlocked(userId)) {
19642                throw new RuntimeException(
19643                        "Yikes, someone asked us to reconcile CE storage while " + userId
19644                                + " was still locked; this would have caused massive data loss!");
19645            }
19646
19647            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19648
19649            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19650            for (File file : files) {
19651                final String packageName = file.getName();
19652                try {
19653                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19654                } catch (PackageManagerException e) {
19655                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19656                    try {
19657                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19658                                StorageManager.FLAG_STORAGE_CE, 0);
19659                    } catch (InstallerException e2) {
19660                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19661                    }
19662                }
19663            }
19664        }
19665        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19666            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19667
19668            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19669            for (File file : files) {
19670                final String packageName = file.getName();
19671                try {
19672                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19673                } catch (PackageManagerException e) {
19674                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19675                    try {
19676                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19677                                StorageManager.FLAG_STORAGE_DE, 0);
19678                    } catch (InstallerException e2) {
19679                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19680                    }
19681                }
19682            }
19683        }
19684
19685        // Ensure that data directories are ready to roll for all packages
19686        // installed for this volume and user
19687        final List<PackageSetting> packages;
19688        synchronized (mPackages) {
19689            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19690        }
19691        int preparedCount = 0;
19692        for (PackageSetting ps : packages) {
19693            final String packageName = ps.name;
19694            if (ps.pkg == null) {
19695                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19696                // TODO: might be due to legacy ASEC apps; we should circle back
19697                // and reconcile again once they're scanned
19698                continue;
19699            }
19700
19701            if (ps.getInstalled(userId)) {
19702                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19703
19704                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19705                    // We may have just shuffled around app data directories, so
19706                    // prepare them one more time
19707                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19708                }
19709
19710                preparedCount++;
19711            }
19712        }
19713
19714        if (restoreconNeeded) {
19715            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19716                SELinuxMMAC.setRestoreconDone(ceDir);
19717            }
19718            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19719                SELinuxMMAC.setRestoreconDone(deDir);
19720            }
19721        }
19722
19723        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19724                + " packages; restoreconNeeded was " + restoreconNeeded);
19725    }
19726
19727    /**
19728     * Prepare app data for the given app just after it was installed or
19729     * upgraded. This method carefully only touches users that it's installed
19730     * for, and it forces a restorecon to handle any seinfo changes.
19731     * <p>
19732     * Verifies that directories exist and that ownership and labeling is
19733     * correct for all installed apps. If there is an ownership mismatch, it
19734     * will try recovering system apps by wiping data; third-party app data is
19735     * left intact.
19736     * <p>
19737     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19738     */
19739    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19740        final PackageSetting ps;
19741        synchronized (mPackages) {
19742            ps = mSettings.mPackages.get(pkg.packageName);
19743            mSettings.writeKernelMappingLPr(ps);
19744        }
19745
19746        final UserManager um = mContext.getSystemService(UserManager.class);
19747        UserManagerInternal umInternal = getUserManagerInternal();
19748        for (UserInfo user : um.getUsers()) {
19749            final int flags;
19750            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19751                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19752            } else if (umInternal.isUserRunning(user.id)) {
19753                flags = StorageManager.FLAG_STORAGE_DE;
19754            } else {
19755                continue;
19756            }
19757
19758            if (ps.getInstalled(user.id)) {
19759                // Whenever an app changes, force a restorecon of its data
19760                // TODO: when user data is locked, mark that we're still dirty
19761                prepareAppDataLIF(pkg, user.id, flags, true);
19762            }
19763        }
19764    }
19765
19766    /**
19767     * Prepare app data for the given app.
19768     * <p>
19769     * Verifies that directories exist and that ownership and labeling is
19770     * correct for all installed apps. If there is an ownership mismatch, this
19771     * will try recovering system apps by wiping data; third-party app data is
19772     * left intact.
19773     */
19774    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19775            boolean restoreconNeeded) {
19776        if (pkg == null) {
19777            Slog.wtf(TAG, "Package was null!", new Throwable());
19778            return;
19779        }
19780        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19781        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19782        for (int i = 0; i < childCount; i++) {
19783            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19784        }
19785    }
19786
19787    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19788            boolean restoreconNeeded) {
19789        if (DEBUG_APP_DATA) {
19790            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19791                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19792        }
19793
19794        final String volumeUuid = pkg.volumeUuid;
19795        final String packageName = pkg.packageName;
19796        final ApplicationInfo app = pkg.applicationInfo;
19797        final int appId = UserHandle.getAppId(app.uid);
19798
19799        Preconditions.checkNotNull(app.seinfo);
19800
19801        try {
19802            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19803                    appId, app.seinfo, app.targetSdkVersion);
19804        } catch (InstallerException e) {
19805            if (app.isSystemApp()) {
19806                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19807                        + ", but trying to recover: " + e);
19808                destroyAppDataLeafLIF(pkg, userId, flags);
19809                try {
19810                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19811                            appId, app.seinfo, app.targetSdkVersion);
19812                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19813                } catch (InstallerException e2) {
19814                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19815                }
19816            } else {
19817                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19818            }
19819        }
19820
19821        if (restoreconNeeded) {
19822            try {
19823                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19824                        app.seinfo);
19825            } catch (InstallerException e) {
19826                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19827            }
19828        }
19829
19830        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19831            try {
19832                // CE storage is unlocked right now, so read out the inode and
19833                // remember for use later when it's locked
19834                // TODO: mark this structure as dirty so we persist it!
19835                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19836                        StorageManager.FLAG_STORAGE_CE);
19837                synchronized (mPackages) {
19838                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19839                    if (ps != null) {
19840                        ps.setCeDataInode(ceDataInode, userId);
19841                    }
19842                }
19843            } catch (InstallerException e) {
19844                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19845            }
19846        }
19847
19848        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19849    }
19850
19851    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19852        if (pkg == null) {
19853            Slog.wtf(TAG, "Package was null!", new Throwable());
19854            return;
19855        }
19856        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19857        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19858        for (int i = 0; i < childCount; i++) {
19859            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19860        }
19861    }
19862
19863    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19864        final String volumeUuid = pkg.volumeUuid;
19865        final String packageName = pkg.packageName;
19866        final ApplicationInfo app = pkg.applicationInfo;
19867
19868        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19869            // Create a native library symlink only if we have native libraries
19870            // and if the native libraries are 32 bit libraries. We do not provide
19871            // this symlink for 64 bit libraries.
19872            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19873                final String nativeLibPath = app.nativeLibraryDir;
19874                try {
19875                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19876                            nativeLibPath, userId);
19877                } catch (InstallerException e) {
19878                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19879                }
19880            }
19881        }
19882    }
19883
19884    /**
19885     * For system apps on non-FBE devices, this method migrates any existing
19886     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19887     * requested by the app.
19888     */
19889    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19890        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19891                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19892            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19893                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19894            try {
19895                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19896                        storageTarget);
19897            } catch (InstallerException e) {
19898                logCriticalInfo(Log.WARN,
19899                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19900            }
19901            return true;
19902        } else {
19903            return false;
19904        }
19905    }
19906
19907    public PackageFreezer freezePackage(String packageName, String killReason) {
19908        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19909    }
19910
19911    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19912        return new PackageFreezer(packageName, userId, killReason);
19913    }
19914
19915    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19916            String killReason) {
19917        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19918    }
19919
19920    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19921            String killReason) {
19922        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19923            return new PackageFreezer();
19924        } else {
19925            return freezePackage(packageName, userId, killReason);
19926        }
19927    }
19928
19929    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19930            String killReason) {
19931        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19932    }
19933
19934    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19935            String killReason) {
19936        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19937            return new PackageFreezer();
19938        } else {
19939            return freezePackage(packageName, userId, killReason);
19940        }
19941    }
19942
19943    /**
19944     * Class that freezes and kills the given package upon creation, and
19945     * unfreezes it upon closing. This is typically used when doing surgery on
19946     * app code/data to prevent the app from running while you're working.
19947     */
19948    private class PackageFreezer implements AutoCloseable {
19949        private final String mPackageName;
19950        private final PackageFreezer[] mChildren;
19951
19952        private final boolean mWeFroze;
19953
19954        private final AtomicBoolean mClosed = new AtomicBoolean();
19955        private final CloseGuard mCloseGuard = CloseGuard.get();
19956
19957        /**
19958         * Create and return a stub freezer that doesn't actually do anything,
19959         * typically used when someone requested
19960         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19961         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19962         */
19963        public PackageFreezer() {
19964            mPackageName = null;
19965            mChildren = null;
19966            mWeFroze = false;
19967            mCloseGuard.open("close");
19968        }
19969
19970        public PackageFreezer(String packageName, int userId, String killReason) {
19971            synchronized (mPackages) {
19972                mPackageName = packageName;
19973                mWeFroze = mFrozenPackages.add(mPackageName);
19974
19975                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19976                if (ps != null) {
19977                    killApplication(ps.name, ps.appId, userId, killReason);
19978                }
19979
19980                final PackageParser.Package p = mPackages.get(packageName);
19981                if (p != null && p.childPackages != null) {
19982                    final int N = p.childPackages.size();
19983                    mChildren = new PackageFreezer[N];
19984                    for (int i = 0; i < N; i++) {
19985                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19986                                userId, killReason);
19987                    }
19988                } else {
19989                    mChildren = null;
19990                }
19991            }
19992            mCloseGuard.open("close");
19993        }
19994
19995        @Override
19996        protected void finalize() throws Throwable {
19997            try {
19998                mCloseGuard.warnIfOpen();
19999                close();
20000            } finally {
20001                super.finalize();
20002            }
20003        }
20004
20005        @Override
20006        public void close() {
20007            mCloseGuard.close();
20008            if (mClosed.compareAndSet(false, true)) {
20009                synchronized (mPackages) {
20010                    if (mWeFroze) {
20011                        mFrozenPackages.remove(mPackageName);
20012                    }
20013
20014                    if (mChildren != null) {
20015                        for (PackageFreezer freezer : mChildren) {
20016                            freezer.close();
20017                        }
20018                    }
20019                }
20020            }
20021        }
20022    }
20023
20024    /**
20025     * Verify that given package is currently frozen.
20026     */
20027    private void checkPackageFrozen(String packageName) {
20028        synchronized (mPackages) {
20029            if (!mFrozenPackages.contains(packageName)) {
20030                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20031            }
20032        }
20033    }
20034
20035    @Override
20036    public int movePackage(final String packageName, final String volumeUuid) {
20037        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20038
20039        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20040        final int moveId = mNextMoveId.getAndIncrement();
20041        mHandler.post(new Runnable() {
20042            @Override
20043            public void run() {
20044                try {
20045                    movePackageInternal(packageName, volumeUuid, moveId, user);
20046                } catch (PackageManagerException e) {
20047                    Slog.w(TAG, "Failed to move " + packageName, e);
20048                    mMoveCallbacks.notifyStatusChanged(moveId,
20049                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20050                }
20051            }
20052        });
20053        return moveId;
20054    }
20055
20056    private void movePackageInternal(final String packageName, final String volumeUuid,
20057            final int moveId, UserHandle user) throws PackageManagerException {
20058        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20059        final PackageManager pm = mContext.getPackageManager();
20060
20061        final boolean currentAsec;
20062        final String currentVolumeUuid;
20063        final File codeFile;
20064        final String installerPackageName;
20065        final String packageAbiOverride;
20066        final int appId;
20067        final String seinfo;
20068        final String label;
20069        final int targetSdkVersion;
20070        final PackageFreezer freezer;
20071        final int[] installedUserIds;
20072
20073        // reader
20074        synchronized (mPackages) {
20075            final PackageParser.Package pkg = mPackages.get(packageName);
20076            final PackageSetting ps = mSettings.mPackages.get(packageName);
20077            if (pkg == null || ps == null) {
20078                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20079            }
20080
20081            if (pkg.applicationInfo.isSystemApp()) {
20082                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20083                        "Cannot move system application");
20084            }
20085
20086            if (pkg.applicationInfo.isExternalAsec()) {
20087                currentAsec = true;
20088                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20089            } else if (pkg.applicationInfo.isForwardLocked()) {
20090                currentAsec = true;
20091                currentVolumeUuid = "forward_locked";
20092            } else {
20093                currentAsec = false;
20094                currentVolumeUuid = ps.volumeUuid;
20095
20096                final File probe = new File(pkg.codePath);
20097                final File probeOat = new File(probe, "oat");
20098                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20099                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20100                            "Move only supported for modern cluster style installs");
20101                }
20102            }
20103
20104            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20105                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20106                        "Package already moved to " + volumeUuid);
20107            }
20108            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20109                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20110                        "Device admin cannot be moved");
20111            }
20112
20113            if (mFrozenPackages.contains(packageName)) {
20114                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20115                        "Failed to move already frozen package");
20116            }
20117
20118            codeFile = new File(pkg.codePath);
20119            installerPackageName = ps.installerPackageName;
20120            packageAbiOverride = ps.cpuAbiOverrideString;
20121            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20122            seinfo = pkg.applicationInfo.seinfo;
20123            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20124            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20125            freezer = freezePackage(packageName, "movePackageInternal");
20126            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20127        }
20128
20129        final Bundle extras = new Bundle();
20130        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20131        extras.putString(Intent.EXTRA_TITLE, label);
20132        mMoveCallbacks.notifyCreated(moveId, extras);
20133
20134        int installFlags;
20135        final boolean moveCompleteApp;
20136        final File measurePath;
20137
20138        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20139            installFlags = INSTALL_INTERNAL;
20140            moveCompleteApp = !currentAsec;
20141            measurePath = Environment.getDataAppDirectory(volumeUuid);
20142        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20143            installFlags = INSTALL_EXTERNAL;
20144            moveCompleteApp = false;
20145            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20146        } else {
20147            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20148            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20149                    || !volume.isMountedWritable()) {
20150                freezer.close();
20151                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20152                        "Move location not mounted private volume");
20153            }
20154
20155            Preconditions.checkState(!currentAsec);
20156
20157            installFlags = INSTALL_INTERNAL;
20158            moveCompleteApp = true;
20159            measurePath = Environment.getDataAppDirectory(volumeUuid);
20160        }
20161
20162        final PackageStats stats = new PackageStats(null, -1);
20163        synchronized (mInstaller) {
20164            for (int userId : installedUserIds) {
20165                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20166                    freezer.close();
20167                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20168                            "Failed to measure package size");
20169                }
20170            }
20171        }
20172
20173        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20174                + stats.dataSize);
20175
20176        final long startFreeBytes = measurePath.getFreeSpace();
20177        final long sizeBytes;
20178        if (moveCompleteApp) {
20179            sizeBytes = stats.codeSize + stats.dataSize;
20180        } else {
20181            sizeBytes = stats.codeSize;
20182        }
20183
20184        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20185            freezer.close();
20186            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20187                    "Not enough free space to move");
20188        }
20189
20190        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20191
20192        final CountDownLatch installedLatch = new CountDownLatch(1);
20193        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20194            @Override
20195            public void onUserActionRequired(Intent intent) throws RemoteException {
20196                throw new IllegalStateException();
20197            }
20198
20199            @Override
20200            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20201                    Bundle extras) throws RemoteException {
20202                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20203                        + PackageManager.installStatusToString(returnCode, msg));
20204
20205                installedLatch.countDown();
20206                freezer.close();
20207
20208                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20209                switch (status) {
20210                    case PackageInstaller.STATUS_SUCCESS:
20211                        mMoveCallbacks.notifyStatusChanged(moveId,
20212                                PackageManager.MOVE_SUCCEEDED);
20213                        break;
20214                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20215                        mMoveCallbacks.notifyStatusChanged(moveId,
20216                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20217                        break;
20218                    default:
20219                        mMoveCallbacks.notifyStatusChanged(moveId,
20220                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20221                        break;
20222                }
20223            }
20224        };
20225
20226        final MoveInfo move;
20227        if (moveCompleteApp) {
20228            // Kick off a thread to report progress estimates
20229            new Thread() {
20230                @Override
20231                public void run() {
20232                    while (true) {
20233                        try {
20234                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20235                                break;
20236                            }
20237                        } catch (InterruptedException ignored) {
20238                        }
20239
20240                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20241                        final int progress = 10 + (int) MathUtils.constrain(
20242                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20243                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20244                    }
20245                }
20246            }.start();
20247
20248            final String dataAppName = codeFile.getName();
20249            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20250                    dataAppName, appId, seinfo, targetSdkVersion);
20251        } else {
20252            move = null;
20253        }
20254
20255        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20256
20257        final Message msg = mHandler.obtainMessage(INIT_COPY);
20258        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20259        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20260                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20261                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20262        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20263        msg.obj = params;
20264
20265        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20266                System.identityHashCode(msg.obj));
20267        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20268                System.identityHashCode(msg.obj));
20269
20270        mHandler.sendMessage(msg);
20271    }
20272
20273    @Override
20274    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20275        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20276
20277        final int realMoveId = mNextMoveId.getAndIncrement();
20278        final Bundle extras = new Bundle();
20279        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20280        mMoveCallbacks.notifyCreated(realMoveId, extras);
20281
20282        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20283            @Override
20284            public void onCreated(int moveId, Bundle extras) {
20285                // Ignored
20286            }
20287
20288            @Override
20289            public void onStatusChanged(int moveId, int status, long estMillis) {
20290                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20291            }
20292        };
20293
20294        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20295        storage.setPrimaryStorageUuid(volumeUuid, callback);
20296        return realMoveId;
20297    }
20298
20299    @Override
20300    public int getMoveStatus(int moveId) {
20301        mContext.enforceCallingOrSelfPermission(
20302                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20303        return mMoveCallbacks.mLastStatus.get(moveId);
20304    }
20305
20306    @Override
20307    public void registerMoveCallback(IPackageMoveObserver callback) {
20308        mContext.enforceCallingOrSelfPermission(
20309                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20310        mMoveCallbacks.register(callback);
20311    }
20312
20313    @Override
20314    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20315        mContext.enforceCallingOrSelfPermission(
20316                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20317        mMoveCallbacks.unregister(callback);
20318    }
20319
20320    @Override
20321    public boolean setInstallLocation(int loc) {
20322        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20323                null);
20324        if (getInstallLocation() == loc) {
20325            return true;
20326        }
20327        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20328                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20329            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20330                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20331            return true;
20332        }
20333        return false;
20334   }
20335
20336    @Override
20337    public int getInstallLocation() {
20338        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20339                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20340                PackageHelper.APP_INSTALL_AUTO);
20341    }
20342
20343    /** Called by UserManagerService */
20344    void cleanUpUser(UserManagerService userManager, int userHandle) {
20345        synchronized (mPackages) {
20346            mDirtyUsers.remove(userHandle);
20347            mUserNeedsBadging.delete(userHandle);
20348            mSettings.removeUserLPw(userHandle);
20349            mPendingBroadcasts.remove(userHandle);
20350            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20351            removeUnusedPackagesLPw(userManager, userHandle);
20352        }
20353    }
20354
20355    /**
20356     * We're removing userHandle and would like to remove any downloaded packages
20357     * that are no longer in use by any other user.
20358     * @param userHandle the user being removed
20359     */
20360    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20361        final boolean DEBUG_CLEAN_APKS = false;
20362        int [] users = userManager.getUserIds();
20363        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20364        while (psit.hasNext()) {
20365            PackageSetting ps = psit.next();
20366            if (ps.pkg == null) {
20367                continue;
20368            }
20369            final String packageName = ps.pkg.packageName;
20370            // Skip over if system app
20371            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20372                continue;
20373            }
20374            if (DEBUG_CLEAN_APKS) {
20375                Slog.i(TAG, "Checking package " + packageName);
20376            }
20377            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20378            if (keep) {
20379                if (DEBUG_CLEAN_APKS) {
20380                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20381                }
20382            } else {
20383                for (int i = 0; i < users.length; i++) {
20384                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20385                        keep = true;
20386                        if (DEBUG_CLEAN_APKS) {
20387                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20388                                    + users[i]);
20389                        }
20390                        break;
20391                    }
20392                }
20393            }
20394            if (!keep) {
20395                if (DEBUG_CLEAN_APKS) {
20396                    Slog.i(TAG, "  Removing package " + packageName);
20397                }
20398                mHandler.post(new Runnable() {
20399                    public void run() {
20400                        deletePackageX(packageName, userHandle, 0);
20401                    } //end run
20402                });
20403            }
20404        }
20405    }
20406
20407    /** Called by UserManagerService */
20408    void createNewUser(int userId) {
20409        synchronized (mInstallLock) {
20410            mSettings.createNewUserLI(this, mInstaller, userId);
20411        }
20412        synchronized (mPackages) {
20413            scheduleWritePackageRestrictionsLocked(userId);
20414            scheduleWritePackageListLocked(userId);
20415            applyFactoryDefaultBrowserLPw(userId);
20416            primeDomainVerificationsLPw(userId);
20417        }
20418    }
20419
20420    void onNewUserCreated(final int userId) {
20421        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20422        // If permission review for legacy apps is required, we represent
20423        // dagerous permissions for such apps as always granted runtime
20424        // permissions to keep per user flag state whether review is needed.
20425        // Hence, if a new user is added we have to propagate dangerous
20426        // permission grants for these legacy apps.
20427        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20428            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20429                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20430        }
20431    }
20432
20433    @Override
20434    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20435        mContext.enforceCallingOrSelfPermission(
20436                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20437                "Only package verification agents can read the verifier device identity");
20438
20439        synchronized (mPackages) {
20440            return mSettings.getVerifierDeviceIdentityLPw();
20441        }
20442    }
20443
20444    @Override
20445    public void setPermissionEnforced(String permission, boolean enforced) {
20446        // TODO: Now that we no longer change GID for storage, this should to away.
20447        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20448                "setPermissionEnforced");
20449        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20450            synchronized (mPackages) {
20451                if (mSettings.mReadExternalStorageEnforced == null
20452                        || mSettings.mReadExternalStorageEnforced != enforced) {
20453                    mSettings.mReadExternalStorageEnforced = enforced;
20454                    mSettings.writeLPr();
20455                }
20456            }
20457            // kill any non-foreground processes so we restart them and
20458            // grant/revoke the GID.
20459            final IActivityManager am = ActivityManagerNative.getDefault();
20460            if (am != null) {
20461                final long token = Binder.clearCallingIdentity();
20462                try {
20463                    am.killProcessesBelowForeground("setPermissionEnforcement");
20464                } catch (RemoteException e) {
20465                } finally {
20466                    Binder.restoreCallingIdentity(token);
20467                }
20468            }
20469        } else {
20470            throw new IllegalArgumentException("No selective enforcement for " + permission);
20471        }
20472    }
20473
20474    @Override
20475    @Deprecated
20476    public boolean isPermissionEnforced(String permission) {
20477        return true;
20478    }
20479
20480    @Override
20481    public boolean isStorageLow() {
20482        final long token = Binder.clearCallingIdentity();
20483        try {
20484            final DeviceStorageMonitorInternal
20485                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20486            if (dsm != null) {
20487                return dsm.isMemoryLow();
20488            } else {
20489                return false;
20490            }
20491        } finally {
20492            Binder.restoreCallingIdentity(token);
20493        }
20494    }
20495
20496    @Override
20497    public IPackageInstaller getPackageInstaller() {
20498        return mInstallerService;
20499    }
20500
20501    private boolean userNeedsBadging(int userId) {
20502        int index = mUserNeedsBadging.indexOfKey(userId);
20503        if (index < 0) {
20504            final UserInfo userInfo;
20505            final long token = Binder.clearCallingIdentity();
20506            try {
20507                userInfo = sUserManager.getUserInfo(userId);
20508            } finally {
20509                Binder.restoreCallingIdentity(token);
20510            }
20511            final boolean b;
20512            if (userInfo != null && userInfo.isManagedProfile()) {
20513                b = true;
20514            } else {
20515                b = false;
20516            }
20517            mUserNeedsBadging.put(userId, b);
20518            return b;
20519        }
20520        return mUserNeedsBadging.valueAt(index);
20521    }
20522
20523    @Override
20524    public KeySet getKeySetByAlias(String packageName, String alias) {
20525        if (packageName == null || alias == null) {
20526            return null;
20527        }
20528        synchronized(mPackages) {
20529            final PackageParser.Package pkg = mPackages.get(packageName);
20530            if (pkg == null) {
20531                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20532                throw new IllegalArgumentException("Unknown package: " + packageName);
20533            }
20534            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20535            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20536        }
20537    }
20538
20539    @Override
20540    public KeySet getSigningKeySet(String packageName) {
20541        if (packageName == null) {
20542            return null;
20543        }
20544        synchronized(mPackages) {
20545            final PackageParser.Package pkg = mPackages.get(packageName);
20546            if (pkg == null) {
20547                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20548                throw new IllegalArgumentException("Unknown package: " + packageName);
20549            }
20550            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20551                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20552                throw new SecurityException("May not access signing KeySet of other apps.");
20553            }
20554            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20555            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20556        }
20557    }
20558
20559    @Override
20560    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20561        if (packageName == null || ks == null) {
20562            return false;
20563        }
20564        synchronized(mPackages) {
20565            final PackageParser.Package pkg = mPackages.get(packageName);
20566            if (pkg == null) {
20567                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20568                throw new IllegalArgumentException("Unknown package: " + packageName);
20569            }
20570            IBinder ksh = ks.getToken();
20571            if (ksh instanceof KeySetHandle) {
20572                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20573                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20574            }
20575            return false;
20576        }
20577    }
20578
20579    @Override
20580    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20581        if (packageName == null || ks == null) {
20582            return false;
20583        }
20584        synchronized(mPackages) {
20585            final PackageParser.Package pkg = mPackages.get(packageName);
20586            if (pkg == null) {
20587                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20588                throw new IllegalArgumentException("Unknown package: " + packageName);
20589            }
20590            IBinder ksh = ks.getToken();
20591            if (ksh instanceof KeySetHandle) {
20592                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20593                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20594            }
20595            return false;
20596        }
20597    }
20598
20599    private void deletePackageIfUnusedLPr(final String packageName) {
20600        PackageSetting ps = mSettings.mPackages.get(packageName);
20601        if (ps == null) {
20602            return;
20603        }
20604        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20605            // TODO Implement atomic delete if package is unused
20606            // It is currently possible that the package will be deleted even if it is installed
20607            // after this method returns.
20608            mHandler.post(new Runnable() {
20609                public void run() {
20610                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20611                }
20612            });
20613        }
20614    }
20615
20616    /**
20617     * Check and throw if the given before/after packages would be considered a
20618     * downgrade.
20619     */
20620    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20621            throws PackageManagerException {
20622        if (after.versionCode < before.mVersionCode) {
20623            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20624                    "Update version code " + after.versionCode + " is older than current "
20625                    + before.mVersionCode);
20626        } else if (after.versionCode == before.mVersionCode) {
20627            if (after.baseRevisionCode < before.baseRevisionCode) {
20628                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20629                        "Update base revision code " + after.baseRevisionCode
20630                        + " is older than current " + before.baseRevisionCode);
20631            }
20632
20633            if (!ArrayUtils.isEmpty(after.splitNames)) {
20634                for (int i = 0; i < after.splitNames.length; i++) {
20635                    final String splitName = after.splitNames[i];
20636                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20637                    if (j != -1) {
20638                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20639                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20640                                    "Update split " + splitName + " revision code "
20641                                    + after.splitRevisionCodes[i] + " is older than current "
20642                                    + before.splitRevisionCodes[j]);
20643                        }
20644                    }
20645                }
20646            }
20647        }
20648    }
20649
20650    private static class MoveCallbacks extends Handler {
20651        private static final int MSG_CREATED = 1;
20652        private static final int MSG_STATUS_CHANGED = 2;
20653
20654        private final RemoteCallbackList<IPackageMoveObserver>
20655                mCallbacks = new RemoteCallbackList<>();
20656
20657        private final SparseIntArray mLastStatus = new SparseIntArray();
20658
20659        public MoveCallbacks(Looper looper) {
20660            super(looper);
20661        }
20662
20663        public void register(IPackageMoveObserver callback) {
20664            mCallbacks.register(callback);
20665        }
20666
20667        public void unregister(IPackageMoveObserver callback) {
20668            mCallbacks.unregister(callback);
20669        }
20670
20671        @Override
20672        public void handleMessage(Message msg) {
20673            final SomeArgs args = (SomeArgs) msg.obj;
20674            final int n = mCallbacks.beginBroadcast();
20675            for (int i = 0; i < n; i++) {
20676                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20677                try {
20678                    invokeCallback(callback, msg.what, args);
20679                } catch (RemoteException ignored) {
20680                }
20681            }
20682            mCallbacks.finishBroadcast();
20683            args.recycle();
20684        }
20685
20686        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20687                throws RemoteException {
20688            switch (what) {
20689                case MSG_CREATED: {
20690                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20691                    break;
20692                }
20693                case MSG_STATUS_CHANGED: {
20694                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20695                    break;
20696                }
20697            }
20698        }
20699
20700        private void notifyCreated(int moveId, Bundle extras) {
20701            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20702
20703            final SomeArgs args = SomeArgs.obtain();
20704            args.argi1 = moveId;
20705            args.arg2 = extras;
20706            obtainMessage(MSG_CREATED, args).sendToTarget();
20707        }
20708
20709        private void notifyStatusChanged(int moveId, int status) {
20710            notifyStatusChanged(moveId, status, -1);
20711        }
20712
20713        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20714            Slog.v(TAG, "Move " + moveId + " status " + status);
20715
20716            final SomeArgs args = SomeArgs.obtain();
20717            args.argi1 = moveId;
20718            args.argi2 = status;
20719            args.arg3 = estMillis;
20720            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20721
20722            synchronized (mLastStatus) {
20723                mLastStatus.put(moveId, status);
20724            }
20725        }
20726    }
20727
20728    private final static class OnPermissionChangeListeners extends Handler {
20729        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20730
20731        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20732                new RemoteCallbackList<>();
20733
20734        public OnPermissionChangeListeners(Looper looper) {
20735            super(looper);
20736        }
20737
20738        @Override
20739        public void handleMessage(Message msg) {
20740            switch (msg.what) {
20741                case MSG_ON_PERMISSIONS_CHANGED: {
20742                    final int uid = msg.arg1;
20743                    handleOnPermissionsChanged(uid);
20744                } break;
20745            }
20746        }
20747
20748        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20749            mPermissionListeners.register(listener);
20750
20751        }
20752
20753        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20754            mPermissionListeners.unregister(listener);
20755        }
20756
20757        public void onPermissionsChanged(int uid) {
20758            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20759                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20760            }
20761        }
20762
20763        private void handleOnPermissionsChanged(int uid) {
20764            final int count = mPermissionListeners.beginBroadcast();
20765            try {
20766                for (int i = 0; i < count; i++) {
20767                    IOnPermissionsChangeListener callback = mPermissionListeners
20768                            .getBroadcastItem(i);
20769                    try {
20770                        callback.onPermissionsChanged(uid);
20771                    } catch (RemoteException e) {
20772                        Log.e(TAG, "Permission listener is dead", e);
20773                    }
20774                }
20775            } finally {
20776                mPermissionListeners.finishBroadcast();
20777            }
20778        }
20779    }
20780
20781    private class PackageManagerInternalImpl extends PackageManagerInternal {
20782        @Override
20783        public void setLocationPackagesProvider(PackagesProvider provider) {
20784            synchronized (mPackages) {
20785                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20786            }
20787        }
20788
20789        @Override
20790        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20791            synchronized (mPackages) {
20792                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20793            }
20794        }
20795
20796        @Override
20797        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20798            synchronized (mPackages) {
20799                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20800            }
20801        }
20802
20803        @Override
20804        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20805            synchronized (mPackages) {
20806                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20807            }
20808        }
20809
20810        @Override
20811        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20812            synchronized (mPackages) {
20813                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20814            }
20815        }
20816
20817        @Override
20818        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20819            synchronized (mPackages) {
20820                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20821            }
20822        }
20823
20824        @Override
20825        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20826            synchronized (mPackages) {
20827                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20828                        packageName, userId);
20829            }
20830        }
20831
20832        @Override
20833        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20834            synchronized (mPackages) {
20835                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20836                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20837                        packageName, userId);
20838            }
20839        }
20840
20841        @Override
20842        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20843            synchronized (mPackages) {
20844                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20845                        packageName, userId);
20846            }
20847        }
20848
20849        @Override
20850        public void setKeepUninstalledPackages(final List<String> packageList) {
20851            Preconditions.checkNotNull(packageList);
20852            List<String> removedFromList = null;
20853            synchronized (mPackages) {
20854                if (mKeepUninstalledPackages != null) {
20855                    final int packagesCount = mKeepUninstalledPackages.size();
20856                    for (int i = 0; i < packagesCount; i++) {
20857                        String oldPackage = mKeepUninstalledPackages.get(i);
20858                        if (packageList != null && packageList.contains(oldPackage)) {
20859                            continue;
20860                        }
20861                        if (removedFromList == null) {
20862                            removedFromList = new ArrayList<>();
20863                        }
20864                        removedFromList.add(oldPackage);
20865                    }
20866                }
20867                mKeepUninstalledPackages = new ArrayList<>(packageList);
20868                if (removedFromList != null) {
20869                    final int removedCount = removedFromList.size();
20870                    for (int i = 0; i < removedCount; i++) {
20871                        deletePackageIfUnusedLPr(removedFromList.get(i));
20872                    }
20873                }
20874            }
20875        }
20876
20877        @Override
20878        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20879            synchronized (mPackages) {
20880                // If we do not support permission review, done.
20881                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20882                    return false;
20883                }
20884
20885                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20886                if (packageSetting == null) {
20887                    return false;
20888                }
20889
20890                // Permission review applies only to apps not supporting the new permission model.
20891                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20892                    return false;
20893                }
20894
20895                // Legacy apps have the permission and get user consent on launch.
20896                PermissionsState permissionsState = packageSetting.getPermissionsState();
20897                return permissionsState.isPermissionReviewRequired(userId);
20898            }
20899        }
20900
20901        @Override
20902        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20903            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20904        }
20905
20906        @Override
20907        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20908                int userId) {
20909            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20910        }
20911
20912        @Override
20913        public void setDeviceAndProfileOwnerPackages(
20914                int deviceOwnerUserId, String deviceOwnerPackage,
20915                SparseArray<String> profileOwnerPackages) {
20916            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20917                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20918        }
20919
20920        @Override
20921        public boolean isPackageDataProtected(int userId, String packageName) {
20922            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20923        }
20924    }
20925
20926    @Override
20927    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20928        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20929        synchronized (mPackages) {
20930            final long identity = Binder.clearCallingIdentity();
20931            try {
20932                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20933                        packageNames, userId);
20934            } finally {
20935                Binder.restoreCallingIdentity(identity);
20936            }
20937        }
20938    }
20939
20940    private static void enforceSystemOrPhoneCaller(String tag) {
20941        int callingUid = Binder.getCallingUid();
20942        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20943            throw new SecurityException(
20944                    "Cannot call " + tag + " from UID " + callingUid);
20945        }
20946    }
20947
20948    boolean isHistoricalPackageUsageAvailable() {
20949        return mPackageUsage.isHistoricalPackageUsageAvailable();
20950    }
20951
20952    /**
20953     * Return a <b>copy</b> of the collection of packages known to the package manager.
20954     * @return A copy of the values of mPackages.
20955     */
20956    Collection<PackageParser.Package> getPackages() {
20957        synchronized (mPackages) {
20958            return new ArrayList<>(mPackages.values());
20959        }
20960    }
20961
20962    /**
20963     * Logs process start information (including base APK hash) to the security log.
20964     * @hide
20965     */
20966    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20967            String apkFile, int pid) {
20968        if (!SecurityLog.isLoggingEnabled()) {
20969            return;
20970        }
20971        Bundle data = new Bundle();
20972        data.putLong("startTimestamp", System.currentTimeMillis());
20973        data.putString("processName", processName);
20974        data.putInt("uid", uid);
20975        data.putString("seinfo", seinfo);
20976        data.putString("apkFile", apkFile);
20977        data.putInt("pid", pid);
20978        Message msg = mProcessLoggingHandler.obtainMessage(
20979                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20980        msg.setData(data);
20981        mProcessLoggingHandler.sendMessage(msg);
20982    }
20983
20984    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20985        return mCompilerStats.getPackageStats(pkgName);
20986    }
20987
20988    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20989        return getOrCreateCompilerPackageStats(pkg.packageName);
20990    }
20991
20992    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20993        return mCompilerStats.getOrCreatePackageStats(pkgName);
20994    }
20995
20996    public void deleteCompilerPackageStats(String pkgName) {
20997        mCompilerStats.deletePackageStats(pkgName);
20998    }
20999}
21000