PackageManagerService.java revision 8e2d9d1d9050e93b15c54e992698325c7d4aa57c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
80import static android.system.OsConstants.O_CREAT;
81import static android.system.OsConstants.O_RDWR;
82
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.annotation.UserIdInt;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.PatternMatcher;
183import android.os.Process;
184import android.os.RemoteCallbackList;
185import android.os.RemoteException;
186import android.os.ResultReceiver;
187import android.os.SELinux;
188import android.os.ServiceManager;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.DisplayMetrics;
211import android.util.EventLog;
212import android.util.ExceptionUtils;
213import android.util.Log;
214import android.util.LogPrinter;
215import android.util.MathUtils;
216import android.util.PrintStreamPrinter;
217import android.util.Slog;
218import android.util.SparseArray;
219import android.util.SparseBooleanArray;
220import android.util.SparseIntArray;
221import android.util.Xml;
222import android.util.jar.StrictJarFile;
223import android.view.Display;
224
225import com.android.internal.R;
226import com.android.internal.annotations.GuardedBy;
227import com.android.internal.app.IMediaContainerService;
228import com.android.internal.app.ResolverActivity;
229import com.android.internal.content.NativeLibraryHelper;
230import com.android.internal.content.PackageHelper;
231import com.android.internal.logging.MetricsLogger;
232import com.android.internal.os.IParcelFileDescriptorFactory;
233import com.android.internal.os.InstallerConnection.InstallerException;
234import com.android.internal.os.SomeArgs;
235import com.android.internal.os.Zygote;
236import com.android.internal.telephony.CarrierAppUtils;
237import com.android.internal.util.ArrayUtils;
238import com.android.internal.util.FastPrintWriter;
239import com.android.internal.util.FastXmlSerializer;
240import com.android.internal.util.IndentingPrintWriter;
241import com.android.internal.util.Preconditions;
242import com.android.internal.util.XmlUtils;
243import com.android.server.AttributeCache;
244import com.android.server.EventLogTags;
245import com.android.server.FgThread;
246import com.android.server.IntentResolver;
247import com.android.server.LocalServices;
248import com.android.server.ServiceThread;
249import com.android.server.SystemConfig;
250import com.android.server.Watchdog;
251import com.android.server.net.NetworkPolicyManagerInternal;
252import com.android.server.pm.PermissionsState.PermissionState;
253import com.android.server.pm.Settings.DatabaseVersion;
254import com.android.server.pm.Settings.VersionInfo;
255import com.android.server.storage.DeviceStorageMonitorInternal;
256
257import dalvik.system.CloseGuard;
258import dalvik.system.DexFile;
259import dalvik.system.VMRuntime;
260
261import libcore.io.IoUtils;
262import libcore.util.EmptyArray;
263
264import org.xmlpull.v1.XmlPullParser;
265import org.xmlpull.v1.XmlPullParserException;
266import org.xmlpull.v1.XmlSerializer;
267
268import java.io.BufferedOutputStream;
269import java.io.BufferedReader;
270import java.io.ByteArrayInputStream;
271import java.io.ByteArrayOutputStream;
272import java.io.File;
273import java.io.FileDescriptor;
274import java.io.FileInputStream;
275import java.io.FileNotFoundException;
276import java.io.FileOutputStream;
277import java.io.FileReader;
278import java.io.FilenameFilter;
279import java.io.IOException;
280import java.io.PrintWriter;
281import java.nio.charset.StandardCharsets;
282import java.security.DigestInputStream;
283import java.security.MessageDigest;
284import java.security.NoSuchAlgorithmException;
285import java.security.PublicKey;
286import java.security.cert.Certificate;
287import java.security.cert.CertificateEncodingException;
288import java.security.cert.CertificateException;
289import java.text.SimpleDateFormat;
290import java.util.ArrayList;
291import java.util.Arrays;
292import java.util.Collection;
293import java.util.Collections;
294import java.util.Comparator;
295import java.util.Date;
296import java.util.HashSet;
297import java.util.Iterator;
298import java.util.List;
299import java.util.Map;
300import java.util.Objects;
301import java.util.Set;
302import java.util.concurrent.CountDownLatch;
303import java.util.concurrent.TimeUnit;
304import java.util.concurrent.atomic.AtomicBoolean;
305import java.util.concurrent.atomic.AtomicInteger;
306
307/**
308 * Keep track of all those APKs everywhere.
309 * <p>
310 * Internally there are two important locks:
311 * <ul>
312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
313 * and other related state. It is a fine-grained lock that should only be held
314 * momentarily, as it's one of the most contended locks in the system.
315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
316 * operations typically involve heavy lifting of application data on disk. Since
317 * {@code installd} is single-threaded, and it's operations can often be slow,
318 * this lock should never be acquired while already holding {@link #mPackages}.
319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
320 * holding {@link #mInstallLock}.
321 * </ul>
322 * Many internal methods rely on the caller to hold the appropriate locks, and
323 * this contract is expressed through method name suffixes:
324 * <ul>
325 * <li>fooLI(): the caller must hold {@link #mInstallLock}
326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
327 * being modified must be frozen
328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
330 * </ul>
331 * <p>
332 * Because this class is very central to the platform's security; please run all
333 * CTS and unit tests whenever making modifications:
334 *
335 * <pre>
336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
338 * </pre>
339 */
340public class PackageManagerService extends IPackageManager.Stub {
341    static final String TAG = "PackageManager";
342    static final boolean DEBUG_SETTINGS = false;
343    static final boolean DEBUG_PREFERRED = false;
344    static final boolean DEBUG_UPGRADE = false;
345    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
346    private static final boolean DEBUG_BACKUP = false;
347    private static final boolean DEBUG_INSTALL = false;
348    private static final boolean DEBUG_REMOVE = false;
349    private static final boolean DEBUG_BROADCASTS = false;
350    private static final boolean DEBUG_SHOW_INFO = false;
351    private static final boolean DEBUG_PACKAGE_INFO = false;
352    private static final boolean DEBUG_INTENT_MATCHING = false;
353    private static final boolean DEBUG_PACKAGE_SCANNING = false;
354    private static final boolean DEBUG_VERIFY = false;
355    private static final boolean DEBUG_FILTERS = false;
356
357    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
358    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
359    // user, but by default initialize to this.
360    static final boolean DEBUG_DEXOPT = false;
361
362    private static final boolean DEBUG_ABI_SELECTION = false;
363    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
364    private static final boolean DEBUG_TRIAGED_MISSING = false;
365    private static final boolean DEBUG_APP_DATA = false;
366
367    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
368
369    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
370
371    private static final int RADIO_UID = Process.PHONE_UID;
372    private static final int LOG_UID = Process.LOG_UID;
373    private static final int NFC_UID = Process.NFC_UID;
374    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
375    private static final int SHELL_UID = Process.SHELL_UID;
376
377    // Cap the size of permission trees that 3rd party apps can define
378    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
379
380    // Suffix used during package installation when copying/moving
381    // package apks to install directory.
382    private static final String INSTALL_PACKAGE_SUFFIX = "-";
383
384    static final int SCAN_NO_DEX = 1<<1;
385    static final int SCAN_FORCE_DEX = 1<<2;
386    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
387    static final int SCAN_NEW_INSTALL = 1<<4;
388    static final int SCAN_NO_PATHS = 1<<5;
389    static final int SCAN_UPDATE_TIME = 1<<6;
390    static final int SCAN_DEFER_DEX = 1<<7;
391    static final int SCAN_BOOTING = 1<<8;
392    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
393    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
394    static final int SCAN_REPLACING = 1<<11;
395    static final int SCAN_REQUIRE_KNOWN = 1<<12;
396    static final int SCAN_MOVE = 1<<13;
397    static final int SCAN_INITIAL = 1<<14;
398    static final int SCAN_CHECK_ONLY = 1<<15;
399    static final int SCAN_DONT_KILL_APP = 1<<17;
400    static final int SCAN_IGNORE_FROZEN = 1<<18;
401
402    static final int REMOVE_CHATTY = 1<<16;
403
404    private static final int[] EMPTY_INT_ARRAY = new int[0];
405
406    /**
407     * Timeout (in milliseconds) after which the watchdog should declare that
408     * our handler thread is wedged.  The usual default for such things is one
409     * minute but we sometimes do very lengthy I/O operations on this thread,
410     * such as installing multi-gigabyte applications, so ours needs to be longer.
411     */
412    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
413
414    /**
415     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
416     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
417     * settings entry if available, otherwise we use the hardcoded default.  If it's been
418     * more than this long since the last fstrim, we force one during the boot sequence.
419     *
420     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
421     * one gets run at the next available charging+idle time.  This final mandatory
422     * no-fstrim check kicks in only of the other scheduling criteria is never met.
423     */
424    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
425
426    /**
427     * Whether verification is enabled by default.
428     */
429    private static final boolean DEFAULT_VERIFY_ENABLE = true;
430
431    /**
432     * The default maximum time to wait for the verification agent to return in
433     * milliseconds.
434     */
435    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
436
437    /**
438     * The default response for package verification timeout.
439     *
440     * This can be either PackageManager.VERIFICATION_ALLOW or
441     * PackageManager.VERIFICATION_REJECT.
442     */
443    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
444
445    static final String PLATFORM_PACKAGE_NAME = "android";
446
447    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
448
449    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
450            DEFAULT_CONTAINER_PACKAGE,
451            "com.android.defcontainer.DefaultContainerService");
452
453    private static final String KILL_APP_REASON_GIDS_CHANGED =
454            "permission grant or revoke changed gids";
455
456    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
457            "permissions revoked";
458
459    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
460
461    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
462
463    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
464    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
465
466    /** Permission grant: not grant the permission. */
467    private static final int GRANT_DENIED = 1;
468
469    /** Permission grant: grant the permission as an install permission. */
470    private static final int GRANT_INSTALL = 2;
471
472    /** Permission grant: grant the permission as a runtime one. */
473    private static final int GRANT_RUNTIME = 3;
474
475    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
476    private static final int GRANT_UPGRADE = 4;
477
478    /** Canonical intent used to identify what counts as a "web browser" app */
479    private static final Intent sBrowserIntent;
480    static {
481        sBrowserIntent = new Intent();
482        sBrowserIntent.setAction(Intent.ACTION_VIEW);
483        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
484        sBrowserIntent.setData(Uri.parse("http:"));
485    }
486
487    /**
488     * The set of all protected actions [i.e. those actions for which a high priority
489     * intent filter is disallowed].
490     */
491    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
492    static {
493        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
495        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
496        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
497    }
498
499    // Compilation reasons.
500    public static final int REASON_FIRST_BOOT = 0;
501    public static final int REASON_BOOT = 1;
502    public static final int REASON_INSTALL = 2;
503    public static final int REASON_BACKGROUND_DEXOPT = 3;
504    public static final int REASON_AB_OTA = 4;
505    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
506    public static final int REASON_SHARED_APK = 6;
507    public static final int REASON_FORCED_DEXOPT = 7;
508    public static final int REASON_CORE_APP = 8;
509
510    public static final int REASON_LAST = REASON_CORE_APP;
511
512    /** Special library name that skips shared libraries check during compilation. */
513    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
514
515    final ServiceThread mHandlerThread;
516
517    final PackageHandler mHandler;
518
519    private final ProcessLoggingHandler mProcessLoggingHandler;
520
521    /**
522     * Messages for {@link #mHandler} that need to wait for system ready before
523     * being dispatched.
524     */
525    private ArrayList<Message> mPostSystemReadyMessages;
526
527    final int mSdkVersion = Build.VERSION.SDK_INT;
528
529    final Context mContext;
530    final boolean mFactoryTest;
531    final boolean mOnlyCore;
532    final DisplayMetrics mMetrics;
533    final int mDefParseFlags;
534    final String[] mSeparateProcesses;
535    final boolean mIsUpgrade;
536    final boolean mIsPreNUpgrade;
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            new DefaultPermissionGrantPolicy(this);
743
744    // List of packages names to keep cached, even if they are uninstalled for all users
745    private List<String> mKeepUninstalledPackages;
746
747    private UserManagerInternal mUserManagerInternal;
748
749    private static class IFVerificationParams {
750        PackageParser.Package pkg;
751        boolean replacing;
752        int userId;
753        int verifierUid;
754
755        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
756                int _userId, int _verifierUid) {
757            pkg = _pkg;
758            replacing = _replacing;
759            userId = _userId;
760            replacing = _replacing;
761            verifierUid = _verifierUid;
762        }
763    }
764
765    private interface IntentFilterVerifier<T extends IntentFilter> {
766        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
767                                               T filter, String packageName);
768        void startVerifications(int userId);
769        void receiveVerificationResponse(int verificationId);
770    }
771
772    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
773        private Context mContext;
774        private ComponentName mIntentFilterVerifierComponent;
775        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
776
777        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
778            mContext = context;
779            mIntentFilterVerifierComponent = verifierComponent;
780        }
781
782        private String getDefaultScheme() {
783            return IntentFilter.SCHEME_HTTPS;
784        }
785
786        @Override
787        public void startVerifications(int userId) {
788            // Launch verifications requests
789            int count = mCurrentIntentFilterVerifications.size();
790            for (int n=0; n<count; n++) {
791                int verificationId = mCurrentIntentFilterVerifications.get(n);
792                final IntentFilterVerificationState ivs =
793                        mIntentFilterVerificationStates.get(verificationId);
794
795                String packageName = ivs.getPackageName();
796
797                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
798                final int filterCount = filters.size();
799                ArraySet<String> domainsSet = new ArraySet<>();
800                for (int m=0; m<filterCount; m++) {
801                    PackageParser.ActivityIntentInfo filter = filters.get(m);
802                    domainsSet.addAll(filter.getHostsList());
803                }
804                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
805                synchronized (mPackages) {
806                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
807                            packageName, domainsList) != null) {
808                        scheduleWriteSettingsLocked();
809                    }
810                }
811                sendVerificationRequest(userId, verificationId, ivs);
812            }
813            mCurrentIntentFilterVerifications.clear();
814        }
815
816        private void sendVerificationRequest(int userId, int verificationId,
817                IntentFilterVerificationState ivs) {
818
819            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
822                    verificationId);
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
825                    getDefaultScheme());
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
828                    ivs.getHostsString());
829            verificationIntent.putExtra(
830                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
831                    ivs.getPackageName());
832            verificationIntent.setComponent(mIntentFilterVerifierComponent);
833            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
834
835            UserHandle user = new UserHandle(userId);
836            mContext.sendBroadcastAsUser(verificationIntent, user);
837            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
838                    "Sending IntentFilter verification broadcast");
839        }
840
841        public void receiveVerificationResponse(int verificationId) {
842            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
843
844            final boolean verified = ivs.isVerified();
845
846            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
847            final int count = filters.size();
848            if (DEBUG_DOMAIN_VERIFICATION) {
849                Slog.i(TAG, "Received verification response " + verificationId
850                        + " for " + count + " filters, verified=" + verified);
851            }
852            for (int n=0; n<count; n++) {
853                PackageParser.ActivityIntentInfo filter = filters.get(n);
854                filter.setVerified(verified);
855
856                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
857                        + " verified with result:" + verified + " and hosts:"
858                        + ivs.getHostsString());
859            }
860
861            mIntentFilterVerificationStates.remove(verificationId);
862
863            final String packageName = ivs.getPackageName();
864            IntentFilterVerificationInfo ivi = null;
865
866            synchronized (mPackages) {
867                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
868            }
869            if (ivi == null) {
870                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
871                        + verificationId + " packageName:" + packageName);
872                return;
873            }
874            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
875                    "Updating IntentFilterVerificationInfo for package " + packageName
876                            +" verificationId:" + verificationId);
877
878            synchronized (mPackages) {
879                if (verified) {
880                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
881                } else {
882                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
883                }
884                scheduleWriteSettingsLocked();
885
886                final int userId = ivs.getUserId();
887                if (userId != UserHandle.USER_ALL) {
888                    final int userStatus =
889                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
890
891                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
892                    boolean needUpdate = false;
893
894                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
895                    // already been set by the User thru the Disambiguation dialog
896                    switch (userStatus) {
897                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
898                            if (verified) {
899                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
900                            } else {
901                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
902                            }
903                            needUpdate = true;
904                            break;
905
906                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
907                            if (verified) {
908                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
909                                needUpdate = true;
910                            }
911                            break;
912
913                        default:
914                            // Nothing to do
915                    }
916
917                    if (needUpdate) {
918                        mSettings.updateIntentFilterVerificationStatusLPw(
919                                packageName, updatedStatus, userId);
920                        scheduleWritePackageRestrictionsLocked(userId);
921                    }
922                }
923            }
924        }
925
926        @Override
927        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
928                    ActivityIntentInfo filter, String packageName) {
929            if (!hasValidDomains(filter)) {
930                return false;
931            }
932            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
933            if (ivs == null) {
934                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
935                        packageName);
936            }
937            if (DEBUG_DOMAIN_VERIFICATION) {
938                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
939            }
940            ivs.addFilter(filter);
941            return true;
942        }
943
944        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
945                int userId, int verificationId, String packageName) {
946            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
947                    verifierUid, userId, packageName);
948            ivs.setPendingState();
949            synchronized (mPackages) {
950                mIntentFilterVerificationStates.append(verificationId, ivs);
951                mCurrentIntentFilterVerifications.add(verificationId);
952            }
953            return ivs;
954        }
955    }
956
957    private static boolean hasValidDomains(ActivityIntentInfo filter) {
958        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
959                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
960                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
961    }
962
963    // Set of pending broadcasts for aggregating enable/disable of components.
964    static class PendingPackageBroadcasts {
965        // for each user id, a map of <package name -> components within that package>
966        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
967
968        public PendingPackageBroadcasts() {
969            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
970        }
971
972        public ArrayList<String> get(int userId, String packageName) {
973            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
974            return packages.get(packageName);
975        }
976
977        public void put(int userId, String packageName, ArrayList<String> components) {
978            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
979            packages.put(packageName, components);
980        }
981
982        public void remove(int userId, String packageName) {
983            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
984            if (packages != null) {
985                packages.remove(packageName);
986            }
987        }
988
989        public void remove(int userId) {
990            mUidMap.remove(userId);
991        }
992
993        public int userIdCount() {
994            return mUidMap.size();
995        }
996
997        public int userIdAt(int n) {
998            return mUidMap.keyAt(n);
999        }
1000
1001        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1002            return mUidMap.get(userId);
1003        }
1004
1005        public int size() {
1006            // total number of pending broadcast entries across all userIds
1007            int num = 0;
1008            for (int i = 0; i< mUidMap.size(); i++) {
1009                num += mUidMap.valueAt(i).size();
1010            }
1011            return num;
1012        }
1013
1014        public void clear() {
1015            mUidMap.clear();
1016        }
1017
1018        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1019            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1020            if (map == null) {
1021                map = new ArrayMap<String, ArrayList<String>>();
1022                mUidMap.put(userId, map);
1023            }
1024            return map;
1025        }
1026    }
1027    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1028
1029    // Service Connection to remote media container service to copy
1030    // package uri's from external media onto secure containers
1031    // or internal storage.
1032    private IMediaContainerService mContainerService = null;
1033
1034    static final int SEND_PENDING_BROADCAST = 1;
1035    static final int MCS_BOUND = 3;
1036    static final int END_COPY = 4;
1037    static final int INIT_COPY = 5;
1038    static final int MCS_UNBIND = 6;
1039    static final int START_CLEANING_PACKAGE = 7;
1040    static final int FIND_INSTALL_LOC = 8;
1041    static final int POST_INSTALL = 9;
1042    static final int MCS_RECONNECT = 10;
1043    static final int MCS_GIVE_UP = 11;
1044    static final int UPDATED_MEDIA_STATUS = 12;
1045    static final int WRITE_SETTINGS = 13;
1046    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1047    static final int PACKAGE_VERIFIED = 15;
1048    static final int CHECK_PENDING_VERIFICATION = 16;
1049    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1050    static final int INTENT_FILTER_VERIFIED = 18;
1051    static final int WRITE_PACKAGE_LIST = 19;
1052
1053    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1054
1055    // Delay time in millisecs
1056    static final int BROADCAST_DELAY = 10 * 1000;
1057
1058    static UserManagerService sUserManager;
1059
1060    // Stores a list of users whose package restrictions file needs to be updated
1061    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1062
1063    final private DefaultContainerConnection mDefContainerConn =
1064            new DefaultContainerConnection();
1065    class DefaultContainerConnection implements ServiceConnection {
1066        public void onServiceConnected(ComponentName name, IBinder service) {
1067            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1068            IMediaContainerService imcs =
1069                IMediaContainerService.Stub.asInterface(service);
1070            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1071        }
1072
1073        public void onServiceDisconnected(ComponentName name) {
1074            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1075        }
1076    }
1077
1078    // Recordkeeping of restore-after-install operations that are currently in flight
1079    // between the Package Manager and the Backup Manager
1080    static class PostInstallData {
1081        public InstallArgs args;
1082        public PackageInstalledInfo res;
1083
1084        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1085            args = _a;
1086            res = _r;
1087        }
1088    }
1089
1090    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1091    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1092
1093    // XML tags for backup/restore of various bits of state
1094    private static final String TAG_PREFERRED_BACKUP = "pa";
1095    private static final String TAG_DEFAULT_APPS = "da";
1096    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1097
1098    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1099    private static final String TAG_ALL_GRANTS = "rt-grants";
1100    private static final String TAG_GRANT = "grant";
1101    private static final String ATTR_PACKAGE_NAME = "pkg";
1102
1103    private static final String TAG_PERMISSION = "perm";
1104    private static final String ATTR_PERMISSION_NAME = "name";
1105    private static final String ATTR_IS_GRANTED = "g";
1106    private static final String ATTR_USER_SET = "set";
1107    private static final String ATTR_USER_FIXED = "fixed";
1108    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1109
1110    // System/policy permission grants are not backed up
1111    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1112            FLAG_PERMISSION_POLICY_FIXED
1113            | FLAG_PERMISSION_SYSTEM_FIXED
1114            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1115
1116    // And we back up these user-adjusted states
1117    private static final int USER_RUNTIME_GRANT_MASK =
1118            FLAG_PERMISSION_USER_SET
1119            | FLAG_PERMISSION_USER_FIXED
1120            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1121
1122    final @Nullable String mRequiredVerifierPackage;
1123    final @NonNull String mRequiredInstallerPackage;
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        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
1968        // disabled after already being started.
1969        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
1970                UserHandle.USER_SYSTEM);
1971        ServiceManager.addService("package", m);
1972        return m;
1973    }
1974
1975    private void enableSystemUserPackages() {
1976        if (!UserManager.isSplitSystemUser()) {
1977            return;
1978        }
1979        // For system user, enable apps based on the following conditions:
1980        // - app is whitelisted or belong to one of these groups:
1981        //   -- system app which has no launcher icons
1982        //   -- system app which has INTERACT_ACROSS_USERS permission
1983        //   -- system IME app
1984        // - app is not in the blacklist
1985        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1986        Set<String> enableApps = new ArraySet<>();
1987        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1988                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1989                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1990        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1991        enableApps.addAll(wlApps);
1992        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1993                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1994        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1995        enableApps.removeAll(blApps);
1996        Log.i(TAG, "Applications installed for system user: " + enableApps);
1997        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1998                UserHandle.SYSTEM);
1999        final int allAppsSize = allAps.size();
2000        synchronized (mPackages) {
2001            for (int i = 0; i < allAppsSize; i++) {
2002                String pName = allAps.get(i);
2003                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2004                // Should not happen, but we shouldn't be failing if it does
2005                if (pkgSetting == null) {
2006                    continue;
2007                }
2008                boolean install = enableApps.contains(pName);
2009                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2010                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2011                            + " for system user");
2012                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2013                }
2014            }
2015        }
2016    }
2017
2018    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2019        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2020                Context.DISPLAY_SERVICE);
2021        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2022    }
2023
2024    /**
2025     * Requests that files preopted on a secondary system partition be copied to the data partition
2026     * if possible.  Note that the actual copying of the files is accomplished by init for security
2027     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2028     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2029     */
2030    private static void requestCopyPreoptedFiles() {
2031        final int WAIT_TIME_MS = 100;
2032        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2033        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2034            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2035            // We will wait for up to 100 seconds.
2036            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2037            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2038                try {
2039                    Thread.sleep(WAIT_TIME_MS);
2040                } catch (InterruptedException e) {
2041                    // Do nothing
2042                }
2043                if (SystemClock.uptimeMillis() > timeEnd) {
2044                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2045                    Slog.wtf(TAG, "cppreopt did not finish!");
2046                    break;
2047                }
2048            }
2049        }
2050    }
2051
2052    public PackageManagerService(Context context, Installer installer,
2053            boolean factoryTest, boolean onlyCore) {
2054        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2055                SystemClock.uptimeMillis());
2056
2057        if (mSdkVersion <= 0) {
2058            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2059        }
2060
2061        mContext = context;
2062        mFactoryTest = factoryTest;
2063        mOnlyCore = onlyCore;
2064        mMetrics = new DisplayMetrics();
2065        mSettings = new Settings(mPackages);
2066        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2067                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2068        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2069                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2070        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2071                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2072        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2073                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2074        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2075                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2076        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2077                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2078
2079        String separateProcesses = SystemProperties.get("debug.separate_processes");
2080        if (separateProcesses != null && separateProcesses.length() > 0) {
2081            if ("*".equals(separateProcesses)) {
2082                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2083                mSeparateProcesses = null;
2084                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2085            } else {
2086                mDefParseFlags = 0;
2087                mSeparateProcesses = separateProcesses.split(",");
2088                Slog.w(TAG, "Running with debug.separate_processes: "
2089                        + separateProcesses);
2090            }
2091        } else {
2092            mDefParseFlags = 0;
2093            mSeparateProcesses = null;
2094        }
2095
2096        mInstaller = installer;
2097        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2098                "*dexopt*");
2099        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2100
2101        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2102                FgThread.get().getLooper());
2103
2104        getDefaultDisplayMetrics(context, mMetrics);
2105
2106        SystemConfig systemConfig = SystemConfig.getInstance();
2107        mGlobalGids = systemConfig.getGlobalGids();
2108        mSystemPermissions = systemConfig.getSystemPermissions();
2109        mAvailableFeatures = systemConfig.getAvailableFeatures();
2110
2111        mProtectedPackages = new ProtectedPackages(mContext);
2112
2113        synchronized (mInstallLock) {
2114        // writer
2115        synchronized (mPackages) {
2116            mHandlerThread = new ServiceThread(TAG,
2117                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2118            mHandlerThread.start();
2119            mHandler = new PackageHandler(mHandlerThread.getLooper());
2120            mProcessLoggingHandler = new ProcessLoggingHandler();
2121            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2122
2123            File dataDir = Environment.getDataDirectory();
2124            mAppInstallDir = new File(dataDir, "app");
2125            mAppLib32InstallDir = new File(dataDir, "app-lib");
2126            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2127            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2128            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2129
2130            sUserManager = new UserManagerService(context, this, mPackages);
2131
2132            // Propagate permission configuration in to package manager.
2133            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2134                    = systemConfig.getPermissions();
2135            for (int i=0; i<permConfig.size(); i++) {
2136                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2137                BasePermission bp = mSettings.mPermissions.get(perm.name);
2138                if (bp == null) {
2139                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2140                    mSettings.mPermissions.put(perm.name, bp);
2141                }
2142                if (perm.gids != null) {
2143                    bp.setGids(perm.gids, perm.perUser);
2144                }
2145            }
2146
2147            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2148            for (int i=0; i<libConfig.size(); i++) {
2149                mSharedLibraries.put(libConfig.keyAt(i),
2150                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2151            }
2152
2153            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2154
2155            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2156
2157            if (mFirstBoot) {
2158                requestCopyPreoptedFiles();
2159            }
2160
2161            String customResolverActivity = Resources.getSystem().getString(
2162                    R.string.config_customResolverActivity);
2163            if (TextUtils.isEmpty(customResolverActivity)) {
2164                customResolverActivity = null;
2165            } else {
2166                mCustomResolverComponentName = ComponentName.unflattenFromString(
2167                        customResolverActivity);
2168            }
2169
2170            long startTime = SystemClock.uptimeMillis();
2171
2172            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2173                    startTime);
2174
2175            // Set flag to monitor and not change apk file paths when
2176            // scanning install directories.
2177            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2178
2179            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2180            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2181
2182            if (bootClassPath == null) {
2183                Slog.w(TAG, "No BOOTCLASSPATH found!");
2184            }
2185
2186            if (systemServerClassPath == null) {
2187                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2188            }
2189
2190            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2191            final String[] dexCodeInstructionSets =
2192                    getDexCodeInstructionSets(
2193                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2194
2195            /**
2196             * Ensure all external libraries have had dexopt run on them.
2197             */
2198            if (mSharedLibraries.size() > 0) {
2199                // NOTE: For now, we're compiling these system "shared libraries"
2200                // (and framework jars) into all available architectures. It's possible
2201                // to compile them only when we come across an app that uses them (there's
2202                // already logic for that in scanPackageLI) but that adds some complexity.
2203                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2204                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2205                        final String lib = libEntry.path;
2206                        if (lib == null) {
2207                            continue;
2208                        }
2209
2210                        try {
2211                            // Shared libraries do not have profiles so we perform a full
2212                            // AOT compilation (if needed).
2213                            int dexoptNeeded = DexFile.getDexOptNeeded(
2214                                    lib, dexCodeInstructionSet,
2215                                    getCompilerFilterForReason(REASON_SHARED_APK),
2216                                    false /* newProfile */);
2217                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2218                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2219                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2220                                        getCompilerFilterForReason(REASON_SHARED_APK),
2221                                        StorageManager.UUID_PRIVATE_INTERNAL,
2222                                        SKIP_SHARED_LIBRARY_CHECK);
2223                            }
2224                        } catch (FileNotFoundException e) {
2225                            Slog.w(TAG, "Library not found: " + lib);
2226                        } catch (IOException | InstallerException e) {
2227                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2228                                    + e.getMessage());
2229                        }
2230                    }
2231                }
2232            }
2233
2234            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2235
2236            final VersionInfo ver = mSettings.getInternalVersion();
2237            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2238
2239            // when upgrading from pre-M, promote system app permissions from install to runtime
2240            mPromoteSystemApps =
2241                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2242
2243            // When upgrading from pre-N, we need to handle package extraction like first boot,
2244            // as there is no profiling data available.
2245            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
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, true /* migrateAppData */);
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                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2630                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2631                        mIntentFilterVerifierComponent);
2632                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2633                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2634                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2635                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2636            } else {
2637                mRequiredVerifierPackage = null;
2638                mRequiredInstallerPackage = null;
2639                mIntentFilterVerifierComponent = null;
2640                mIntentFilterVerifier = null;
2641                mServicesSystemSharedLibraryPackageName = null;
2642                mSharedSystemSharedLibraryPackageName = null;
2643            }
2644
2645            mInstallerService = new PackageInstallerService(context, this);
2646
2647            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2648            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2649            // both the installer and resolver must be present to enable ephemeral
2650            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2651                if (DEBUG_EPHEMERAL) {
2652                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2653                            + " installer:" + ephemeralInstallerComponent);
2654                }
2655                mEphemeralResolverComponent = ephemeralResolverComponent;
2656                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2657                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2658                mEphemeralResolverConnection =
2659                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2660            } else {
2661                if (DEBUG_EPHEMERAL) {
2662                    final String missingComponent =
2663                            (ephemeralResolverComponent == null)
2664                            ? (ephemeralInstallerComponent == null)
2665                                    ? "resolver and installer"
2666                                    : "resolver"
2667                            : "installer";
2668                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2669                }
2670                mEphemeralResolverComponent = null;
2671                mEphemeralInstallerComponent = null;
2672                mEphemeralResolverConnection = null;
2673            }
2674
2675            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2676        } // synchronized (mPackages)
2677        } // synchronized (mInstallLock)
2678
2679        // Now after opening every single application zip, make sure they
2680        // are all flushed.  Not really needed, but keeps things nice and
2681        // tidy.
2682        Runtime.getRuntime().gc();
2683
2684        // The initial scanning above does many calls into installd while
2685        // holding the mPackages lock, but we're mostly interested in yelling
2686        // once we have a booted system.
2687        mInstaller.setWarnIfHeld(mPackages);
2688
2689        // Expose private service for system components to use.
2690        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2691    }
2692
2693    @Override
2694    public boolean isFirstBoot() {
2695        return mFirstBoot;
2696    }
2697
2698    @Override
2699    public boolean isOnlyCoreApps() {
2700        return mOnlyCore;
2701    }
2702
2703    @Override
2704    public boolean isUpgrade() {
2705        return mIsUpgrade;
2706    }
2707
2708    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2709        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2710
2711        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2712                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2713                UserHandle.USER_SYSTEM);
2714        if (matches.size() == 1) {
2715            return matches.get(0).getComponentInfo().packageName;
2716        } else {
2717            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2718            return null;
2719        }
2720    }
2721
2722    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2723        synchronized (mPackages) {
2724            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2725            if (libraryEntry == null) {
2726                throw new IllegalStateException("Missing required shared library:" + libraryName);
2727            }
2728            return libraryEntry.apk;
2729        }
2730    }
2731
2732    private @NonNull String getRequiredInstallerLPr() {
2733        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2734        intent.addCategory(Intent.CATEGORY_DEFAULT);
2735        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2736
2737        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2738                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2739                UserHandle.USER_SYSTEM);
2740        if (matches.size() == 1) {
2741            ResolveInfo resolveInfo = matches.get(0);
2742            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2743                throw new RuntimeException("The installer must be a privileged app");
2744            }
2745            return matches.get(0).getComponentInfo().packageName;
2746        } else {
2747            throw new RuntimeException("There must be exactly one installer; found " + matches);
2748        }
2749    }
2750
2751    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2752        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2753
2754        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2755                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2756                UserHandle.USER_SYSTEM);
2757        ResolveInfo best = null;
2758        final int N = matches.size();
2759        for (int i = 0; i < N; i++) {
2760            final ResolveInfo cur = matches.get(i);
2761            final String packageName = cur.getComponentInfo().packageName;
2762            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2763                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2764                continue;
2765            }
2766
2767            if (best == null || cur.priority > best.priority) {
2768                best = cur;
2769            }
2770        }
2771
2772        if (best != null) {
2773            return best.getComponentInfo().getComponentName();
2774        } else {
2775            throw new RuntimeException("There must be at least one intent filter verifier");
2776        }
2777    }
2778
2779    private @Nullable ComponentName getEphemeralResolverLPr() {
2780        final String[] packageArray =
2781                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2782        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2783            if (DEBUG_EPHEMERAL) {
2784                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2785            }
2786            return null;
2787        }
2788
2789        final int resolveFlags =
2790                MATCH_DIRECT_BOOT_AWARE
2791                | MATCH_DIRECT_BOOT_UNAWARE
2792                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2793        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2794        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2795                resolveFlags, UserHandle.USER_SYSTEM);
2796
2797        final int N = resolvers.size();
2798        if (N == 0) {
2799            if (DEBUG_EPHEMERAL) {
2800                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2801            }
2802            return null;
2803        }
2804
2805        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2806        for (int i = 0; i < N; i++) {
2807            final ResolveInfo info = resolvers.get(i);
2808
2809            if (info.serviceInfo == null) {
2810                continue;
2811            }
2812
2813            final String packageName = info.serviceInfo.packageName;
2814            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2815                if (DEBUG_EPHEMERAL) {
2816                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2817                            + " pkg: " + packageName + ", info:" + info);
2818                }
2819                continue;
2820            }
2821
2822            if (DEBUG_EPHEMERAL) {
2823                Slog.v(TAG, "Ephemeral resolver found;"
2824                        + " pkg: " + packageName + ", info:" + info);
2825            }
2826            return new ComponentName(packageName, info.serviceInfo.name);
2827        }
2828        if (DEBUG_EPHEMERAL) {
2829            Slog.v(TAG, "Ephemeral resolver NOT found");
2830        }
2831        return null;
2832    }
2833
2834    private @Nullable ComponentName getEphemeralInstallerLPr() {
2835        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2836        intent.addCategory(Intent.CATEGORY_DEFAULT);
2837        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2838
2839        final int resolveFlags =
2840                MATCH_DIRECT_BOOT_AWARE
2841                | MATCH_DIRECT_BOOT_UNAWARE
2842                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2843        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2844                resolveFlags, UserHandle.USER_SYSTEM);
2845        if (matches.size() == 0) {
2846            return null;
2847        } else if (matches.size() == 1) {
2848            return matches.get(0).getComponentInfo().getComponentName();
2849        } else {
2850            throw new RuntimeException(
2851                    "There must be at most one ephemeral installer; found " + matches);
2852        }
2853    }
2854
2855    private void primeDomainVerificationsLPw(int userId) {
2856        if (DEBUG_DOMAIN_VERIFICATION) {
2857            Slog.d(TAG, "Priming domain verifications in user " + userId);
2858        }
2859
2860        SystemConfig systemConfig = SystemConfig.getInstance();
2861        ArraySet<String> packages = systemConfig.getLinkedApps();
2862        ArraySet<String> domains = new ArraySet<String>();
2863
2864        for (String packageName : packages) {
2865            PackageParser.Package pkg = mPackages.get(packageName);
2866            if (pkg != null) {
2867                if (!pkg.isSystemApp()) {
2868                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2869                    continue;
2870                }
2871
2872                domains.clear();
2873                for (PackageParser.Activity a : pkg.activities) {
2874                    for (ActivityIntentInfo filter : a.intents) {
2875                        if (hasValidDomains(filter)) {
2876                            domains.addAll(filter.getHostsList());
2877                        }
2878                    }
2879                }
2880
2881                if (domains.size() > 0) {
2882                    if (DEBUG_DOMAIN_VERIFICATION) {
2883                        Slog.v(TAG, "      + " + packageName);
2884                    }
2885                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2886                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2887                    // and then 'always' in the per-user state actually used for intent resolution.
2888                    final IntentFilterVerificationInfo ivi;
2889                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2890                            new ArrayList<String>(domains));
2891                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2892                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2893                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2894                } else {
2895                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2896                            + "' does not handle web links");
2897                }
2898            } else {
2899                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2900            }
2901        }
2902
2903        scheduleWritePackageRestrictionsLocked(userId);
2904        scheduleWriteSettingsLocked();
2905    }
2906
2907    private void applyFactoryDefaultBrowserLPw(int userId) {
2908        // The default browser app's package name is stored in a string resource,
2909        // with a product-specific overlay used for vendor customization.
2910        String browserPkg = mContext.getResources().getString(
2911                com.android.internal.R.string.default_browser);
2912        if (!TextUtils.isEmpty(browserPkg)) {
2913            // non-empty string => required to be a known package
2914            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2915            if (ps == null) {
2916                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2917                browserPkg = null;
2918            } else {
2919                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2920            }
2921        }
2922
2923        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2924        // default.  If there's more than one, just leave everything alone.
2925        if (browserPkg == null) {
2926            calculateDefaultBrowserLPw(userId);
2927        }
2928    }
2929
2930    private void calculateDefaultBrowserLPw(int userId) {
2931        List<String> allBrowsers = resolveAllBrowserApps(userId);
2932        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2933        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2934    }
2935
2936    private List<String> resolveAllBrowserApps(int userId) {
2937        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2938        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2939                PackageManager.MATCH_ALL, userId);
2940
2941        final int count = list.size();
2942        List<String> result = new ArrayList<String>(count);
2943        for (int i=0; i<count; i++) {
2944            ResolveInfo info = list.get(i);
2945            if (info.activityInfo == null
2946                    || !info.handleAllWebDataURI
2947                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2948                    || result.contains(info.activityInfo.packageName)) {
2949                continue;
2950            }
2951            result.add(info.activityInfo.packageName);
2952        }
2953
2954        return result;
2955    }
2956
2957    private boolean packageIsBrowser(String packageName, int userId) {
2958        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2959                PackageManager.MATCH_ALL, userId);
2960        final int N = list.size();
2961        for (int i = 0; i < N; i++) {
2962            ResolveInfo info = list.get(i);
2963            if (packageName.equals(info.activityInfo.packageName)) {
2964                return true;
2965            }
2966        }
2967        return false;
2968    }
2969
2970    private void checkDefaultBrowser() {
2971        final int myUserId = UserHandle.myUserId();
2972        final String packageName = getDefaultBrowserPackageName(myUserId);
2973        if (packageName != null) {
2974            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2975            if (info == null) {
2976                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2977                synchronized (mPackages) {
2978                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2979                }
2980            }
2981        }
2982    }
2983
2984    @Override
2985    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2986            throws RemoteException {
2987        try {
2988            return super.onTransact(code, data, reply, flags);
2989        } catch (RuntimeException e) {
2990            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2991                Slog.wtf(TAG, "Package Manager Crash", e);
2992            }
2993            throw e;
2994        }
2995    }
2996
2997    static int[] appendInts(int[] cur, int[] add) {
2998        if (add == null) return cur;
2999        if (cur == null) return add;
3000        final int N = add.length;
3001        for (int i=0; i<N; i++) {
3002            cur = appendInt(cur, add[i]);
3003        }
3004        return cur;
3005    }
3006
3007    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        if (ps == null) {
3010            return null;
3011        }
3012        final PackageParser.Package p = ps.pkg;
3013        if (p == null) {
3014            return null;
3015        }
3016
3017        final PermissionsState permissionsState = ps.getPermissionsState();
3018
3019        // Compute GIDs only if requested
3020        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3021                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3022        // Compute granted permissions only if package has requested permissions
3023        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3024                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3025        final PackageUserState state = ps.readUserState(userId);
3026
3027        return PackageParser.generatePackageInfo(p, gids, flags,
3028                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3029    }
3030
3031    @Override
3032    public void checkPackageStartable(String packageName, int userId) {
3033        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3034
3035        synchronized (mPackages) {
3036            final PackageSetting ps = mSettings.mPackages.get(packageName);
3037            if (ps == null) {
3038                throw new SecurityException("Package " + packageName + " was not found!");
3039            }
3040
3041            if (!ps.getInstalled(userId)) {
3042                throw new SecurityException(
3043                        "Package " + packageName + " was not installed for user " + userId + "!");
3044            }
3045
3046            if (mSafeMode && !ps.isSystem()) {
3047                throw new SecurityException("Package " + packageName + " not a system app!");
3048            }
3049
3050            if (mFrozenPackages.contains(packageName)) {
3051                throw new SecurityException("Package " + packageName + " is currently frozen!");
3052            }
3053
3054            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3055                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3056                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3057            }
3058        }
3059    }
3060
3061    @Override
3062    public boolean isPackageAvailable(String packageName, int userId) {
3063        if (!sUserManager.exists(userId)) return false;
3064        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3065                false /* requireFullPermission */, false /* checkShell */, "is package available");
3066        synchronized (mPackages) {
3067            PackageParser.Package p = mPackages.get(packageName);
3068            if (p != null) {
3069                final PackageSetting ps = (PackageSetting) p.mExtras;
3070                if (ps != null) {
3071                    final PackageUserState state = ps.readUserState(userId);
3072                    if (state != null) {
3073                        return PackageParser.isAvailable(state);
3074                    }
3075                }
3076            }
3077        }
3078        return false;
3079    }
3080
3081    @Override
3082    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3083        if (!sUserManager.exists(userId)) return null;
3084        flags = updateFlagsForPackage(flags, userId, packageName);
3085        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3086                false /* requireFullPermission */, false /* checkShell */, "get package info");
3087        // reader
3088        synchronized (mPackages) {
3089            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3090            PackageParser.Package p = null;
3091            if (matchFactoryOnly) {
3092                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3093                if (ps != null) {
3094                    return generatePackageInfo(ps, flags, userId);
3095                }
3096            }
3097            if (p == null) {
3098                p = mPackages.get(packageName);
3099                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3100                    return null;
3101                }
3102            }
3103            if (DEBUG_PACKAGE_INFO)
3104                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3105            if (p != null) {
3106                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3107            }
3108            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3109                final PackageSetting ps = mSettings.mPackages.get(packageName);
3110                return generatePackageInfo(ps, flags, userId);
3111            }
3112        }
3113        return null;
3114    }
3115
3116    @Override
3117    public String[] currentToCanonicalPackageNames(String[] names) {
3118        String[] out = new String[names.length];
3119        // reader
3120        synchronized (mPackages) {
3121            for (int i=names.length-1; i>=0; i--) {
3122                PackageSetting ps = mSettings.mPackages.get(names[i]);
3123                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3124            }
3125        }
3126        return out;
3127    }
3128
3129    @Override
3130    public String[] canonicalToCurrentPackageNames(String[] names) {
3131        String[] out = new String[names.length];
3132        // reader
3133        synchronized (mPackages) {
3134            for (int i=names.length-1; i>=0; i--) {
3135                String cur = mSettings.mRenamedPackages.get(names[i]);
3136                out[i] = cur != null ? cur : names[i];
3137            }
3138        }
3139        return out;
3140    }
3141
3142    @Override
3143    public int getPackageUid(String packageName, int flags, int userId) {
3144        if (!sUserManager.exists(userId)) return -1;
3145        flags = updateFlagsForPackage(flags, userId, packageName);
3146        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3147                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3148
3149        // reader
3150        synchronized (mPackages) {
3151            final PackageParser.Package p = mPackages.get(packageName);
3152            if (p != null && p.isMatch(flags)) {
3153                return UserHandle.getUid(userId, p.applicationInfo.uid);
3154            }
3155            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3156                final PackageSetting ps = mSettings.mPackages.get(packageName);
3157                if (ps != null && ps.isMatch(flags)) {
3158                    return UserHandle.getUid(userId, ps.appId);
3159                }
3160            }
3161        }
3162
3163        return -1;
3164    }
3165
3166    @Override
3167    public int[] getPackageGids(String packageName, int flags, int userId) {
3168        if (!sUserManager.exists(userId)) return null;
3169        flags = updateFlagsForPackage(flags, userId, packageName);
3170        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3171                false /* requireFullPermission */, false /* checkShell */,
3172                "getPackageGids");
3173
3174        // reader
3175        synchronized (mPackages) {
3176            final PackageParser.Package p = mPackages.get(packageName);
3177            if (p != null && p.isMatch(flags)) {
3178                PackageSetting ps = (PackageSetting) p.mExtras;
3179                return ps.getPermissionsState().computeGids(userId);
3180            }
3181            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3182                final PackageSetting ps = mSettings.mPackages.get(packageName);
3183                if (ps != null && ps.isMatch(flags)) {
3184                    return ps.getPermissionsState().computeGids(userId);
3185                }
3186            }
3187        }
3188
3189        return null;
3190    }
3191
3192    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3193        if (bp.perm != null) {
3194            return PackageParser.generatePermissionInfo(bp.perm, flags);
3195        }
3196        PermissionInfo pi = new PermissionInfo();
3197        pi.name = bp.name;
3198        pi.packageName = bp.sourcePackage;
3199        pi.nonLocalizedLabel = bp.name;
3200        pi.protectionLevel = bp.protectionLevel;
3201        return pi;
3202    }
3203
3204    @Override
3205    public PermissionInfo getPermissionInfo(String name, int flags) {
3206        // reader
3207        synchronized (mPackages) {
3208            final BasePermission p = mSettings.mPermissions.get(name);
3209            if (p != null) {
3210                return generatePermissionInfo(p, flags);
3211            }
3212            return null;
3213        }
3214    }
3215
3216    @Override
3217    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3218            int flags) {
3219        // reader
3220        synchronized (mPackages) {
3221            if (group != null && !mPermissionGroups.containsKey(group)) {
3222                // This is thrown as NameNotFoundException
3223                return null;
3224            }
3225
3226            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3227            for (BasePermission p : mSettings.mPermissions.values()) {
3228                if (group == null) {
3229                    if (p.perm == null || p.perm.info.group == null) {
3230                        out.add(generatePermissionInfo(p, flags));
3231                    }
3232                } else {
3233                    if (p.perm != null && group.equals(p.perm.info.group)) {
3234                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3235                    }
3236                }
3237            }
3238            return new ParceledListSlice<>(out);
3239        }
3240    }
3241
3242    @Override
3243    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3244        // reader
3245        synchronized (mPackages) {
3246            return PackageParser.generatePermissionGroupInfo(
3247                    mPermissionGroups.get(name), flags);
3248        }
3249    }
3250
3251    @Override
3252    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3253        // reader
3254        synchronized (mPackages) {
3255            final int N = mPermissionGroups.size();
3256            ArrayList<PermissionGroupInfo> out
3257                    = new ArrayList<PermissionGroupInfo>(N);
3258            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3259                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3260            }
3261            return new ParceledListSlice<>(out);
3262        }
3263    }
3264
3265    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3266            int userId) {
3267        if (!sUserManager.exists(userId)) return null;
3268        PackageSetting ps = mSettings.mPackages.get(packageName);
3269        if (ps != null) {
3270            if (ps.pkg == null) {
3271                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3272                if (pInfo != null) {
3273                    return pInfo.applicationInfo;
3274                }
3275                return null;
3276            }
3277            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3278                    ps.readUserState(userId), userId);
3279        }
3280        return null;
3281    }
3282
3283    @Override
3284    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3285        if (!sUserManager.exists(userId)) return null;
3286        flags = updateFlagsForApplication(flags, userId, packageName);
3287        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3288                false /* requireFullPermission */, false /* checkShell */, "get application info");
3289        // writer
3290        synchronized (mPackages) {
3291            PackageParser.Package p = mPackages.get(packageName);
3292            if (DEBUG_PACKAGE_INFO) Log.v(
3293                    TAG, "getApplicationInfo " + packageName
3294                    + ": " + p);
3295            if (p != null) {
3296                PackageSetting ps = mSettings.mPackages.get(packageName);
3297                if (ps == null) return null;
3298                // Note: isEnabledLP() does not apply here - always return info
3299                return PackageParser.generateApplicationInfo(
3300                        p, flags, ps.readUserState(userId), userId);
3301            }
3302            if ("android".equals(packageName)||"system".equals(packageName)) {
3303                return mAndroidApplication;
3304            }
3305            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3306                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3307            }
3308        }
3309        return null;
3310    }
3311
3312    @Override
3313    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3314            final IPackageDataObserver observer) {
3315        mContext.enforceCallingOrSelfPermission(
3316                android.Manifest.permission.CLEAR_APP_CACHE, null);
3317        // Queue up an async operation since clearing cache may take a little while.
3318        mHandler.post(new Runnable() {
3319            public void run() {
3320                mHandler.removeCallbacks(this);
3321                boolean success = true;
3322                synchronized (mInstallLock) {
3323                    try {
3324                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3325                    } catch (InstallerException e) {
3326                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3327                        success = false;
3328                    }
3329                }
3330                if (observer != null) {
3331                    try {
3332                        observer.onRemoveCompleted(null, success);
3333                    } catch (RemoteException e) {
3334                        Slog.w(TAG, "RemoveException when invoking call back");
3335                    }
3336                }
3337            }
3338        });
3339    }
3340
3341    @Override
3342    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3343            final IntentSender pi) {
3344        mContext.enforceCallingOrSelfPermission(
3345                android.Manifest.permission.CLEAR_APP_CACHE, null);
3346        // Queue up an async operation since clearing cache may take a little while.
3347        mHandler.post(new Runnable() {
3348            public void run() {
3349                mHandler.removeCallbacks(this);
3350                boolean success = true;
3351                synchronized (mInstallLock) {
3352                    try {
3353                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3354                    } catch (InstallerException e) {
3355                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3356                        success = false;
3357                    }
3358                }
3359                if(pi != null) {
3360                    try {
3361                        // Callback via pending intent
3362                        int code = success ? 1 : 0;
3363                        pi.sendIntent(null, code, null,
3364                                null, null);
3365                    } catch (SendIntentException e1) {
3366                        Slog.i(TAG, "Failed to send pending intent");
3367                    }
3368                }
3369            }
3370        });
3371    }
3372
3373    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3374        synchronized (mInstallLock) {
3375            try {
3376                mInstaller.freeCache(volumeUuid, freeStorageSize);
3377            } catch (InstallerException e) {
3378                throw new IOException("Failed to free enough space", e);
3379            }
3380        }
3381    }
3382
3383    /**
3384     * Update given flags based on encryption status of current user.
3385     */
3386    private int updateFlags(int flags, int userId) {
3387        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3388                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3389            // Caller expressed an explicit opinion about what encryption
3390            // aware/unaware components they want to see, so fall through and
3391            // give them what they want
3392        } else {
3393            // Caller expressed no opinion, so match based on user state
3394            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3395                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3396            } else {
3397                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3398            }
3399        }
3400        return flags;
3401    }
3402
3403    private UserManagerInternal getUserManagerInternal() {
3404        if (mUserManagerInternal == null) {
3405            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3406        }
3407        return mUserManagerInternal;
3408    }
3409
3410    /**
3411     * Update given flags when being used to request {@link PackageInfo}.
3412     */
3413    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3414        boolean triaged = true;
3415        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3416                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3417            // Caller is asking for component details, so they'd better be
3418            // asking for specific encryption matching behavior, or be triaged
3419            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3420                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3421                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3422                triaged = false;
3423            }
3424        }
3425        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3426                | PackageManager.MATCH_SYSTEM_ONLY
3427                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3428            triaged = false;
3429        }
3430        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3431            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3432                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3433        }
3434        return updateFlags(flags, userId);
3435    }
3436
3437    /**
3438     * Update given flags when being used to request {@link ApplicationInfo}.
3439     */
3440    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3441        return updateFlagsForPackage(flags, userId, cookie);
3442    }
3443
3444    /**
3445     * Update given flags when being used to request {@link ComponentInfo}.
3446     */
3447    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3448        if (cookie instanceof Intent) {
3449            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3450                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3451            }
3452        }
3453
3454        boolean triaged = true;
3455        // Caller is asking for component details, so they'd better be
3456        // asking for specific encryption matching behavior, or be triaged
3457        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3458                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3459                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3460            triaged = false;
3461        }
3462        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3463            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3464                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3465        }
3466
3467        return updateFlags(flags, userId);
3468    }
3469
3470    /**
3471     * Update given flags when being used to request {@link ResolveInfo}.
3472     */
3473    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3474        // Safe mode means we shouldn't match any third-party components
3475        if (mSafeMode) {
3476            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3477        }
3478
3479        return updateFlagsForComponent(flags, userId, cookie);
3480    }
3481
3482    @Override
3483    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3484        if (!sUserManager.exists(userId)) return null;
3485        flags = updateFlagsForComponent(flags, userId, component);
3486        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3487                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3488        synchronized (mPackages) {
3489            PackageParser.Activity a = mActivities.mActivities.get(component);
3490
3491            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3492            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3493                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3494                if (ps == null) return null;
3495                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3496                        userId);
3497            }
3498            if (mResolveComponentName.equals(component)) {
3499                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3500                        new PackageUserState(), userId);
3501            }
3502        }
3503        return null;
3504    }
3505
3506    @Override
3507    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3508            String resolvedType) {
3509        synchronized (mPackages) {
3510            if (component.equals(mResolveComponentName)) {
3511                // The resolver supports EVERYTHING!
3512                return true;
3513            }
3514            PackageParser.Activity a = mActivities.mActivities.get(component);
3515            if (a == null) {
3516                return false;
3517            }
3518            for (int i=0; i<a.intents.size(); i++) {
3519                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3520                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3521                    return true;
3522                }
3523            }
3524            return false;
3525        }
3526    }
3527
3528    @Override
3529    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3530        if (!sUserManager.exists(userId)) return null;
3531        flags = updateFlagsForComponent(flags, userId, component);
3532        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3533                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3534        synchronized (mPackages) {
3535            PackageParser.Activity a = mReceivers.mActivities.get(component);
3536            if (DEBUG_PACKAGE_INFO) Log.v(
3537                TAG, "getReceiverInfo " + component + ": " + a);
3538            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3539                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3540                if (ps == null) return null;
3541                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3542                        userId);
3543            }
3544        }
3545        return null;
3546    }
3547
3548    @Override
3549    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3550        if (!sUserManager.exists(userId)) return null;
3551        flags = updateFlagsForComponent(flags, userId, component);
3552        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3553                false /* requireFullPermission */, false /* checkShell */, "get service info");
3554        synchronized (mPackages) {
3555            PackageParser.Service s = mServices.mServices.get(component);
3556            if (DEBUG_PACKAGE_INFO) Log.v(
3557                TAG, "getServiceInfo " + component + ": " + s);
3558            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3559                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3560                if (ps == null) return null;
3561                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3562                        userId);
3563            }
3564        }
3565        return null;
3566    }
3567
3568    @Override
3569    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3570        if (!sUserManager.exists(userId)) return null;
3571        flags = updateFlagsForComponent(flags, userId, component);
3572        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3573                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3574        synchronized (mPackages) {
3575            PackageParser.Provider p = mProviders.mProviders.get(component);
3576            if (DEBUG_PACKAGE_INFO) Log.v(
3577                TAG, "getProviderInfo " + component + ": " + p);
3578            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3579                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3580                if (ps == null) return null;
3581                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3582                        userId);
3583            }
3584        }
3585        return null;
3586    }
3587
3588    @Override
3589    public String[] getSystemSharedLibraryNames() {
3590        Set<String> libSet;
3591        synchronized (mPackages) {
3592            libSet = mSharedLibraries.keySet();
3593            int size = libSet.size();
3594            if (size > 0) {
3595                String[] libs = new String[size];
3596                libSet.toArray(libs);
3597                return libs;
3598            }
3599        }
3600        return null;
3601    }
3602
3603    @Override
3604    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3605        synchronized (mPackages) {
3606            return mServicesSystemSharedLibraryPackageName;
3607        }
3608    }
3609
3610    @Override
3611    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3612        synchronized (mPackages) {
3613            return mSharedSystemSharedLibraryPackageName;
3614        }
3615    }
3616
3617    @Override
3618    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3619        synchronized (mPackages) {
3620            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3621
3622            final FeatureInfo fi = new FeatureInfo();
3623            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3624                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3625            res.add(fi);
3626
3627            return new ParceledListSlice<>(res);
3628        }
3629    }
3630
3631    @Override
3632    public boolean hasSystemFeature(String name, int version) {
3633        synchronized (mPackages) {
3634            final FeatureInfo feat = mAvailableFeatures.get(name);
3635            if (feat == null) {
3636                return false;
3637            } else {
3638                return feat.version >= version;
3639            }
3640        }
3641    }
3642
3643    @Override
3644    public int checkPermission(String permName, String pkgName, int userId) {
3645        if (!sUserManager.exists(userId)) {
3646            return PackageManager.PERMISSION_DENIED;
3647        }
3648
3649        synchronized (mPackages) {
3650            final PackageParser.Package p = mPackages.get(pkgName);
3651            if (p != null && p.mExtras != null) {
3652                final PackageSetting ps = (PackageSetting) p.mExtras;
3653                final PermissionsState permissionsState = ps.getPermissionsState();
3654                if (permissionsState.hasPermission(permName, userId)) {
3655                    return PackageManager.PERMISSION_GRANTED;
3656                }
3657                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3658                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3659                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3660                    return PackageManager.PERMISSION_GRANTED;
3661                }
3662            }
3663        }
3664
3665        return PackageManager.PERMISSION_DENIED;
3666    }
3667
3668    @Override
3669    public int checkUidPermission(String permName, int uid) {
3670        final int userId = UserHandle.getUserId(uid);
3671
3672        if (!sUserManager.exists(userId)) {
3673            return PackageManager.PERMISSION_DENIED;
3674        }
3675
3676        synchronized (mPackages) {
3677            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3678            if (obj != null) {
3679                final SettingBase ps = (SettingBase) obj;
3680                final PermissionsState permissionsState = ps.getPermissionsState();
3681                if (permissionsState.hasPermission(permName, userId)) {
3682                    return PackageManager.PERMISSION_GRANTED;
3683                }
3684                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3685                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3686                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3687                    return PackageManager.PERMISSION_GRANTED;
3688                }
3689            } else {
3690                ArraySet<String> perms = mSystemPermissions.get(uid);
3691                if (perms != null) {
3692                    if (perms.contains(permName)) {
3693                        return PackageManager.PERMISSION_GRANTED;
3694                    }
3695                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3696                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3697                        return PackageManager.PERMISSION_GRANTED;
3698                    }
3699                }
3700            }
3701        }
3702
3703        return PackageManager.PERMISSION_DENIED;
3704    }
3705
3706    @Override
3707    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3708        if (UserHandle.getCallingUserId() != userId) {
3709            mContext.enforceCallingPermission(
3710                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3711                    "isPermissionRevokedByPolicy for user " + userId);
3712        }
3713
3714        if (checkPermission(permission, packageName, userId)
3715                == PackageManager.PERMISSION_GRANTED) {
3716            return false;
3717        }
3718
3719        final long identity = Binder.clearCallingIdentity();
3720        try {
3721            final int flags = getPermissionFlags(permission, packageName, userId);
3722            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3723        } finally {
3724            Binder.restoreCallingIdentity(identity);
3725        }
3726    }
3727
3728    @Override
3729    public String getPermissionControllerPackageName() {
3730        synchronized (mPackages) {
3731            return mRequiredInstallerPackage;
3732        }
3733    }
3734
3735    /**
3736     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3737     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3738     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3739     * @param message the message to log on security exception
3740     */
3741    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3742            boolean checkShell, String message) {
3743        if (userId < 0) {
3744            throw new IllegalArgumentException("Invalid userId " + userId);
3745        }
3746        if (checkShell) {
3747            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3748        }
3749        if (userId == UserHandle.getUserId(callingUid)) return;
3750        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3751            if (requireFullPermission) {
3752                mContext.enforceCallingOrSelfPermission(
3753                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3754            } else {
3755                try {
3756                    mContext.enforceCallingOrSelfPermission(
3757                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3758                } catch (SecurityException se) {
3759                    mContext.enforceCallingOrSelfPermission(
3760                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3761                }
3762            }
3763        }
3764    }
3765
3766    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3767        if (callingUid == Process.SHELL_UID) {
3768            if (userHandle >= 0
3769                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3770                throw new SecurityException("Shell does not have permission to access user "
3771                        + userHandle);
3772            } else if (userHandle < 0) {
3773                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3774                        + Debug.getCallers(3));
3775            }
3776        }
3777    }
3778
3779    private BasePermission findPermissionTreeLP(String permName) {
3780        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3781            if (permName.startsWith(bp.name) &&
3782                    permName.length() > bp.name.length() &&
3783                    permName.charAt(bp.name.length()) == '.') {
3784                return bp;
3785            }
3786        }
3787        return null;
3788    }
3789
3790    private BasePermission checkPermissionTreeLP(String permName) {
3791        if (permName != null) {
3792            BasePermission bp = findPermissionTreeLP(permName);
3793            if (bp != null) {
3794                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3795                    return bp;
3796                }
3797                throw new SecurityException("Calling uid "
3798                        + Binder.getCallingUid()
3799                        + " is not allowed to add to permission tree "
3800                        + bp.name + " owned by uid " + bp.uid);
3801            }
3802        }
3803        throw new SecurityException("No permission tree found for " + permName);
3804    }
3805
3806    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3807        if (s1 == null) {
3808            return s2 == null;
3809        }
3810        if (s2 == null) {
3811            return false;
3812        }
3813        if (s1.getClass() != s2.getClass()) {
3814            return false;
3815        }
3816        return s1.equals(s2);
3817    }
3818
3819    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3820        if (pi1.icon != pi2.icon) return false;
3821        if (pi1.logo != pi2.logo) return false;
3822        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3823        if (!compareStrings(pi1.name, pi2.name)) return false;
3824        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3825        // We'll take care of setting this one.
3826        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3827        // These are not currently stored in settings.
3828        //if (!compareStrings(pi1.group, pi2.group)) return false;
3829        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3830        //if (pi1.labelRes != pi2.labelRes) return false;
3831        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3832        return true;
3833    }
3834
3835    int permissionInfoFootprint(PermissionInfo info) {
3836        int size = info.name.length();
3837        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3838        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3839        return size;
3840    }
3841
3842    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3843        int size = 0;
3844        for (BasePermission perm : mSettings.mPermissions.values()) {
3845            if (perm.uid == tree.uid) {
3846                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3847            }
3848        }
3849        return size;
3850    }
3851
3852    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3853        // We calculate the max size of permissions defined by this uid and throw
3854        // if that plus the size of 'info' would exceed our stated maximum.
3855        if (tree.uid != Process.SYSTEM_UID) {
3856            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3857            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3858                throw new SecurityException("Permission tree size cap exceeded");
3859            }
3860        }
3861    }
3862
3863    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3864        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3865            throw new SecurityException("Label must be specified in permission");
3866        }
3867        BasePermission tree = checkPermissionTreeLP(info.name);
3868        BasePermission bp = mSettings.mPermissions.get(info.name);
3869        boolean added = bp == null;
3870        boolean changed = true;
3871        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3872        if (added) {
3873            enforcePermissionCapLocked(info, tree);
3874            bp = new BasePermission(info.name, tree.sourcePackage,
3875                    BasePermission.TYPE_DYNAMIC);
3876        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3877            throw new SecurityException(
3878                    "Not allowed to modify non-dynamic permission "
3879                    + info.name);
3880        } else {
3881            if (bp.protectionLevel == fixedLevel
3882                    && bp.perm.owner.equals(tree.perm.owner)
3883                    && bp.uid == tree.uid
3884                    && comparePermissionInfos(bp.perm.info, info)) {
3885                changed = false;
3886            }
3887        }
3888        bp.protectionLevel = fixedLevel;
3889        info = new PermissionInfo(info);
3890        info.protectionLevel = fixedLevel;
3891        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3892        bp.perm.info.packageName = tree.perm.info.packageName;
3893        bp.uid = tree.uid;
3894        if (added) {
3895            mSettings.mPermissions.put(info.name, bp);
3896        }
3897        if (changed) {
3898            if (!async) {
3899                mSettings.writeLPr();
3900            } else {
3901                scheduleWriteSettingsLocked();
3902            }
3903        }
3904        return added;
3905    }
3906
3907    @Override
3908    public boolean addPermission(PermissionInfo info) {
3909        synchronized (mPackages) {
3910            return addPermissionLocked(info, false);
3911        }
3912    }
3913
3914    @Override
3915    public boolean addPermissionAsync(PermissionInfo info) {
3916        synchronized (mPackages) {
3917            return addPermissionLocked(info, true);
3918        }
3919    }
3920
3921    @Override
3922    public void removePermission(String name) {
3923        synchronized (mPackages) {
3924            checkPermissionTreeLP(name);
3925            BasePermission bp = mSettings.mPermissions.get(name);
3926            if (bp != null) {
3927                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3928                    throw new SecurityException(
3929                            "Not allowed to modify non-dynamic permission "
3930                            + name);
3931                }
3932                mSettings.mPermissions.remove(name);
3933                mSettings.writeLPr();
3934            }
3935        }
3936    }
3937
3938    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3939            BasePermission bp) {
3940        int index = pkg.requestedPermissions.indexOf(bp.name);
3941        if (index == -1) {
3942            throw new SecurityException("Package " + pkg.packageName
3943                    + " has not requested permission " + bp.name);
3944        }
3945        if (!bp.isRuntime() && !bp.isDevelopment()) {
3946            throw new SecurityException("Permission " + bp.name
3947                    + " is not a changeable permission type");
3948        }
3949    }
3950
3951    @Override
3952    public void grantRuntimePermission(String packageName, String name, final int userId) {
3953        if (!sUserManager.exists(userId)) {
3954            Log.e(TAG, "No such user:" + userId);
3955            return;
3956        }
3957
3958        mContext.enforceCallingOrSelfPermission(
3959                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3960                "grantRuntimePermission");
3961
3962        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3963                true /* requireFullPermission */, true /* checkShell */,
3964                "grantRuntimePermission");
3965
3966        final int uid;
3967        final SettingBase sb;
3968
3969        synchronized (mPackages) {
3970            final PackageParser.Package pkg = mPackages.get(packageName);
3971            if (pkg == null) {
3972                throw new IllegalArgumentException("Unknown package: " + packageName);
3973            }
3974
3975            final BasePermission bp = mSettings.mPermissions.get(name);
3976            if (bp == null) {
3977                throw new IllegalArgumentException("Unknown permission: " + name);
3978            }
3979
3980            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3981
3982            // If a permission review is required for legacy apps we represent
3983            // their permissions as always granted runtime ones since we need
3984            // to keep the review required permission flag per user while an
3985            // install permission's state is shared across all users.
3986            if (Build.PERMISSIONS_REVIEW_REQUIRED
3987                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3988                    && bp.isRuntime()) {
3989                return;
3990            }
3991
3992            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3993            sb = (SettingBase) pkg.mExtras;
3994            if (sb == null) {
3995                throw new IllegalArgumentException("Unknown package: " + packageName);
3996            }
3997
3998            final PermissionsState permissionsState = sb.getPermissionsState();
3999
4000            final int flags = permissionsState.getPermissionFlags(name, userId);
4001            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4002                throw new SecurityException("Cannot grant system fixed permission "
4003                        + name + " for package " + packageName);
4004            }
4005
4006            if (bp.isDevelopment()) {
4007                // Development permissions must be handled specially, since they are not
4008                // normal runtime permissions.  For now they apply to all users.
4009                if (permissionsState.grantInstallPermission(bp) !=
4010                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4011                    scheduleWriteSettingsLocked();
4012                }
4013                return;
4014            }
4015
4016            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4017                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4018                return;
4019            }
4020
4021            final int result = permissionsState.grantRuntimePermission(bp, userId);
4022            switch (result) {
4023                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4024                    return;
4025                }
4026
4027                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4028                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4029                    mHandler.post(new Runnable() {
4030                        @Override
4031                        public void run() {
4032                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4033                        }
4034                    });
4035                }
4036                break;
4037            }
4038
4039            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4040
4041            // Not critical if that is lost - app has to request again.
4042            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4043        }
4044
4045        // Only need to do this if user is initialized. Otherwise it's a new user
4046        // and there are no processes running as the user yet and there's no need
4047        // to make an expensive call to remount processes for the changed permissions.
4048        if (READ_EXTERNAL_STORAGE.equals(name)
4049                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4050            final long token = Binder.clearCallingIdentity();
4051            try {
4052                if (sUserManager.isInitialized(userId)) {
4053                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4054                            MountServiceInternal.class);
4055                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4056                }
4057            } finally {
4058                Binder.restoreCallingIdentity(token);
4059            }
4060        }
4061    }
4062
4063    @Override
4064    public void revokeRuntimePermission(String packageName, String name, int userId) {
4065        if (!sUserManager.exists(userId)) {
4066            Log.e(TAG, "No such user:" + userId);
4067            return;
4068        }
4069
4070        mContext.enforceCallingOrSelfPermission(
4071                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4072                "revokeRuntimePermission");
4073
4074        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4075                true /* requireFullPermission */, true /* checkShell */,
4076                "revokeRuntimePermission");
4077
4078        final int appId;
4079
4080        synchronized (mPackages) {
4081            final PackageParser.Package pkg = mPackages.get(packageName);
4082            if (pkg == null) {
4083                throw new IllegalArgumentException("Unknown package: " + packageName);
4084            }
4085
4086            final BasePermission bp = mSettings.mPermissions.get(name);
4087            if (bp == null) {
4088                throw new IllegalArgumentException("Unknown permission: " + name);
4089            }
4090
4091            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4092
4093            // If a permission review is required for legacy apps we represent
4094            // their permissions as always granted runtime ones since we need
4095            // to keep the review required permission flag per user while an
4096            // install permission's state is shared across all users.
4097            if (Build.PERMISSIONS_REVIEW_REQUIRED
4098                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4099                    && bp.isRuntime()) {
4100                return;
4101            }
4102
4103            SettingBase sb = (SettingBase) pkg.mExtras;
4104            if (sb == null) {
4105                throw new IllegalArgumentException("Unknown package: " + packageName);
4106            }
4107
4108            final PermissionsState permissionsState = sb.getPermissionsState();
4109
4110            final int flags = permissionsState.getPermissionFlags(name, userId);
4111            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4112                throw new SecurityException("Cannot revoke system fixed permission "
4113                        + name + " for package " + packageName);
4114            }
4115
4116            if (bp.isDevelopment()) {
4117                // Development permissions must be handled specially, since they are not
4118                // normal runtime permissions.  For now they apply to all users.
4119                if (permissionsState.revokeInstallPermission(bp) !=
4120                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4121                    scheduleWriteSettingsLocked();
4122                }
4123                return;
4124            }
4125
4126            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4127                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4128                return;
4129            }
4130
4131            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4132
4133            // Critical, after this call app should never have the permission.
4134            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4135
4136            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4137        }
4138
4139        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4140    }
4141
4142    @Override
4143    public void resetRuntimePermissions() {
4144        mContext.enforceCallingOrSelfPermission(
4145                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4146                "revokeRuntimePermission");
4147
4148        int callingUid = Binder.getCallingUid();
4149        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4150            mContext.enforceCallingOrSelfPermission(
4151                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4152                    "resetRuntimePermissions");
4153        }
4154
4155        synchronized (mPackages) {
4156            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4157            for (int userId : UserManagerService.getInstance().getUserIds()) {
4158                final int packageCount = mPackages.size();
4159                for (int i = 0; i < packageCount; i++) {
4160                    PackageParser.Package pkg = mPackages.valueAt(i);
4161                    if (!(pkg.mExtras instanceof PackageSetting)) {
4162                        continue;
4163                    }
4164                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4165                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4166                }
4167            }
4168        }
4169    }
4170
4171    @Override
4172    public int getPermissionFlags(String name, String packageName, int userId) {
4173        if (!sUserManager.exists(userId)) {
4174            return 0;
4175        }
4176
4177        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4178
4179        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4180                true /* requireFullPermission */, false /* checkShell */,
4181                "getPermissionFlags");
4182
4183        synchronized (mPackages) {
4184            final PackageParser.Package pkg = mPackages.get(packageName);
4185            if (pkg == null) {
4186                return 0;
4187            }
4188
4189            final BasePermission bp = mSettings.mPermissions.get(name);
4190            if (bp == null) {
4191                return 0;
4192            }
4193
4194            SettingBase sb = (SettingBase) pkg.mExtras;
4195            if (sb == null) {
4196                return 0;
4197            }
4198
4199            PermissionsState permissionsState = sb.getPermissionsState();
4200            return permissionsState.getPermissionFlags(name, userId);
4201        }
4202    }
4203
4204    @Override
4205    public void updatePermissionFlags(String name, String packageName, int flagMask,
4206            int flagValues, int userId) {
4207        if (!sUserManager.exists(userId)) {
4208            return;
4209        }
4210
4211        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4212
4213        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4214                true /* requireFullPermission */, true /* checkShell */,
4215                "updatePermissionFlags");
4216
4217        // Only the system can change these flags and nothing else.
4218        if (getCallingUid() != Process.SYSTEM_UID) {
4219            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4220            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4221            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4222            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4223            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4224        }
4225
4226        synchronized (mPackages) {
4227            final PackageParser.Package pkg = mPackages.get(packageName);
4228            if (pkg == null) {
4229                throw new IllegalArgumentException("Unknown package: " + packageName);
4230            }
4231
4232            final BasePermission bp = mSettings.mPermissions.get(name);
4233            if (bp == null) {
4234                throw new IllegalArgumentException("Unknown permission: " + name);
4235            }
4236
4237            SettingBase sb = (SettingBase) pkg.mExtras;
4238            if (sb == null) {
4239                throw new IllegalArgumentException("Unknown package: " + packageName);
4240            }
4241
4242            PermissionsState permissionsState = sb.getPermissionsState();
4243
4244            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4245
4246            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4247                // Install and runtime permissions are stored in different places,
4248                // so figure out what permission changed and persist the change.
4249                if (permissionsState.getInstallPermissionState(name) != null) {
4250                    scheduleWriteSettingsLocked();
4251                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4252                        || hadState) {
4253                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4254                }
4255            }
4256        }
4257    }
4258
4259    /**
4260     * Update the permission flags for all packages and runtime permissions of a user in order
4261     * to allow device or profile owner to remove POLICY_FIXED.
4262     */
4263    @Override
4264    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4265        if (!sUserManager.exists(userId)) {
4266            return;
4267        }
4268
4269        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4270
4271        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4272                true /* requireFullPermission */, true /* checkShell */,
4273                "updatePermissionFlagsForAllApps");
4274
4275        // Only the system can change system fixed flags.
4276        if (getCallingUid() != Process.SYSTEM_UID) {
4277            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4278            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4279        }
4280
4281        synchronized (mPackages) {
4282            boolean changed = false;
4283            final int packageCount = mPackages.size();
4284            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4285                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4286                SettingBase sb = (SettingBase) pkg.mExtras;
4287                if (sb == null) {
4288                    continue;
4289                }
4290                PermissionsState permissionsState = sb.getPermissionsState();
4291                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4292                        userId, flagMask, flagValues);
4293            }
4294            if (changed) {
4295                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4296            }
4297        }
4298    }
4299
4300    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4301        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4302                != PackageManager.PERMISSION_GRANTED
4303            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4304                != PackageManager.PERMISSION_GRANTED) {
4305            throw new SecurityException(message + " requires "
4306                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4307                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4308        }
4309    }
4310
4311    @Override
4312    public boolean shouldShowRequestPermissionRationale(String permissionName,
4313            String packageName, int userId) {
4314        if (UserHandle.getCallingUserId() != userId) {
4315            mContext.enforceCallingPermission(
4316                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4317                    "canShowRequestPermissionRationale for user " + userId);
4318        }
4319
4320        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4321        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4322            return false;
4323        }
4324
4325        if (checkPermission(permissionName, packageName, userId)
4326                == PackageManager.PERMISSION_GRANTED) {
4327            return false;
4328        }
4329
4330        final int flags;
4331
4332        final long identity = Binder.clearCallingIdentity();
4333        try {
4334            flags = getPermissionFlags(permissionName,
4335                    packageName, userId);
4336        } finally {
4337            Binder.restoreCallingIdentity(identity);
4338        }
4339
4340        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4341                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4342                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4343
4344        if ((flags & fixedFlags) != 0) {
4345            return false;
4346        }
4347
4348        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4349    }
4350
4351    @Override
4352    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4353        mContext.enforceCallingOrSelfPermission(
4354                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4355                "addOnPermissionsChangeListener");
4356
4357        synchronized (mPackages) {
4358            mOnPermissionChangeListeners.addListenerLocked(listener);
4359        }
4360    }
4361
4362    @Override
4363    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4364        synchronized (mPackages) {
4365            mOnPermissionChangeListeners.removeListenerLocked(listener);
4366        }
4367    }
4368
4369    @Override
4370    public boolean isProtectedBroadcast(String actionName) {
4371        synchronized (mPackages) {
4372            if (mProtectedBroadcasts.contains(actionName)) {
4373                return true;
4374            } else if (actionName != null) {
4375                // TODO: remove these terrible hacks
4376                if (actionName.startsWith("android.net.netmon.lingerExpired")
4377                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4378                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4379                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4380                    return true;
4381                }
4382            }
4383        }
4384        return false;
4385    }
4386
4387    @Override
4388    public int checkSignatures(String pkg1, String pkg2) {
4389        synchronized (mPackages) {
4390            final PackageParser.Package p1 = mPackages.get(pkg1);
4391            final PackageParser.Package p2 = mPackages.get(pkg2);
4392            if (p1 == null || p1.mExtras == null
4393                    || p2 == null || p2.mExtras == null) {
4394                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4395            }
4396            return compareSignatures(p1.mSignatures, p2.mSignatures);
4397        }
4398    }
4399
4400    @Override
4401    public int checkUidSignatures(int uid1, int uid2) {
4402        // Map to base uids.
4403        uid1 = UserHandle.getAppId(uid1);
4404        uid2 = UserHandle.getAppId(uid2);
4405        // reader
4406        synchronized (mPackages) {
4407            Signature[] s1;
4408            Signature[] s2;
4409            Object obj = mSettings.getUserIdLPr(uid1);
4410            if (obj != null) {
4411                if (obj instanceof SharedUserSetting) {
4412                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4413                } else if (obj instanceof PackageSetting) {
4414                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4415                } else {
4416                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4417                }
4418            } else {
4419                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4420            }
4421            obj = mSettings.getUserIdLPr(uid2);
4422            if (obj != null) {
4423                if (obj instanceof SharedUserSetting) {
4424                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4425                } else if (obj instanceof PackageSetting) {
4426                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4427                } else {
4428                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4429                }
4430            } else {
4431                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4432            }
4433            return compareSignatures(s1, s2);
4434        }
4435    }
4436
4437    /**
4438     * This method should typically only be used when granting or revoking
4439     * permissions, since the app may immediately restart after this call.
4440     * <p>
4441     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4442     * guard your work against the app being relaunched.
4443     */
4444    private void killUid(int appId, int userId, String reason) {
4445        final long identity = Binder.clearCallingIdentity();
4446        try {
4447            IActivityManager am = ActivityManagerNative.getDefault();
4448            if (am != null) {
4449                try {
4450                    am.killUid(appId, userId, reason);
4451                } catch (RemoteException e) {
4452                    /* ignore - same process */
4453                }
4454            }
4455        } finally {
4456            Binder.restoreCallingIdentity(identity);
4457        }
4458    }
4459
4460    /**
4461     * Compares two sets of signatures. Returns:
4462     * <br />
4463     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4464     * <br />
4465     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4466     * <br />
4467     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4468     * <br />
4469     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4470     * <br />
4471     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4472     */
4473    static int compareSignatures(Signature[] s1, Signature[] s2) {
4474        if (s1 == null) {
4475            return s2 == null
4476                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4477                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4478        }
4479
4480        if (s2 == null) {
4481            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4482        }
4483
4484        if (s1.length != s2.length) {
4485            return PackageManager.SIGNATURE_NO_MATCH;
4486        }
4487
4488        // Since both signature sets are of size 1, we can compare without HashSets.
4489        if (s1.length == 1) {
4490            return s1[0].equals(s2[0]) ?
4491                    PackageManager.SIGNATURE_MATCH :
4492                    PackageManager.SIGNATURE_NO_MATCH;
4493        }
4494
4495        ArraySet<Signature> set1 = new ArraySet<Signature>();
4496        for (Signature sig : s1) {
4497            set1.add(sig);
4498        }
4499        ArraySet<Signature> set2 = new ArraySet<Signature>();
4500        for (Signature sig : s2) {
4501            set2.add(sig);
4502        }
4503        // Make sure s2 contains all signatures in s1.
4504        if (set1.equals(set2)) {
4505            return PackageManager.SIGNATURE_MATCH;
4506        }
4507        return PackageManager.SIGNATURE_NO_MATCH;
4508    }
4509
4510    /**
4511     * If the database version for this type of package (internal storage or
4512     * external storage) is less than the version where package signatures
4513     * were updated, return true.
4514     */
4515    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4516        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4517        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4518    }
4519
4520    /**
4521     * Used for backward compatibility to make sure any packages with
4522     * certificate chains get upgraded to the new style. {@code existingSigs}
4523     * will be in the old format (since they were stored on disk from before the
4524     * system upgrade) and {@code scannedSigs} will be in the newer format.
4525     */
4526    private int compareSignaturesCompat(PackageSignatures existingSigs,
4527            PackageParser.Package scannedPkg) {
4528        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4529            return PackageManager.SIGNATURE_NO_MATCH;
4530        }
4531
4532        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4533        for (Signature sig : existingSigs.mSignatures) {
4534            existingSet.add(sig);
4535        }
4536        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4537        for (Signature sig : scannedPkg.mSignatures) {
4538            try {
4539                Signature[] chainSignatures = sig.getChainSignatures();
4540                for (Signature chainSig : chainSignatures) {
4541                    scannedCompatSet.add(chainSig);
4542                }
4543            } catch (CertificateEncodingException e) {
4544                scannedCompatSet.add(sig);
4545            }
4546        }
4547        /*
4548         * Make sure the expanded scanned set contains all signatures in the
4549         * existing one.
4550         */
4551        if (scannedCompatSet.equals(existingSet)) {
4552            // Migrate the old signatures to the new scheme.
4553            existingSigs.assignSignatures(scannedPkg.mSignatures);
4554            // The new KeySets will be re-added later in the scanning process.
4555            synchronized (mPackages) {
4556                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4557            }
4558            return PackageManager.SIGNATURE_MATCH;
4559        }
4560        return PackageManager.SIGNATURE_NO_MATCH;
4561    }
4562
4563    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4564        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4565        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4566    }
4567
4568    private int compareSignaturesRecover(PackageSignatures existingSigs,
4569            PackageParser.Package scannedPkg) {
4570        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4571            return PackageManager.SIGNATURE_NO_MATCH;
4572        }
4573
4574        String msg = null;
4575        try {
4576            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4577                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4578                        + scannedPkg.packageName);
4579                return PackageManager.SIGNATURE_MATCH;
4580            }
4581        } catch (CertificateException e) {
4582            msg = e.getMessage();
4583        }
4584
4585        logCriticalInfo(Log.INFO,
4586                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4587        return PackageManager.SIGNATURE_NO_MATCH;
4588    }
4589
4590    @Override
4591    public List<String> getAllPackages() {
4592        synchronized (mPackages) {
4593            return new ArrayList<String>(mPackages.keySet());
4594        }
4595    }
4596
4597    @Override
4598    public String[] getPackagesForUid(int uid) {
4599        uid = UserHandle.getAppId(uid);
4600        // reader
4601        synchronized (mPackages) {
4602            Object obj = mSettings.getUserIdLPr(uid);
4603            if (obj instanceof SharedUserSetting) {
4604                final SharedUserSetting sus = (SharedUserSetting) obj;
4605                final int N = sus.packages.size();
4606                final String[] res = new String[N];
4607                for (int i = 0; i < N; i++) {
4608                    res[i] = sus.packages.valueAt(i).name;
4609                }
4610                return res;
4611            } else if (obj instanceof PackageSetting) {
4612                final PackageSetting ps = (PackageSetting) obj;
4613                return new String[] { ps.name };
4614            }
4615        }
4616        return null;
4617    }
4618
4619    @Override
4620    public String getNameForUid(int uid) {
4621        // reader
4622        synchronized (mPackages) {
4623            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4624            if (obj instanceof SharedUserSetting) {
4625                final SharedUserSetting sus = (SharedUserSetting) obj;
4626                return sus.name + ":" + sus.userId;
4627            } else if (obj instanceof PackageSetting) {
4628                final PackageSetting ps = (PackageSetting) obj;
4629                return ps.name;
4630            }
4631        }
4632        return null;
4633    }
4634
4635    @Override
4636    public int getUidForSharedUser(String sharedUserName) {
4637        if(sharedUserName == null) {
4638            return -1;
4639        }
4640        // reader
4641        synchronized (mPackages) {
4642            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4643            if (suid == null) {
4644                return -1;
4645            }
4646            return suid.userId;
4647        }
4648    }
4649
4650    @Override
4651    public int getFlagsForUid(int uid) {
4652        synchronized (mPackages) {
4653            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4654            if (obj instanceof SharedUserSetting) {
4655                final SharedUserSetting sus = (SharedUserSetting) obj;
4656                return sus.pkgFlags;
4657            } else if (obj instanceof PackageSetting) {
4658                final PackageSetting ps = (PackageSetting) obj;
4659                return ps.pkgFlags;
4660            }
4661        }
4662        return 0;
4663    }
4664
4665    @Override
4666    public int getPrivateFlagsForUid(int uid) {
4667        synchronized (mPackages) {
4668            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4669            if (obj instanceof SharedUserSetting) {
4670                final SharedUserSetting sus = (SharedUserSetting) obj;
4671                return sus.pkgPrivateFlags;
4672            } else if (obj instanceof PackageSetting) {
4673                final PackageSetting ps = (PackageSetting) obj;
4674                return ps.pkgPrivateFlags;
4675            }
4676        }
4677        return 0;
4678    }
4679
4680    @Override
4681    public boolean isUidPrivileged(int uid) {
4682        uid = UserHandle.getAppId(uid);
4683        // reader
4684        synchronized (mPackages) {
4685            Object obj = mSettings.getUserIdLPr(uid);
4686            if (obj instanceof SharedUserSetting) {
4687                final SharedUserSetting sus = (SharedUserSetting) obj;
4688                final Iterator<PackageSetting> it = sus.packages.iterator();
4689                while (it.hasNext()) {
4690                    if (it.next().isPrivileged()) {
4691                        return true;
4692                    }
4693                }
4694            } else if (obj instanceof PackageSetting) {
4695                final PackageSetting ps = (PackageSetting) obj;
4696                return ps.isPrivileged();
4697            }
4698        }
4699        return false;
4700    }
4701
4702    @Override
4703    public String[] getAppOpPermissionPackages(String permissionName) {
4704        synchronized (mPackages) {
4705            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4706            if (pkgs == null) {
4707                return null;
4708            }
4709            return pkgs.toArray(new String[pkgs.size()]);
4710        }
4711    }
4712
4713    @Override
4714    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4715            int flags, int userId) {
4716        try {
4717            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4718
4719            if (!sUserManager.exists(userId)) return null;
4720            flags = updateFlagsForResolve(flags, userId, intent);
4721            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4722                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4723
4724            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4725            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4726                    flags, userId);
4727            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4728
4729            final ResolveInfo bestChoice =
4730                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4731            return bestChoice;
4732        } finally {
4733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4734        }
4735    }
4736
4737    @Override
4738    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4739            IntentFilter filter, int match, ComponentName activity) {
4740        final int userId = UserHandle.getCallingUserId();
4741        if (DEBUG_PREFERRED) {
4742            Log.v(TAG, "setLastChosenActivity intent=" + intent
4743                + " resolvedType=" + resolvedType
4744                + " flags=" + flags
4745                + " filter=" + filter
4746                + " match=" + match
4747                + " activity=" + activity);
4748            filter.dump(new PrintStreamPrinter(System.out), "    ");
4749        }
4750        intent.setComponent(null);
4751        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4752                userId);
4753        // Find any earlier preferred or last chosen entries and nuke them
4754        findPreferredActivity(intent, resolvedType,
4755                flags, query, 0, false, true, false, userId);
4756        // Add the new activity as the last chosen for this filter
4757        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4758                "Setting last chosen");
4759    }
4760
4761    @Override
4762    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4763        final int userId = UserHandle.getCallingUserId();
4764        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4765        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4766                userId);
4767        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4768                false, false, false, userId);
4769    }
4770
4771    private boolean isEphemeralAllowed(
4772            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4773            boolean skipPackageCheck) {
4774        // Short circuit and return early if possible.
4775        if (DISABLE_EPHEMERAL_APPS) {
4776            return false;
4777        }
4778        final int callingUser = UserHandle.getCallingUserId();
4779        if (callingUser != UserHandle.USER_SYSTEM) {
4780            return false;
4781        }
4782        if (mEphemeralResolverConnection == null) {
4783            return false;
4784        }
4785        if (intent.getComponent() != null) {
4786            return false;
4787        }
4788        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4789            return false;
4790        }
4791        if (!skipPackageCheck && intent.getPackage() != null) {
4792            return false;
4793        }
4794        final boolean isWebUri = hasWebURI(intent);
4795        if (!isWebUri || intent.getData().getHost() == null) {
4796            return false;
4797        }
4798        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4799        synchronized (mPackages) {
4800            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4801            for (int n = 0; n < count; n++) {
4802                ResolveInfo info = resolvedActivities.get(n);
4803                String packageName = info.activityInfo.packageName;
4804                PackageSetting ps = mSettings.mPackages.get(packageName);
4805                if (ps != null) {
4806                    // Try to get the status from User settings first
4807                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4808                    int status = (int) (packedStatus >> 32);
4809                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4810                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4811                        if (DEBUG_EPHEMERAL) {
4812                            Slog.v(TAG, "DENY ephemeral apps;"
4813                                + " pkg: " + packageName + ", status: " + status);
4814                        }
4815                        return false;
4816                    }
4817                }
4818            }
4819        }
4820        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4821        return true;
4822    }
4823
4824    private static EphemeralResolveInfo getEphemeralResolveInfo(
4825            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4826            String resolvedType, int userId, String packageName) {
4827        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4828                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4829        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4830                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4831        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4832                ephemeralPrefixCount);
4833        final int[] shaPrefix = digest.getDigestPrefix();
4834        final byte[][] digestBytes = digest.getDigestBytes();
4835        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4836                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4837        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4838            // No hash prefix match; there are no ephemeral apps for this domain.
4839            return null;
4840        }
4841
4842        // Go in reverse order so we match the narrowest scope first.
4843        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4844            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4845                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4846                    continue;
4847                }
4848                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4849                // No filters; this should never happen.
4850                if (filters.isEmpty()) {
4851                    continue;
4852                }
4853                if (packageName != null
4854                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4855                    continue;
4856                }
4857                // We have a domain match; resolve the filters to see if anything matches.
4858                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4859                for (int j = filters.size() - 1; j >= 0; --j) {
4860                    final EphemeralResolveIntentInfo intentInfo =
4861                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4862                    ephemeralResolver.addFilter(intentInfo);
4863                }
4864                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4865                        intent, resolvedType, false /*defaultOnly*/, userId);
4866                if (!matchedResolveInfoList.isEmpty()) {
4867                    return matchedResolveInfoList.get(0);
4868                }
4869            }
4870        }
4871        // Hash or filter mis-match; no ephemeral apps for this domain.
4872        return null;
4873    }
4874
4875    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4876            int flags, List<ResolveInfo> query, int userId) {
4877        if (query != null) {
4878            final int N = query.size();
4879            if (N == 1) {
4880                return query.get(0);
4881            } else if (N > 1) {
4882                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4883                // If there is more than one activity with the same priority,
4884                // then let the user decide between them.
4885                ResolveInfo r0 = query.get(0);
4886                ResolveInfo r1 = query.get(1);
4887                if (DEBUG_INTENT_MATCHING || debug) {
4888                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4889                            + r1.activityInfo.name + "=" + r1.priority);
4890                }
4891                // If the first activity has a higher priority, or a different
4892                // default, then it is always desirable to pick it.
4893                if (r0.priority != r1.priority
4894                        || r0.preferredOrder != r1.preferredOrder
4895                        || r0.isDefault != r1.isDefault) {
4896                    return query.get(0);
4897                }
4898                // If we have saved a preference for a preferred activity for
4899                // this Intent, use that.
4900                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4901                        flags, query, r0.priority, true, false, debug, userId);
4902                if (ri != null) {
4903                    return ri;
4904                }
4905                ri = new ResolveInfo(mResolveInfo);
4906                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4907                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4908                // If all of the options come from the same package, show the application's
4909                // label and icon instead of the generic resolver's.
4910                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4911                // and then throw away the ResolveInfo itself, meaning that the caller loses
4912                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4913                // a fallback for this case; we only set the target package's resources on
4914                // the ResolveInfo, not the ActivityInfo.
4915                final String intentPackage = intent.getPackage();
4916                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4917                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4918                    ri.resolvePackageName = intentPackage;
4919                    if (userNeedsBadging(userId)) {
4920                        ri.noResourceId = true;
4921                    } else {
4922                        ri.icon = appi.icon;
4923                    }
4924                    ri.iconResourceId = appi.icon;
4925                    ri.labelRes = appi.labelRes;
4926                }
4927                ri.activityInfo.applicationInfo = new ApplicationInfo(
4928                        ri.activityInfo.applicationInfo);
4929                if (userId != 0) {
4930                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4931                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4932                }
4933                // Make sure that the resolver is displayable in car mode
4934                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4935                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4936                return ri;
4937            }
4938        }
4939        return null;
4940    }
4941
4942    /**
4943     * Return true if the given list is not empty and all of its contents have
4944     * an activityInfo with the given package name.
4945     */
4946    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4947        if (ArrayUtils.isEmpty(list)) {
4948            return false;
4949        }
4950        for (int i = 0, N = list.size(); i < N; i++) {
4951            final ResolveInfo ri = list.get(i);
4952            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4953            if (ai == null || !packageName.equals(ai.packageName)) {
4954                return false;
4955            }
4956        }
4957        return true;
4958    }
4959
4960    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4961            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4962        final int N = query.size();
4963        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4964                .get(userId);
4965        // Get the list of persistent preferred activities that handle the intent
4966        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4967        List<PersistentPreferredActivity> pprefs = ppir != null
4968                ? ppir.queryIntent(intent, resolvedType,
4969                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4970                : null;
4971        if (pprefs != null && pprefs.size() > 0) {
4972            final int M = pprefs.size();
4973            for (int i=0; i<M; i++) {
4974                final PersistentPreferredActivity ppa = pprefs.get(i);
4975                if (DEBUG_PREFERRED || debug) {
4976                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4977                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4978                            + "\n  component=" + ppa.mComponent);
4979                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4980                }
4981                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4982                        flags | MATCH_DISABLED_COMPONENTS, userId);
4983                if (DEBUG_PREFERRED || debug) {
4984                    Slog.v(TAG, "Found persistent preferred activity:");
4985                    if (ai != null) {
4986                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4987                    } else {
4988                        Slog.v(TAG, "  null");
4989                    }
4990                }
4991                if (ai == null) {
4992                    // This previously registered persistent preferred activity
4993                    // component is no longer known. Ignore it and do NOT remove it.
4994                    continue;
4995                }
4996                for (int j=0; j<N; j++) {
4997                    final ResolveInfo ri = query.get(j);
4998                    if (!ri.activityInfo.applicationInfo.packageName
4999                            .equals(ai.applicationInfo.packageName)) {
5000                        continue;
5001                    }
5002                    if (!ri.activityInfo.name.equals(ai.name)) {
5003                        continue;
5004                    }
5005                    //  Found a persistent preference that can handle the intent.
5006                    if (DEBUG_PREFERRED || debug) {
5007                        Slog.v(TAG, "Returning persistent preferred activity: " +
5008                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5009                    }
5010                    return ri;
5011                }
5012            }
5013        }
5014        return null;
5015    }
5016
5017    // TODO: handle preferred activities missing while user has amnesia
5018    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5019            List<ResolveInfo> query, int priority, boolean always,
5020            boolean removeMatches, boolean debug, int userId) {
5021        if (!sUserManager.exists(userId)) return null;
5022        flags = updateFlagsForResolve(flags, userId, intent);
5023        // writer
5024        synchronized (mPackages) {
5025            if (intent.getSelector() != null) {
5026                intent = intent.getSelector();
5027            }
5028            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5029
5030            // Try to find a matching persistent preferred activity.
5031            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5032                    debug, userId);
5033
5034            // If a persistent preferred activity matched, use it.
5035            if (pri != null) {
5036                return pri;
5037            }
5038
5039            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5040            // Get the list of preferred activities that handle the intent
5041            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5042            List<PreferredActivity> prefs = pir != null
5043                    ? pir.queryIntent(intent, resolvedType,
5044                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5045                    : null;
5046            if (prefs != null && prefs.size() > 0) {
5047                boolean changed = false;
5048                try {
5049                    // First figure out how good the original match set is.
5050                    // We will only allow preferred activities that came
5051                    // from the same match quality.
5052                    int match = 0;
5053
5054                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5055
5056                    final int N = query.size();
5057                    for (int j=0; j<N; j++) {
5058                        final ResolveInfo ri = query.get(j);
5059                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5060                                + ": 0x" + Integer.toHexString(match));
5061                        if (ri.match > match) {
5062                            match = ri.match;
5063                        }
5064                    }
5065
5066                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5067                            + Integer.toHexString(match));
5068
5069                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5070                    final int M = prefs.size();
5071                    for (int i=0; i<M; i++) {
5072                        final PreferredActivity pa = prefs.get(i);
5073                        if (DEBUG_PREFERRED || debug) {
5074                            Slog.v(TAG, "Checking PreferredActivity ds="
5075                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5076                                    + "\n  component=" + pa.mPref.mComponent);
5077                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5078                        }
5079                        if (pa.mPref.mMatch != match) {
5080                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5081                                    + Integer.toHexString(pa.mPref.mMatch));
5082                            continue;
5083                        }
5084                        // If it's not an "always" type preferred activity and that's what we're
5085                        // looking for, skip it.
5086                        if (always && !pa.mPref.mAlways) {
5087                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5088                            continue;
5089                        }
5090                        final ActivityInfo ai = getActivityInfo(
5091                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5092                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5093                                userId);
5094                        if (DEBUG_PREFERRED || debug) {
5095                            Slog.v(TAG, "Found preferred activity:");
5096                            if (ai != null) {
5097                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5098                            } else {
5099                                Slog.v(TAG, "  null");
5100                            }
5101                        }
5102                        if (ai == null) {
5103                            // This previously registered preferred activity
5104                            // component is no longer known.  Most likely an update
5105                            // to the app was installed and in the new version this
5106                            // component no longer exists.  Clean it up by removing
5107                            // it from the preferred activities list, and skip it.
5108                            Slog.w(TAG, "Removing dangling preferred activity: "
5109                                    + pa.mPref.mComponent);
5110                            pir.removeFilter(pa);
5111                            changed = true;
5112                            continue;
5113                        }
5114                        for (int j=0; j<N; j++) {
5115                            final ResolveInfo ri = query.get(j);
5116                            if (!ri.activityInfo.applicationInfo.packageName
5117                                    .equals(ai.applicationInfo.packageName)) {
5118                                continue;
5119                            }
5120                            if (!ri.activityInfo.name.equals(ai.name)) {
5121                                continue;
5122                            }
5123
5124                            if (removeMatches) {
5125                                pir.removeFilter(pa);
5126                                changed = true;
5127                                if (DEBUG_PREFERRED) {
5128                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5129                                }
5130                                break;
5131                            }
5132
5133                            // Okay we found a previously set preferred or last chosen app.
5134                            // If the result set is different from when this
5135                            // was created, we need to clear it and re-ask the
5136                            // user their preference, if we're looking for an "always" type entry.
5137                            if (always && !pa.mPref.sameSet(query)) {
5138                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5139                                        + intent + " type " + resolvedType);
5140                                if (DEBUG_PREFERRED) {
5141                                    Slog.v(TAG, "Removing preferred activity since set changed "
5142                                            + pa.mPref.mComponent);
5143                                }
5144                                pir.removeFilter(pa);
5145                                // Re-add the filter as a "last chosen" entry (!always)
5146                                PreferredActivity lastChosen = new PreferredActivity(
5147                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5148                                pir.addFilter(lastChosen);
5149                                changed = true;
5150                                return null;
5151                            }
5152
5153                            // Yay! Either the set matched or we're looking for the last chosen
5154                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5155                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5156                            return ri;
5157                        }
5158                    }
5159                } finally {
5160                    if (changed) {
5161                        if (DEBUG_PREFERRED) {
5162                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5163                        }
5164                        scheduleWritePackageRestrictionsLocked(userId);
5165                    }
5166                }
5167            }
5168        }
5169        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5170        return null;
5171    }
5172
5173    /*
5174     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5175     */
5176    @Override
5177    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5178            int targetUserId) {
5179        mContext.enforceCallingOrSelfPermission(
5180                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5181        List<CrossProfileIntentFilter> matches =
5182                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5183        if (matches != null) {
5184            int size = matches.size();
5185            for (int i = 0; i < size; i++) {
5186                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5187            }
5188        }
5189        if (hasWebURI(intent)) {
5190            // cross-profile app linking works only towards the parent.
5191            final UserInfo parent = getProfileParent(sourceUserId);
5192            synchronized(mPackages) {
5193                int flags = updateFlagsForResolve(0, parent.id, intent);
5194                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5195                        intent, resolvedType, flags, sourceUserId, parent.id);
5196                return xpDomainInfo != null;
5197            }
5198        }
5199        return false;
5200    }
5201
5202    private UserInfo getProfileParent(int userId) {
5203        final long identity = Binder.clearCallingIdentity();
5204        try {
5205            return sUserManager.getProfileParent(userId);
5206        } finally {
5207            Binder.restoreCallingIdentity(identity);
5208        }
5209    }
5210
5211    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5212            String resolvedType, int userId) {
5213        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5214        if (resolver != null) {
5215            return resolver.queryIntent(intent, resolvedType, false, userId);
5216        }
5217        return null;
5218    }
5219
5220    @Override
5221    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5222            String resolvedType, int flags, int userId) {
5223        try {
5224            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5225
5226            return new ParceledListSlice<>(
5227                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5228        } finally {
5229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5230        }
5231    }
5232
5233    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5234            String resolvedType, int flags, int userId) {
5235        if (!sUserManager.exists(userId)) return Collections.emptyList();
5236        flags = updateFlagsForResolve(flags, userId, intent);
5237        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5238                false /* requireFullPermission */, false /* checkShell */,
5239                "query intent activities");
5240        ComponentName comp = intent.getComponent();
5241        if (comp == null) {
5242            if (intent.getSelector() != null) {
5243                intent = intent.getSelector();
5244                comp = intent.getComponent();
5245            }
5246        }
5247
5248        if (comp != null) {
5249            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5250            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5251            if (ai != null) {
5252                final ResolveInfo ri = new ResolveInfo();
5253                ri.activityInfo = ai;
5254                list.add(ri);
5255            }
5256            return list;
5257        }
5258
5259        // reader
5260        boolean sortResult = false;
5261        boolean addEphemeral = false;
5262        boolean matchEphemeralPackage = false;
5263        List<ResolveInfo> result;
5264        final String pkgName = intent.getPackage();
5265        synchronized (mPackages) {
5266            if (pkgName == null) {
5267                List<CrossProfileIntentFilter> matchingFilters =
5268                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5269                // Check for results that need to skip the current profile.
5270                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5271                        resolvedType, flags, userId);
5272                if (xpResolveInfo != null) {
5273                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5274                    xpResult.add(xpResolveInfo);
5275                    return filterIfNotSystemUser(xpResult, userId);
5276                }
5277
5278                // Check for results in the current profile.
5279                result = filterIfNotSystemUser(mActivities.queryIntent(
5280                        intent, resolvedType, flags, userId), userId);
5281                addEphemeral =
5282                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5283
5284                // Check for cross profile results.
5285                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5286                xpResolveInfo = queryCrossProfileIntents(
5287                        matchingFilters, intent, resolvedType, flags, userId,
5288                        hasNonNegativePriorityResult);
5289                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5290                    boolean isVisibleToUser = filterIfNotSystemUser(
5291                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5292                    if (isVisibleToUser) {
5293                        result.add(xpResolveInfo);
5294                        sortResult = true;
5295                    }
5296                }
5297                if (hasWebURI(intent)) {
5298                    CrossProfileDomainInfo xpDomainInfo = null;
5299                    final UserInfo parent = getProfileParent(userId);
5300                    if (parent != null) {
5301                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5302                                flags, userId, parent.id);
5303                    }
5304                    if (xpDomainInfo != null) {
5305                        if (xpResolveInfo != null) {
5306                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5307                            // in the result.
5308                            result.remove(xpResolveInfo);
5309                        }
5310                        if (result.size() == 0 && !addEphemeral) {
5311                            result.add(xpDomainInfo.resolveInfo);
5312                            return result;
5313                        }
5314                    }
5315                    if (result.size() > 1 || addEphemeral) {
5316                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5317                                intent, flags, result, xpDomainInfo, userId);
5318                        sortResult = true;
5319                    }
5320                }
5321            } else {
5322                final PackageParser.Package pkg = mPackages.get(pkgName);
5323                if (pkg != null) {
5324                    result = filterIfNotSystemUser(
5325                            mActivities.queryIntentForPackage(
5326                                    intent, resolvedType, flags, pkg.activities, userId),
5327                            userId);
5328                } else {
5329                    // the caller wants to resolve for a particular package; however, there
5330                    // were no installed results, so, try to find an ephemeral result
5331                    addEphemeral = isEphemeralAllowed(
5332                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5333                    matchEphemeralPackage = true;
5334                    result = new ArrayList<ResolveInfo>();
5335                }
5336            }
5337        }
5338        if (addEphemeral) {
5339            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5340            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5341                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5342                    matchEphemeralPackage ? pkgName : null);
5343            if (ai != null) {
5344                if (DEBUG_EPHEMERAL) {
5345                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5346                }
5347                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5348                ephemeralInstaller.ephemeralResolveInfo = ai;
5349                // make sure this resolver is the default
5350                ephemeralInstaller.isDefault = true;
5351                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5352                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5353                // add a non-generic filter
5354                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5355                ephemeralInstaller.filter.addDataPath(
5356                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5357                result.add(ephemeralInstaller);
5358            }
5359            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5360        }
5361        if (sortResult) {
5362            Collections.sort(result, mResolvePrioritySorter);
5363        }
5364        return result;
5365    }
5366
5367    private static class CrossProfileDomainInfo {
5368        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5369        ResolveInfo resolveInfo;
5370        /* Best domain verification status of the activities found in the other profile */
5371        int bestDomainVerificationStatus;
5372    }
5373
5374    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5375            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5376        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5377                sourceUserId)) {
5378            return null;
5379        }
5380        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5381                resolvedType, flags, parentUserId);
5382
5383        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5384            return null;
5385        }
5386        CrossProfileDomainInfo result = null;
5387        int size = resultTargetUser.size();
5388        for (int i = 0; i < size; i++) {
5389            ResolveInfo riTargetUser = resultTargetUser.get(i);
5390            // Intent filter verification is only for filters that specify a host. So don't return
5391            // those that handle all web uris.
5392            if (riTargetUser.handleAllWebDataURI) {
5393                continue;
5394            }
5395            String packageName = riTargetUser.activityInfo.packageName;
5396            PackageSetting ps = mSettings.mPackages.get(packageName);
5397            if (ps == null) {
5398                continue;
5399            }
5400            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5401            int status = (int)(verificationState >> 32);
5402            if (result == null) {
5403                result = new CrossProfileDomainInfo();
5404                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5405                        sourceUserId, parentUserId);
5406                result.bestDomainVerificationStatus = status;
5407            } else {
5408                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5409                        result.bestDomainVerificationStatus);
5410            }
5411        }
5412        // Don't consider matches with status NEVER across profiles.
5413        if (result != null && result.bestDomainVerificationStatus
5414                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5415            return null;
5416        }
5417        return result;
5418    }
5419
5420    /**
5421     * Verification statuses are ordered from the worse to the best, except for
5422     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5423     */
5424    private int bestDomainVerificationStatus(int status1, int status2) {
5425        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5426            return status2;
5427        }
5428        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5429            return status1;
5430        }
5431        return (int) MathUtils.max(status1, status2);
5432    }
5433
5434    private boolean isUserEnabled(int userId) {
5435        long callingId = Binder.clearCallingIdentity();
5436        try {
5437            UserInfo userInfo = sUserManager.getUserInfo(userId);
5438            return userInfo != null && userInfo.isEnabled();
5439        } finally {
5440            Binder.restoreCallingIdentity(callingId);
5441        }
5442    }
5443
5444    /**
5445     * Filter out activities with systemUserOnly flag set, when current user is not System.
5446     *
5447     * @return filtered list
5448     */
5449    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5450        if (userId == UserHandle.USER_SYSTEM) {
5451            return resolveInfos;
5452        }
5453        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5454            ResolveInfo info = resolveInfos.get(i);
5455            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5456                resolveInfos.remove(i);
5457            }
5458        }
5459        return resolveInfos;
5460    }
5461
5462    /**
5463     * @param resolveInfos list of resolve infos in descending priority order
5464     * @return if the list contains a resolve info with non-negative priority
5465     */
5466    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5467        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5468    }
5469
5470    private static boolean hasWebURI(Intent intent) {
5471        if (intent.getData() == null) {
5472            return false;
5473        }
5474        final String scheme = intent.getScheme();
5475        if (TextUtils.isEmpty(scheme)) {
5476            return false;
5477        }
5478        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5479    }
5480
5481    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5482            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5483            int userId) {
5484        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5485
5486        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5487            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5488                    candidates.size());
5489        }
5490
5491        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5492        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5493        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5494        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5495        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5496        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5497
5498        synchronized (mPackages) {
5499            final int count = candidates.size();
5500            // First, try to use linked apps. Partition the candidates into four lists:
5501            // one for the final results, one for the "do not use ever", one for "undefined status"
5502            // and finally one for "browser app type".
5503            for (int n=0; n<count; n++) {
5504                ResolveInfo info = candidates.get(n);
5505                String packageName = info.activityInfo.packageName;
5506                PackageSetting ps = mSettings.mPackages.get(packageName);
5507                if (ps != null) {
5508                    // Add to the special match all list (Browser use case)
5509                    if (info.handleAllWebDataURI) {
5510                        matchAllList.add(info);
5511                        continue;
5512                    }
5513                    // Try to get the status from User settings first
5514                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5515                    int status = (int)(packedStatus >> 32);
5516                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5517                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5518                        if (DEBUG_DOMAIN_VERIFICATION) {
5519                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5520                                    + " : linkgen=" + linkGeneration);
5521                        }
5522                        // Use link-enabled generation as preferredOrder, i.e.
5523                        // prefer newly-enabled over earlier-enabled.
5524                        info.preferredOrder = linkGeneration;
5525                        alwaysList.add(info);
5526                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5527                        if (DEBUG_DOMAIN_VERIFICATION) {
5528                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5529                        }
5530                        neverList.add(info);
5531                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5532                        if (DEBUG_DOMAIN_VERIFICATION) {
5533                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5534                        }
5535                        alwaysAskList.add(info);
5536                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5537                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5538                        if (DEBUG_DOMAIN_VERIFICATION) {
5539                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5540                        }
5541                        undefinedList.add(info);
5542                    }
5543                }
5544            }
5545
5546            // We'll want to include browser possibilities in a few cases
5547            boolean includeBrowser = false;
5548
5549            // First try to add the "always" resolution(s) for the current user, if any
5550            if (alwaysList.size() > 0) {
5551                result.addAll(alwaysList);
5552            } else {
5553                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5554                result.addAll(undefinedList);
5555                // Maybe add one for the other profile.
5556                if (xpDomainInfo != null && (
5557                        xpDomainInfo.bestDomainVerificationStatus
5558                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5559                    result.add(xpDomainInfo.resolveInfo);
5560                }
5561                includeBrowser = true;
5562            }
5563
5564            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5565            // If there were 'always' entries their preferred order has been set, so we also
5566            // back that off to make the alternatives equivalent
5567            if (alwaysAskList.size() > 0) {
5568                for (ResolveInfo i : result) {
5569                    i.preferredOrder = 0;
5570                }
5571                result.addAll(alwaysAskList);
5572                includeBrowser = true;
5573            }
5574
5575            if (includeBrowser) {
5576                // Also add browsers (all of them or only the default one)
5577                if (DEBUG_DOMAIN_VERIFICATION) {
5578                    Slog.v(TAG, "   ...including browsers in candidate set");
5579                }
5580                if ((matchFlags & MATCH_ALL) != 0) {
5581                    result.addAll(matchAllList);
5582                } else {
5583                    // Browser/generic handling case.  If there's a default browser, go straight
5584                    // to that (but only if there is no other higher-priority match).
5585                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5586                    int maxMatchPrio = 0;
5587                    ResolveInfo defaultBrowserMatch = null;
5588                    final int numCandidates = matchAllList.size();
5589                    for (int n = 0; n < numCandidates; n++) {
5590                        ResolveInfo info = matchAllList.get(n);
5591                        // track the highest overall match priority...
5592                        if (info.priority > maxMatchPrio) {
5593                            maxMatchPrio = info.priority;
5594                        }
5595                        // ...and the highest-priority default browser match
5596                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5597                            if (defaultBrowserMatch == null
5598                                    || (defaultBrowserMatch.priority < info.priority)) {
5599                                if (debug) {
5600                                    Slog.v(TAG, "Considering default browser match " + info);
5601                                }
5602                                defaultBrowserMatch = info;
5603                            }
5604                        }
5605                    }
5606                    if (defaultBrowserMatch != null
5607                            && defaultBrowserMatch.priority >= maxMatchPrio
5608                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5609                    {
5610                        if (debug) {
5611                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5612                        }
5613                        result.add(defaultBrowserMatch);
5614                    } else {
5615                        result.addAll(matchAllList);
5616                    }
5617                }
5618
5619                // If there is nothing selected, add all candidates and remove the ones that the user
5620                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5621                if (result.size() == 0) {
5622                    result.addAll(candidates);
5623                    result.removeAll(neverList);
5624                }
5625            }
5626        }
5627        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5628            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5629                    result.size());
5630            for (ResolveInfo info : result) {
5631                Slog.v(TAG, "  + " + info.activityInfo);
5632            }
5633        }
5634        return result;
5635    }
5636
5637    // Returns a packed value as a long:
5638    //
5639    // high 'int'-sized word: link status: undefined/ask/never/always.
5640    // low 'int'-sized word: relative priority among 'always' results.
5641    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5642        long result = ps.getDomainVerificationStatusForUser(userId);
5643        // if none available, get the master status
5644        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5645            if (ps.getIntentFilterVerificationInfo() != null) {
5646                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5647            }
5648        }
5649        return result;
5650    }
5651
5652    private ResolveInfo querySkipCurrentProfileIntents(
5653            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5654            int flags, int sourceUserId) {
5655        if (matchingFilters != null) {
5656            int size = matchingFilters.size();
5657            for (int i = 0; i < size; i ++) {
5658                CrossProfileIntentFilter filter = matchingFilters.get(i);
5659                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5660                    // Checking if there are activities in the target user that can handle the
5661                    // intent.
5662                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5663                            resolvedType, flags, sourceUserId);
5664                    if (resolveInfo != null) {
5665                        return resolveInfo;
5666                    }
5667                }
5668            }
5669        }
5670        return null;
5671    }
5672
5673    // Return matching ResolveInfo in target user if any.
5674    private ResolveInfo queryCrossProfileIntents(
5675            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5676            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5677        if (matchingFilters != null) {
5678            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5679            // match the same intent. For performance reasons, it is better not to
5680            // run queryIntent twice for the same userId
5681            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5682            int size = matchingFilters.size();
5683            for (int i = 0; i < size; i++) {
5684                CrossProfileIntentFilter filter = matchingFilters.get(i);
5685                int targetUserId = filter.getTargetUserId();
5686                boolean skipCurrentProfile =
5687                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5688                boolean skipCurrentProfileIfNoMatchFound =
5689                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5690                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5691                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5692                    // Checking if there are activities in the target user that can handle the
5693                    // intent.
5694                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5695                            resolvedType, flags, sourceUserId);
5696                    if (resolveInfo != null) return resolveInfo;
5697                    alreadyTriedUserIds.put(targetUserId, true);
5698                }
5699            }
5700        }
5701        return null;
5702    }
5703
5704    /**
5705     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5706     * will forward the intent to the filter's target user.
5707     * Otherwise, returns null.
5708     */
5709    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5710            String resolvedType, int flags, int sourceUserId) {
5711        int targetUserId = filter.getTargetUserId();
5712        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5713                resolvedType, flags, targetUserId);
5714        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5715            // If all the matches in the target profile are suspended, return null.
5716            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5717                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5718                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5719                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5720                            targetUserId);
5721                }
5722            }
5723        }
5724        return null;
5725    }
5726
5727    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5728            int sourceUserId, int targetUserId) {
5729        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5730        long ident = Binder.clearCallingIdentity();
5731        boolean targetIsProfile;
5732        try {
5733            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5734        } finally {
5735            Binder.restoreCallingIdentity(ident);
5736        }
5737        String className;
5738        if (targetIsProfile) {
5739            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5740        } else {
5741            className = FORWARD_INTENT_TO_PARENT;
5742        }
5743        ComponentName forwardingActivityComponentName = new ComponentName(
5744                mAndroidApplication.packageName, className);
5745        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5746                sourceUserId);
5747        if (!targetIsProfile) {
5748            forwardingActivityInfo.showUserIcon = targetUserId;
5749            forwardingResolveInfo.noResourceId = true;
5750        }
5751        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5752        forwardingResolveInfo.priority = 0;
5753        forwardingResolveInfo.preferredOrder = 0;
5754        forwardingResolveInfo.match = 0;
5755        forwardingResolveInfo.isDefault = true;
5756        forwardingResolveInfo.filter = filter;
5757        forwardingResolveInfo.targetUserId = targetUserId;
5758        return forwardingResolveInfo;
5759    }
5760
5761    @Override
5762    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5763            Intent[] specifics, String[] specificTypes, Intent intent,
5764            String resolvedType, int flags, int userId) {
5765        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5766                specificTypes, intent, resolvedType, flags, userId));
5767    }
5768
5769    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5770            Intent[] specifics, String[] specificTypes, Intent intent,
5771            String resolvedType, int flags, int userId) {
5772        if (!sUserManager.exists(userId)) return Collections.emptyList();
5773        flags = updateFlagsForResolve(flags, userId, intent);
5774        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5775                false /* requireFullPermission */, false /* checkShell */,
5776                "query intent activity options");
5777        final String resultsAction = intent.getAction();
5778
5779        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5780                | PackageManager.GET_RESOLVED_FILTER, userId);
5781
5782        if (DEBUG_INTENT_MATCHING) {
5783            Log.v(TAG, "Query " + intent + ": " + results);
5784        }
5785
5786        int specificsPos = 0;
5787        int N;
5788
5789        // todo: note that the algorithm used here is O(N^2).  This
5790        // isn't a problem in our current environment, but if we start running
5791        // into situations where we have more than 5 or 10 matches then this
5792        // should probably be changed to something smarter...
5793
5794        // First we go through and resolve each of the specific items
5795        // that were supplied, taking care of removing any corresponding
5796        // duplicate items in the generic resolve list.
5797        if (specifics != null) {
5798            for (int i=0; i<specifics.length; i++) {
5799                final Intent sintent = specifics[i];
5800                if (sintent == null) {
5801                    continue;
5802                }
5803
5804                if (DEBUG_INTENT_MATCHING) {
5805                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5806                }
5807
5808                String action = sintent.getAction();
5809                if (resultsAction != null && resultsAction.equals(action)) {
5810                    // If this action was explicitly requested, then don't
5811                    // remove things that have it.
5812                    action = null;
5813                }
5814
5815                ResolveInfo ri = null;
5816                ActivityInfo ai = null;
5817
5818                ComponentName comp = sintent.getComponent();
5819                if (comp == null) {
5820                    ri = resolveIntent(
5821                        sintent,
5822                        specificTypes != null ? specificTypes[i] : null,
5823                            flags, userId);
5824                    if (ri == null) {
5825                        continue;
5826                    }
5827                    if (ri == mResolveInfo) {
5828                        // ACK!  Must do something better with this.
5829                    }
5830                    ai = ri.activityInfo;
5831                    comp = new ComponentName(ai.applicationInfo.packageName,
5832                            ai.name);
5833                } else {
5834                    ai = getActivityInfo(comp, flags, userId);
5835                    if (ai == null) {
5836                        continue;
5837                    }
5838                }
5839
5840                // Look for any generic query activities that are duplicates
5841                // of this specific one, and remove them from the results.
5842                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5843                N = results.size();
5844                int j;
5845                for (j=specificsPos; j<N; j++) {
5846                    ResolveInfo sri = results.get(j);
5847                    if ((sri.activityInfo.name.equals(comp.getClassName())
5848                            && sri.activityInfo.applicationInfo.packageName.equals(
5849                                    comp.getPackageName()))
5850                        || (action != null && sri.filter.matchAction(action))) {
5851                        results.remove(j);
5852                        if (DEBUG_INTENT_MATCHING) Log.v(
5853                            TAG, "Removing duplicate item from " + j
5854                            + " due to specific " + specificsPos);
5855                        if (ri == null) {
5856                            ri = sri;
5857                        }
5858                        j--;
5859                        N--;
5860                    }
5861                }
5862
5863                // Add this specific item to its proper place.
5864                if (ri == null) {
5865                    ri = new ResolveInfo();
5866                    ri.activityInfo = ai;
5867                }
5868                results.add(specificsPos, ri);
5869                ri.specificIndex = i;
5870                specificsPos++;
5871            }
5872        }
5873
5874        // Now we go through the remaining generic results and remove any
5875        // duplicate actions that are found here.
5876        N = results.size();
5877        for (int i=specificsPos; i<N-1; i++) {
5878            final ResolveInfo rii = results.get(i);
5879            if (rii.filter == null) {
5880                continue;
5881            }
5882
5883            // Iterate over all of the actions of this result's intent
5884            // filter...  typically this should be just one.
5885            final Iterator<String> it = rii.filter.actionsIterator();
5886            if (it == null) {
5887                continue;
5888            }
5889            while (it.hasNext()) {
5890                final String action = it.next();
5891                if (resultsAction != null && resultsAction.equals(action)) {
5892                    // If this action was explicitly requested, then don't
5893                    // remove things that have it.
5894                    continue;
5895                }
5896                for (int j=i+1; j<N; j++) {
5897                    final ResolveInfo rij = results.get(j);
5898                    if (rij.filter != null && rij.filter.hasAction(action)) {
5899                        results.remove(j);
5900                        if (DEBUG_INTENT_MATCHING) Log.v(
5901                            TAG, "Removing duplicate item from " + j
5902                            + " due to action " + action + " at " + i);
5903                        j--;
5904                        N--;
5905                    }
5906                }
5907            }
5908
5909            // If the caller didn't request filter information, drop it now
5910            // so we don't have to marshall/unmarshall it.
5911            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5912                rii.filter = null;
5913            }
5914        }
5915
5916        // Filter out the caller activity if so requested.
5917        if (caller != null) {
5918            N = results.size();
5919            for (int i=0; i<N; i++) {
5920                ActivityInfo ainfo = results.get(i).activityInfo;
5921                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5922                        && caller.getClassName().equals(ainfo.name)) {
5923                    results.remove(i);
5924                    break;
5925                }
5926            }
5927        }
5928
5929        // If the caller didn't request filter information,
5930        // drop them now so we don't have to
5931        // marshall/unmarshall it.
5932        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5933            N = results.size();
5934            for (int i=0; i<N; i++) {
5935                results.get(i).filter = null;
5936            }
5937        }
5938
5939        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5940        return results;
5941    }
5942
5943    @Override
5944    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5945            String resolvedType, int flags, int userId) {
5946        return new ParceledListSlice<>(
5947                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5948    }
5949
5950    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5951            String resolvedType, int flags, int userId) {
5952        if (!sUserManager.exists(userId)) return Collections.emptyList();
5953        flags = updateFlagsForResolve(flags, userId, intent);
5954        ComponentName comp = intent.getComponent();
5955        if (comp == null) {
5956            if (intent.getSelector() != null) {
5957                intent = intent.getSelector();
5958                comp = intent.getComponent();
5959            }
5960        }
5961        if (comp != null) {
5962            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5963            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5964            if (ai != null) {
5965                ResolveInfo ri = new ResolveInfo();
5966                ri.activityInfo = ai;
5967                list.add(ri);
5968            }
5969            return list;
5970        }
5971
5972        // reader
5973        synchronized (mPackages) {
5974            String pkgName = intent.getPackage();
5975            if (pkgName == null) {
5976                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5977            }
5978            final PackageParser.Package pkg = mPackages.get(pkgName);
5979            if (pkg != null) {
5980                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5981                        userId);
5982            }
5983            return Collections.emptyList();
5984        }
5985    }
5986
5987    @Override
5988    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5989        if (!sUserManager.exists(userId)) return null;
5990        flags = updateFlagsForResolve(flags, userId, intent);
5991        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5992        if (query != null) {
5993            if (query.size() >= 1) {
5994                // If there is more than one service with the same priority,
5995                // just arbitrarily pick the first one.
5996                return query.get(0);
5997            }
5998        }
5999        return null;
6000    }
6001
6002    @Override
6003    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6004            String resolvedType, int flags, int userId) {
6005        return new ParceledListSlice<>(
6006                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6007    }
6008
6009    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6010            String resolvedType, int flags, int userId) {
6011        if (!sUserManager.exists(userId)) return Collections.emptyList();
6012        flags = updateFlagsForResolve(flags, userId, intent);
6013        ComponentName comp = intent.getComponent();
6014        if (comp == null) {
6015            if (intent.getSelector() != null) {
6016                intent = intent.getSelector();
6017                comp = intent.getComponent();
6018            }
6019        }
6020        if (comp != null) {
6021            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6022            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6023            if (si != null) {
6024                final ResolveInfo ri = new ResolveInfo();
6025                ri.serviceInfo = si;
6026                list.add(ri);
6027            }
6028            return list;
6029        }
6030
6031        // reader
6032        synchronized (mPackages) {
6033            String pkgName = intent.getPackage();
6034            if (pkgName == null) {
6035                return mServices.queryIntent(intent, resolvedType, flags, userId);
6036            }
6037            final PackageParser.Package pkg = mPackages.get(pkgName);
6038            if (pkg != null) {
6039                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6040                        userId);
6041            }
6042            return Collections.emptyList();
6043        }
6044    }
6045
6046    @Override
6047    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6048            String resolvedType, int flags, int userId) {
6049        return new ParceledListSlice<>(
6050                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6051    }
6052
6053    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6054            Intent intent, String resolvedType, int flags, int userId) {
6055        if (!sUserManager.exists(userId)) return Collections.emptyList();
6056        flags = updateFlagsForResolve(flags, userId, intent);
6057        ComponentName comp = intent.getComponent();
6058        if (comp == null) {
6059            if (intent.getSelector() != null) {
6060                intent = intent.getSelector();
6061                comp = intent.getComponent();
6062            }
6063        }
6064        if (comp != null) {
6065            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6066            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6067            if (pi != null) {
6068                final ResolveInfo ri = new ResolveInfo();
6069                ri.providerInfo = pi;
6070                list.add(ri);
6071            }
6072            return list;
6073        }
6074
6075        // reader
6076        synchronized (mPackages) {
6077            String pkgName = intent.getPackage();
6078            if (pkgName == null) {
6079                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6080            }
6081            final PackageParser.Package pkg = mPackages.get(pkgName);
6082            if (pkg != null) {
6083                return mProviders.queryIntentForPackage(
6084                        intent, resolvedType, flags, pkg.providers, userId);
6085            }
6086            return Collections.emptyList();
6087        }
6088    }
6089
6090    @Override
6091    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6092        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6093        flags = updateFlagsForPackage(flags, userId, null);
6094        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6095        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6096                true /* requireFullPermission */, false /* checkShell */,
6097                "get installed packages");
6098
6099        // writer
6100        synchronized (mPackages) {
6101            ArrayList<PackageInfo> list;
6102            if (listUninstalled) {
6103                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6104                for (PackageSetting ps : mSettings.mPackages.values()) {
6105                    final PackageInfo pi;
6106                    if (ps.pkg != null) {
6107                        pi = generatePackageInfo(ps, flags, userId);
6108                    } else {
6109                        pi = generatePackageInfo(ps, flags, userId);
6110                    }
6111                    if (pi != null) {
6112                        list.add(pi);
6113                    }
6114                }
6115            } else {
6116                list = new ArrayList<PackageInfo>(mPackages.size());
6117                for (PackageParser.Package p : mPackages.values()) {
6118                    final PackageInfo pi =
6119                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6120                    if (pi != null) {
6121                        list.add(pi);
6122                    }
6123                }
6124            }
6125
6126            return new ParceledListSlice<PackageInfo>(list);
6127        }
6128    }
6129
6130    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6131            String[] permissions, boolean[] tmp, int flags, int userId) {
6132        int numMatch = 0;
6133        final PermissionsState permissionsState = ps.getPermissionsState();
6134        for (int i=0; i<permissions.length; i++) {
6135            final String permission = permissions[i];
6136            if (permissionsState.hasPermission(permission, userId)) {
6137                tmp[i] = true;
6138                numMatch++;
6139            } else {
6140                tmp[i] = false;
6141            }
6142        }
6143        if (numMatch == 0) {
6144            return;
6145        }
6146        final PackageInfo pi;
6147        if (ps.pkg != null) {
6148            pi = generatePackageInfo(ps, flags, userId);
6149        } else {
6150            pi = generatePackageInfo(ps, flags, userId);
6151        }
6152        // The above might return null in cases of uninstalled apps or install-state
6153        // skew across users/profiles.
6154        if (pi != null) {
6155            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6156                if (numMatch == permissions.length) {
6157                    pi.requestedPermissions = permissions;
6158                } else {
6159                    pi.requestedPermissions = new String[numMatch];
6160                    numMatch = 0;
6161                    for (int i=0; i<permissions.length; i++) {
6162                        if (tmp[i]) {
6163                            pi.requestedPermissions[numMatch] = permissions[i];
6164                            numMatch++;
6165                        }
6166                    }
6167                }
6168            }
6169            list.add(pi);
6170        }
6171    }
6172
6173    @Override
6174    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6175            String[] permissions, int flags, int userId) {
6176        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6177        flags = updateFlagsForPackage(flags, userId, permissions);
6178        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6179
6180        // writer
6181        synchronized (mPackages) {
6182            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6183            boolean[] tmpBools = new boolean[permissions.length];
6184            if (listUninstalled) {
6185                for (PackageSetting ps : mSettings.mPackages.values()) {
6186                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6187                }
6188            } else {
6189                for (PackageParser.Package pkg : mPackages.values()) {
6190                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6191                    if (ps != null) {
6192                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6193                                userId);
6194                    }
6195                }
6196            }
6197
6198            return new ParceledListSlice<PackageInfo>(list);
6199        }
6200    }
6201
6202    @Override
6203    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6204        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6205        flags = updateFlagsForApplication(flags, userId, null);
6206        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6207
6208        // writer
6209        synchronized (mPackages) {
6210            ArrayList<ApplicationInfo> list;
6211            if (listUninstalled) {
6212                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6213                for (PackageSetting ps : mSettings.mPackages.values()) {
6214                    ApplicationInfo ai;
6215                    if (ps.pkg != null) {
6216                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6217                                ps.readUserState(userId), userId);
6218                    } else {
6219                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6220                    }
6221                    if (ai != null) {
6222                        list.add(ai);
6223                    }
6224                }
6225            } else {
6226                list = new ArrayList<ApplicationInfo>(mPackages.size());
6227                for (PackageParser.Package p : mPackages.values()) {
6228                    if (p.mExtras != null) {
6229                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6230                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6231                        if (ai != null) {
6232                            list.add(ai);
6233                        }
6234                    }
6235                }
6236            }
6237
6238            return new ParceledListSlice<ApplicationInfo>(list);
6239        }
6240    }
6241
6242    @Override
6243    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6244        if (DISABLE_EPHEMERAL_APPS) {
6245            return null;
6246        }
6247
6248        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6249                "getEphemeralApplications");
6250        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6251                true /* requireFullPermission */, false /* checkShell */,
6252                "getEphemeralApplications");
6253        synchronized (mPackages) {
6254            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6255                    .getEphemeralApplicationsLPw(userId);
6256            if (ephemeralApps != null) {
6257                return new ParceledListSlice<>(ephemeralApps);
6258            }
6259        }
6260        return null;
6261    }
6262
6263    @Override
6264    public boolean isEphemeralApplication(String packageName, int userId) {
6265        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6266                true /* requireFullPermission */, false /* checkShell */,
6267                "isEphemeral");
6268        if (DISABLE_EPHEMERAL_APPS) {
6269            return false;
6270        }
6271
6272        if (!isCallerSameApp(packageName)) {
6273            return false;
6274        }
6275        synchronized (mPackages) {
6276            PackageParser.Package pkg = mPackages.get(packageName);
6277            if (pkg != null) {
6278                return pkg.applicationInfo.isEphemeralApp();
6279            }
6280        }
6281        return false;
6282    }
6283
6284    @Override
6285    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6286        if (DISABLE_EPHEMERAL_APPS) {
6287            return null;
6288        }
6289
6290        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6291                true /* requireFullPermission */, false /* checkShell */,
6292                "getCookie");
6293        if (!isCallerSameApp(packageName)) {
6294            return null;
6295        }
6296        synchronized (mPackages) {
6297            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6298                    packageName, userId);
6299        }
6300    }
6301
6302    @Override
6303    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6304        if (DISABLE_EPHEMERAL_APPS) {
6305            return true;
6306        }
6307
6308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6309                true /* requireFullPermission */, true /* checkShell */,
6310                "setCookie");
6311        if (!isCallerSameApp(packageName)) {
6312            return false;
6313        }
6314        synchronized (mPackages) {
6315            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6316                    packageName, cookie, userId);
6317        }
6318    }
6319
6320    @Override
6321    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6322        if (DISABLE_EPHEMERAL_APPS) {
6323            return null;
6324        }
6325
6326        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6327                "getEphemeralApplicationIcon");
6328        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6329                true /* requireFullPermission */, false /* checkShell */,
6330                "getEphemeralApplicationIcon");
6331        synchronized (mPackages) {
6332            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6333                    packageName, userId);
6334        }
6335    }
6336
6337    private boolean isCallerSameApp(String packageName) {
6338        PackageParser.Package pkg = mPackages.get(packageName);
6339        return pkg != null
6340                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6341    }
6342
6343    @Override
6344    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6345        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6346    }
6347
6348    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6349        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6350
6351        // reader
6352        synchronized (mPackages) {
6353            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6354            final int userId = UserHandle.getCallingUserId();
6355            while (i.hasNext()) {
6356                final PackageParser.Package p = i.next();
6357                if (p.applicationInfo == null) continue;
6358
6359                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6360                        && !p.applicationInfo.isDirectBootAware();
6361                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6362                        && p.applicationInfo.isDirectBootAware();
6363
6364                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6365                        && (!mSafeMode || isSystemApp(p))
6366                        && (matchesUnaware || matchesAware)) {
6367                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6368                    if (ps != null) {
6369                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6370                                ps.readUserState(userId), userId);
6371                        if (ai != null) {
6372                            finalList.add(ai);
6373                        }
6374                    }
6375                }
6376            }
6377        }
6378
6379        return finalList;
6380    }
6381
6382    @Override
6383    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6384        if (!sUserManager.exists(userId)) return null;
6385        flags = updateFlagsForComponent(flags, userId, name);
6386        // reader
6387        synchronized (mPackages) {
6388            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6389            PackageSetting ps = provider != null
6390                    ? mSettings.mPackages.get(provider.owner.packageName)
6391                    : null;
6392            return ps != null
6393                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6394                    ? PackageParser.generateProviderInfo(provider, flags,
6395                            ps.readUserState(userId), userId)
6396                    : null;
6397        }
6398    }
6399
6400    /**
6401     * @deprecated
6402     */
6403    @Deprecated
6404    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6405        // reader
6406        synchronized (mPackages) {
6407            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6408                    .entrySet().iterator();
6409            final int userId = UserHandle.getCallingUserId();
6410            while (i.hasNext()) {
6411                Map.Entry<String, PackageParser.Provider> entry = i.next();
6412                PackageParser.Provider p = entry.getValue();
6413                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6414
6415                if (ps != null && p.syncable
6416                        && (!mSafeMode || (p.info.applicationInfo.flags
6417                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6418                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6419                            ps.readUserState(userId), userId);
6420                    if (info != null) {
6421                        outNames.add(entry.getKey());
6422                        outInfo.add(info);
6423                    }
6424                }
6425            }
6426        }
6427    }
6428
6429    @Override
6430    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6431            int uid, int flags) {
6432        final int userId = processName != null ? UserHandle.getUserId(uid)
6433                : UserHandle.getCallingUserId();
6434        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6435        flags = updateFlagsForComponent(flags, userId, processName);
6436
6437        ArrayList<ProviderInfo> finalList = null;
6438        // reader
6439        synchronized (mPackages) {
6440            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6441            while (i.hasNext()) {
6442                final PackageParser.Provider p = i.next();
6443                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6444                if (ps != null && p.info.authority != null
6445                        && (processName == null
6446                                || (p.info.processName.equals(processName)
6447                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6448                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6449                    if (finalList == null) {
6450                        finalList = new ArrayList<ProviderInfo>(3);
6451                    }
6452                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6453                            ps.readUserState(userId), userId);
6454                    if (info != null) {
6455                        finalList.add(info);
6456                    }
6457                }
6458            }
6459        }
6460
6461        if (finalList != null) {
6462            Collections.sort(finalList, mProviderInitOrderSorter);
6463            return new ParceledListSlice<ProviderInfo>(finalList);
6464        }
6465
6466        return ParceledListSlice.emptyList();
6467    }
6468
6469    @Override
6470    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6471        // reader
6472        synchronized (mPackages) {
6473            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6474            return PackageParser.generateInstrumentationInfo(i, flags);
6475        }
6476    }
6477
6478    @Override
6479    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6480            String targetPackage, int flags) {
6481        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6482    }
6483
6484    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6485            int flags) {
6486        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6487
6488        // reader
6489        synchronized (mPackages) {
6490            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6491            while (i.hasNext()) {
6492                final PackageParser.Instrumentation p = i.next();
6493                if (targetPackage == null
6494                        || targetPackage.equals(p.info.targetPackage)) {
6495                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6496                            flags);
6497                    if (ii != null) {
6498                        finalList.add(ii);
6499                    }
6500                }
6501            }
6502        }
6503
6504        return finalList;
6505    }
6506
6507    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6508        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6509        if (overlays == null) {
6510            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6511            return;
6512        }
6513        for (PackageParser.Package opkg : overlays.values()) {
6514            // Not much to do if idmap fails: we already logged the error
6515            // and we certainly don't want to abort installation of pkg simply
6516            // because an overlay didn't fit properly. For these reasons,
6517            // ignore the return value of createIdmapForPackagePairLI.
6518            createIdmapForPackagePairLI(pkg, opkg);
6519        }
6520    }
6521
6522    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6523            PackageParser.Package opkg) {
6524        if (!opkg.mTrustedOverlay) {
6525            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6526                    opkg.baseCodePath + ": overlay not trusted");
6527            return false;
6528        }
6529        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6530        if (overlaySet == null) {
6531            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6532                    opkg.baseCodePath + " but target package has no known overlays");
6533            return false;
6534        }
6535        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6536        // TODO: generate idmap for split APKs
6537        try {
6538            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6539        } catch (InstallerException e) {
6540            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6541                    + opkg.baseCodePath);
6542            return false;
6543        }
6544        PackageParser.Package[] overlayArray =
6545            overlaySet.values().toArray(new PackageParser.Package[0]);
6546        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6547            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6548                return p1.mOverlayPriority - p2.mOverlayPriority;
6549            }
6550        };
6551        Arrays.sort(overlayArray, cmp);
6552
6553        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6554        int i = 0;
6555        for (PackageParser.Package p : overlayArray) {
6556            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6557        }
6558        return true;
6559    }
6560
6561    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6562        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6563        try {
6564            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6565        } finally {
6566            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6567        }
6568    }
6569
6570    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6571        final File[] files = dir.listFiles();
6572        if (ArrayUtils.isEmpty(files)) {
6573            Log.d(TAG, "No files in app dir " + dir);
6574            return;
6575        }
6576
6577        if (DEBUG_PACKAGE_SCANNING) {
6578            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6579                    + " flags=0x" + Integer.toHexString(parseFlags));
6580        }
6581
6582        for (File file : files) {
6583            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6584                    && !PackageInstallerService.isStageName(file.getName());
6585            if (!isPackage) {
6586                // Ignore entries which are not packages
6587                continue;
6588            }
6589            try {
6590                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6591                        scanFlags, currentTime, null);
6592            } catch (PackageManagerException e) {
6593                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6594
6595                // Delete invalid userdata apps
6596                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6597                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6598                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6599                    removeCodePathLI(file);
6600                }
6601            }
6602        }
6603    }
6604
6605    private static File getSettingsProblemFile() {
6606        File dataDir = Environment.getDataDirectory();
6607        File systemDir = new File(dataDir, "system");
6608        File fname = new File(systemDir, "uiderrors.txt");
6609        return fname;
6610    }
6611
6612    static void reportSettingsProblem(int priority, String msg) {
6613        logCriticalInfo(priority, msg);
6614    }
6615
6616    static void logCriticalInfo(int priority, String msg) {
6617        Slog.println(priority, TAG, msg);
6618        EventLogTags.writePmCriticalInfo(msg);
6619        try {
6620            File fname = getSettingsProblemFile();
6621            FileOutputStream out = new FileOutputStream(fname, true);
6622            PrintWriter pw = new FastPrintWriter(out);
6623            SimpleDateFormat formatter = new SimpleDateFormat();
6624            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6625            pw.println(dateString + ": " + msg);
6626            pw.close();
6627            FileUtils.setPermissions(
6628                    fname.toString(),
6629                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6630                    -1, -1);
6631        } catch (java.io.IOException e) {
6632        }
6633    }
6634
6635    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6636        if (srcFile.isDirectory()) {
6637            final File baseFile = new File(pkg.baseCodePath);
6638            long maxModifiedTime = baseFile.lastModified();
6639            if (pkg.splitCodePaths != null) {
6640                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6641                    final File splitFile = new File(pkg.splitCodePaths[i]);
6642                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6643                }
6644            }
6645            return maxModifiedTime;
6646        }
6647        return srcFile.lastModified();
6648    }
6649
6650    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6651            final int policyFlags) throws PackageManagerException {
6652        if (ps != null
6653                && ps.codePath.equals(srcFile)
6654                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6655                && !isCompatSignatureUpdateNeeded(pkg)
6656                && !isRecoverSignatureUpdateNeeded(pkg)) {
6657            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6658            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6659            ArraySet<PublicKey> signingKs;
6660            synchronized (mPackages) {
6661                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6662            }
6663            if (ps.signatures.mSignatures != null
6664                    && ps.signatures.mSignatures.length != 0
6665                    && signingKs != null) {
6666                // Optimization: reuse the existing cached certificates
6667                // if the package appears to be unchanged.
6668                pkg.mSignatures = ps.signatures.mSignatures;
6669                pkg.mSigningKeys = signingKs;
6670                return;
6671            }
6672
6673            Slog.w(TAG, "PackageSetting for " + ps.name
6674                    + " is missing signatures.  Collecting certs again to recover them.");
6675        } else {
6676            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6677        }
6678
6679        try {
6680            PackageParser.collectCertificates(pkg, policyFlags);
6681        } catch (PackageParserException e) {
6682            throw PackageManagerException.from(e);
6683        }
6684    }
6685
6686    /**
6687     *  Traces a package scan.
6688     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6689     */
6690    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6691            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6692        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6693        try {
6694            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6695        } finally {
6696            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6697        }
6698    }
6699
6700    /**
6701     *  Scans a package and returns the newly parsed package.
6702     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6703     */
6704    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6705            long currentTime, UserHandle user) throws PackageManagerException {
6706        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6707        PackageParser pp = new PackageParser();
6708        pp.setSeparateProcesses(mSeparateProcesses);
6709        pp.setOnlyCoreApps(mOnlyCore);
6710        pp.setDisplayMetrics(mMetrics);
6711
6712        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6713            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6714        }
6715
6716        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6717        final PackageParser.Package pkg;
6718        try {
6719            pkg = pp.parsePackage(scanFile, parseFlags);
6720        } catch (PackageParserException e) {
6721            throw PackageManagerException.from(e);
6722        } finally {
6723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6724        }
6725
6726        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6727    }
6728
6729    /**
6730     *  Scans a package and returns the newly parsed package.
6731     *  @throws PackageManagerException on a parse error.
6732     */
6733    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6734            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6735            throws PackageManagerException {
6736        // If the package has children and this is the first dive in the function
6737        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6738        // packages (parent and children) would be successfully scanned before the
6739        // actual scan since scanning mutates internal state and we want to atomically
6740        // install the package and its children.
6741        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6742            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6743                scanFlags |= SCAN_CHECK_ONLY;
6744            }
6745        } else {
6746            scanFlags &= ~SCAN_CHECK_ONLY;
6747        }
6748
6749        // Scan the parent
6750        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6751                scanFlags, currentTime, user);
6752
6753        // Scan the children
6754        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6755        for (int i = 0; i < childCount; i++) {
6756            PackageParser.Package childPackage = pkg.childPackages.get(i);
6757            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6758                    currentTime, user);
6759        }
6760
6761
6762        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6763            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6764        }
6765
6766        return scannedPkg;
6767    }
6768
6769    /**
6770     *  Scans a package and returns the newly parsed package.
6771     *  @throws PackageManagerException on a parse error.
6772     */
6773    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6774            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6775            throws PackageManagerException {
6776        PackageSetting ps = null;
6777        PackageSetting updatedPkg;
6778        // reader
6779        synchronized (mPackages) {
6780            // Look to see if we already know about this package.
6781            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6782            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6783                // This package has been renamed to its original name.  Let's
6784                // use that.
6785                ps = mSettings.peekPackageLPr(oldName);
6786            }
6787            // If there was no original package, see one for the real package name.
6788            if (ps == null) {
6789                ps = mSettings.peekPackageLPr(pkg.packageName);
6790            }
6791            // Check to see if this package could be hiding/updating a system
6792            // package.  Must look for it either under the original or real
6793            // package name depending on our state.
6794            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6795            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6796
6797            // If this is a package we don't know about on the system partition, we
6798            // may need to remove disabled child packages on the system partition
6799            // or may need to not add child packages if the parent apk is updated
6800            // on the data partition and no longer defines this child package.
6801            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6802                // If this is a parent package for an updated system app and this system
6803                // app got an OTA update which no longer defines some of the child packages
6804                // we have to prune them from the disabled system packages.
6805                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6806                if (disabledPs != null) {
6807                    final int scannedChildCount = (pkg.childPackages != null)
6808                            ? pkg.childPackages.size() : 0;
6809                    final int disabledChildCount = disabledPs.childPackageNames != null
6810                            ? disabledPs.childPackageNames.size() : 0;
6811                    for (int i = 0; i < disabledChildCount; i++) {
6812                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6813                        boolean disabledPackageAvailable = false;
6814                        for (int j = 0; j < scannedChildCount; j++) {
6815                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6816                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6817                                disabledPackageAvailable = true;
6818                                break;
6819                            }
6820                         }
6821                         if (!disabledPackageAvailable) {
6822                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6823                         }
6824                    }
6825                }
6826            }
6827        }
6828
6829        boolean updatedPkgBetter = false;
6830        // First check if this is a system package that may involve an update
6831        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6832            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6833            // it needs to drop FLAG_PRIVILEGED.
6834            if (locationIsPrivileged(scanFile)) {
6835                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6836            } else {
6837                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6838            }
6839
6840            if (ps != null && !ps.codePath.equals(scanFile)) {
6841                // The path has changed from what was last scanned...  check the
6842                // version of the new path against what we have stored to determine
6843                // what to do.
6844                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6845                if (pkg.mVersionCode <= ps.versionCode) {
6846                    // The system package has been updated and the code path does not match
6847                    // Ignore entry. Skip it.
6848                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6849                            + " ignored: updated version " + ps.versionCode
6850                            + " better than this " + pkg.mVersionCode);
6851                    if (!updatedPkg.codePath.equals(scanFile)) {
6852                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6853                                + ps.name + " changing from " + updatedPkg.codePathString
6854                                + " to " + scanFile);
6855                        updatedPkg.codePath = scanFile;
6856                        updatedPkg.codePathString = scanFile.toString();
6857                        updatedPkg.resourcePath = scanFile;
6858                        updatedPkg.resourcePathString = scanFile.toString();
6859                    }
6860                    updatedPkg.pkg = pkg;
6861                    updatedPkg.versionCode = pkg.mVersionCode;
6862
6863                    // Update the disabled system child packages to point to the package too.
6864                    final int childCount = updatedPkg.childPackageNames != null
6865                            ? updatedPkg.childPackageNames.size() : 0;
6866                    for (int i = 0; i < childCount; i++) {
6867                        String childPackageName = updatedPkg.childPackageNames.get(i);
6868                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6869                                childPackageName);
6870                        if (updatedChildPkg != null) {
6871                            updatedChildPkg.pkg = pkg;
6872                            updatedChildPkg.versionCode = pkg.mVersionCode;
6873                        }
6874                    }
6875
6876                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6877                            + scanFile + " ignored: updated version " + ps.versionCode
6878                            + " better than this " + pkg.mVersionCode);
6879                } else {
6880                    // The current app on the system partition is better than
6881                    // what we have updated to on the data partition; switch
6882                    // back to the system partition version.
6883                    // At this point, its safely assumed that package installation for
6884                    // apps in system partition will go through. If not there won't be a working
6885                    // version of the app
6886                    // writer
6887                    synchronized (mPackages) {
6888                        // Just remove the loaded entries from package lists.
6889                        mPackages.remove(ps.name);
6890                    }
6891
6892                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6893                            + " reverting from " + ps.codePathString
6894                            + ": new version " + pkg.mVersionCode
6895                            + " better than installed " + ps.versionCode);
6896
6897                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6898                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6899                    synchronized (mInstallLock) {
6900                        args.cleanUpResourcesLI();
6901                    }
6902                    synchronized (mPackages) {
6903                        mSettings.enableSystemPackageLPw(ps.name);
6904                    }
6905                    updatedPkgBetter = true;
6906                }
6907            }
6908        }
6909
6910        if (updatedPkg != null) {
6911            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6912            // initially
6913            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6914
6915            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6916            // flag set initially
6917            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6918                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6919            }
6920        }
6921
6922        // Verify certificates against what was last scanned
6923        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6924
6925        /*
6926         * A new system app appeared, but we already had a non-system one of the
6927         * same name installed earlier.
6928         */
6929        boolean shouldHideSystemApp = false;
6930        if (updatedPkg == null && ps != null
6931                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6932            /*
6933             * Check to make sure the signatures match first. If they don't,
6934             * wipe the installed application and its data.
6935             */
6936            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6937                    != PackageManager.SIGNATURE_MATCH) {
6938                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6939                        + " signatures don't match existing userdata copy; removing");
6940                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6941                        "scanPackageInternalLI")) {
6942                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6943                }
6944                ps = null;
6945            } else {
6946                /*
6947                 * If the newly-added system app is an older version than the
6948                 * already installed version, hide it. It will be scanned later
6949                 * and re-added like an update.
6950                 */
6951                if (pkg.mVersionCode <= ps.versionCode) {
6952                    shouldHideSystemApp = true;
6953                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6954                            + " but new version " + pkg.mVersionCode + " better than installed "
6955                            + ps.versionCode + "; hiding system");
6956                } else {
6957                    /*
6958                     * The newly found system app is a newer version that the
6959                     * one previously installed. Simply remove the
6960                     * already-installed application and replace it with our own
6961                     * while keeping the application data.
6962                     */
6963                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6964                            + " reverting from " + ps.codePathString + ": new version "
6965                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6966                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6967                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6968                    synchronized (mInstallLock) {
6969                        args.cleanUpResourcesLI();
6970                    }
6971                }
6972            }
6973        }
6974
6975        // The apk is forward locked (not public) if its code and resources
6976        // are kept in different files. (except for app in either system or
6977        // vendor path).
6978        // TODO grab this value from PackageSettings
6979        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6980            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6981                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6982            }
6983        }
6984
6985        // TODO: extend to support forward-locked splits
6986        String resourcePath = null;
6987        String baseResourcePath = null;
6988        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6989            if (ps != null && ps.resourcePathString != null) {
6990                resourcePath = ps.resourcePathString;
6991                baseResourcePath = ps.resourcePathString;
6992            } else {
6993                // Should not happen at all. Just log an error.
6994                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6995            }
6996        } else {
6997            resourcePath = pkg.codePath;
6998            baseResourcePath = pkg.baseCodePath;
6999        }
7000
7001        // Set application objects path explicitly.
7002        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7003        pkg.setApplicationInfoCodePath(pkg.codePath);
7004        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7005        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7006        pkg.setApplicationInfoResourcePath(resourcePath);
7007        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7008        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7009
7010        // Note that we invoke the following method only if we are about to unpack an application
7011        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7012                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7013
7014        /*
7015         * If the system app should be overridden by a previously installed
7016         * data, hide the system app now and let the /data/app scan pick it up
7017         * again.
7018         */
7019        if (shouldHideSystemApp) {
7020            synchronized (mPackages) {
7021                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7022            }
7023        }
7024
7025        return scannedPkg;
7026    }
7027
7028    private static String fixProcessName(String defProcessName,
7029            String processName, int uid) {
7030        if (processName == null) {
7031            return defProcessName;
7032        }
7033        return processName;
7034    }
7035
7036    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7037            throws PackageManagerException {
7038        if (pkgSetting.signatures.mSignatures != null) {
7039            // Already existing package. Make sure signatures match
7040            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7041                    == PackageManager.SIGNATURE_MATCH;
7042            if (!match) {
7043                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7044                        == PackageManager.SIGNATURE_MATCH;
7045            }
7046            if (!match) {
7047                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7048                        == PackageManager.SIGNATURE_MATCH;
7049            }
7050            if (!match) {
7051                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7052                        + pkg.packageName + " signatures do not match the "
7053                        + "previously installed version; ignoring!");
7054            }
7055        }
7056
7057        // Check for shared user signatures
7058        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7059            // Already existing package. Make sure signatures match
7060            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7061                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7062            if (!match) {
7063                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7064                        == PackageManager.SIGNATURE_MATCH;
7065            }
7066            if (!match) {
7067                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7068                        == PackageManager.SIGNATURE_MATCH;
7069            }
7070            if (!match) {
7071                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7072                        "Package " + pkg.packageName
7073                        + " has no signatures that match those in shared user "
7074                        + pkgSetting.sharedUser.name + "; ignoring!");
7075            }
7076        }
7077    }
7078
7079    /**
7080     * Enforces that only the system UID or root's UID can call a method exposed
7081     * via Binder.
7082     *
7083     * @param message used as message if SecurityException is thrown
7084     * @throws SecurityException if the caller is not system or root
7085     */
7086    private static final void enforceSystemOrRoot(String message) {
7087        final int uid = Binder.getCallingUid();
7088        if (uid != Process.SYSTEM_UID && uid != 0) {
7089            throw new SecurityException(message);
7090        }
7091    }
7092
7093    @Override
7094    public void performFstrimIfNeeded() {
7095        enforceSystemOrRoot("Only the system can request fstrim");
7096
7097        // Before everything else, see whether we need to fstrim.
7098        try {
7099            IMountService ms = PackageHelper.getMountService();
7100            if (ms != null) {
7101                boolean doTrim = false;
7102                final long interval = android.provider.Settings.Global.getLong(
7103                        mContext.getContentResolver(),
7104                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7105                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7106                if (interval > 0) {
7107                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7108                    if (timeSinceLast > interval) {
7109                        doTrim = true;
7110                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7111                                + "; running immediately");
7112                    }
7113                }
7114                if (doTrim) {
7115                    if (!isFirstBoot()) {
7116                        try {
7117                            ActivityManagerNative.getDefault().showBootMessage(
7118                                    mContext.getResources().getString(
7119                                            R.string.android_upgrading_fstrim), true);
7120                        } catch (RemoteException e) {
7121                        }
7122                    }
7123                    ms.runMaintenance();
7124                }
7125            } else {
7126                Slog.e(TAG, "Mount service unavailable!");
7127            }
7128        } catch (RemoteException e) {
7129            // Can't happen; MountService is local
7130        }
7131    }
7132
7133    @Override
7134    public void updatePackagesIfNeeded() {
7135        enforceSystemOrRoot("Only the system can request package update");
7136
7137        // We need to re-extract after an OTA.
7138        boolean causeUpgrade = isUpgrade();
7139
7140        // First boot or factory reset.
7141        // Note: we also handle devices that are upgrading to N right now as if it is their
7142        //       first boot, as they do not have profile data.
7143        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7144
7145        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7146        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7147
7148        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7149            return;
7150        }
7151
7152        List<PackageParser.Package> pkgs;
7153        synchronized (mPackages) {
7154            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7155        }
7156
7157        final long startTime = System.nanoTime();
7158        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7159                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7160
7161        final int elapsedTimeSeconds =
7162                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7163
7164        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7165        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7166        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7167        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7168        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7169    }
7170
7171    /**
7172     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7173     * containing statistics about the invocation. The array consists of three elements,
7174     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7175     * and {@code numberOfPackagesFailed}.
7176     */
7177    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7178            String compilerFilter) {
7179
7180        int numberOfPackagesVisited = 0;
7181        int numberOfPackagesOptimized = 0;
7182        int numberOfPackagesSkipped = 0;
7183        int numberOfPackagesFailed = 0;
7184        final int numberOfPackagesToDexopt = pkgs.size();
7185
7186        for (PackageParser.Package pkg : pkgs) {
7187            numberOfPackagesVisited++;
7188
7189            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7190                if (DEBUG_DEXOPT) {
7191                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7192                }
7193                numberOfPackagesSkipped++;
7194                continue;
7195            }
7196
7197            if (DEBUG_DEXOPT) {
7198                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7199                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7200            }
7201
7202            if (showDialog) {
7203                try {
7204                    ActivityManagerNative.getDefault().showBootMessage(
7205                            mContext.getResources().getString(R.string.android_upgrading_apk,
7206                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7207                } catch (RemoteException e) {
7208                }
7209            }
7210
7211            // If the OTA updates a system app which was previously preopted to a non-preopted state
7212            // the app might end up being verified at runtime. That's because by default the apps
7213            // are verify-profile but for preopted apps there's no profile.
7214            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7215            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7216            // filter (by default interpret-only).
7217            // Note that at this stage unused apps are already filtered.
7218            if (isSystemApp(pkg) &&
7219                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7220                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7221                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7222            }
7223
7224            // checkProfiles is false to avoid merging profiles during boot which
7225            // might interfere with background compilation (b/28612421).
7226            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7227            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7228            // trade-off worth doing to save boot time work.
7229            int dexOptStatus = performDexOptTraced(pkg.packageName,
7230                    false /* checkProfiles */,
7231                    compilerFilter,
7232                    false /* force */);
7233            switch (dexOptStatus) {
7234                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7235                    numberOfPackagesOptimized++;
7236                    break;
7237                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7238                    numberOfPackagesSkipped++;
7239                    break;
7240                case PackageDexOptimizer.DEX_OPT_FAILED:
7241                    numberOfPackagesFailed++;
7242                    break;
7243                default:
7244                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7245                    break;
7246            }
7247        }
7248
7249        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7250                numberOfPackagesFailed };
7251    }
7252
7253    @Override
7254    public void notifyPackageUse(String packageName, int reason) {
7255        synchronized (mPackages) {
7256            PackageParser.Package p = mPackages.get(packageName);
7257            if (p == null) {
7258                return;
7259            }
7260            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7261        }
7262    }
7263
7264    // TODO: this is not used nor needed. Delete it.
7265    @Override
7266    public boolean performDexOptIfNeeded(String packageName) {
7267        int dexOptStatus = performDexOptTraced(packageName,
7268                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7269        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7270    }
7271
7272    @Override
7273    public boolean performDexOpt(String packageName,
7274            boolean checkProfiles, int compileReason, boolean force) {
7275        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7276                getCompilerFilterForReason(compileReason), force);
7277        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7278    }
7279
7280    @Override
7281    public boolean performDexOptMode(String packageName,
7282            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7283        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7284                targetCompilerFilter, force);
7285        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7286    }
7287
7288    private int performDexOptTraced(String packageName,
7289                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7290        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7291        try {
7292            return performDexOptInternal(packageName, checkProfiles,
7293                    targetCompilerFilter, force);
7294        } finally {
7295            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7296        }
7297    }
7298
7299    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7300    // if the package can now be considered up to date for the given filter.
7301    private int performDexOptInternal(String packageName,
7302                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7303        PackageParser.Package p;
7304        synchronized (mPackages) {
7305            p = mPackages.get(packageName);
7306            if (p == null) {
7307                // Package could not be found. Report failure.
7308                return PackageDexOptimizer.DEX_OPT_FAILED;
7309            }
7310            mPackageUsage.maybeWriteAsync(mPackages);
7311            mCompilerStats.maybeWriteAsync();
7312        }
7313        long callingId = Binder.clearCallingIdentity();
7314        try {
7315            synchronized (mInstallLock) {
7316                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7317                        targetCompilerFilter, force);
7318            }
7319        } finally {
7320            Binder.restoreCallingIdentity(callingId);
7321        }
7322    }
7323
7324    public ArraySet<String> getOptimizablePackages() {
7325        ArraySet<String> pkgs = new ArraySet<String>();
7326        synchronized (mPackages) {
7327            for (PackageParser.Package p : mPackages.values()) {
7328                if (PackageDexOptimizer.canOptimizePackage(p)) {
7329                    pkgs.add(p.packageName);
7330                }
7331            }
7332        }
7333        return pkgs;
7334    }
7335
7336    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7337            boolean checkProfiles, String targetCompilerFilter,
7338            boolean force) {
7339        // Select the dex optimizer based on the force parameter.
7340        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7341        //       allocate an object here.
7342        PackageDexOptimizer pdo = force
7343                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7344                : mPackageDexOptimizer;
7345
7346        // Optimize all dependencies first. Note: we ignore the return value and march on
7347        // on errors.
7348        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7349        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7350        if (!deps.isEmpty()) {
7351            for (PackageParser.Package depPackage : deps) {
7352                // TODO: Analyze and investigate if we (should) profile libraries.
7353                // Currently this will do a full compilation of the library by default.
7354                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7355                        false /* checkProfiles */,
7356                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7357                        getOrCreateCompilerPackageStats(depPackage));
7358            }
7359        }
7360        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7361                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7362    }
7363
7364    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7365        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7366            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7367            Set<String> collectedNames = new HashSet<>();
7368            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7369
7370            retValue.remove(p);
7371
7372            return retValue;
7373        } else {
7374            return Collections.emptyList();
7375        }
7376    }
7377
7378    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7379            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7380        if (!collectedNames.contains(p.packageName)) {
7381            collectedNames.add(p.packageName);
7382            collected.add(p);
7383
7384            if (p.usesLibraries != null) {
7385                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7386            }
7387            if (p.usesOptionalLibraries != null) {
7388                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7389                        collectedNames);
7390            }
7391        }
7392    }
7393
7394    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7395            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7396        for (String libName : libs) {
7397            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7398            if (libPkg != null) {
7399                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7400            }
7401        }
7402    }
7403
7404    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7405        synchronized (mPackages) {
7406            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7407            if (lib != null && lib.apk != null) {
7408                return mPackages.get(lib.apk);
7409            }
7410        }
7411        return null;
7412    }
7413
7414    public void shutdown() {
7415        mPackageUsage.writeNow(mPackages);
7416        mCompilerStats.writeNow();
7417    }
7418
7419    @Override
7420    public void dumpProfiles(String packageName) {
7421        PackageParser.Package pkg;
7422        synchronized (mPackages) {
7423            pkg = mPackages.get(packageName);
7424            if (pkg == null) {
7425                throw new IllegalArgumentException("Unknown package: " + packageName);
7426            }
7427        }
7428        /* Only the shell, root, or the app user should be able to dump profiles. */
7429        int callingUid = Binder.getCallingUid();
7430        if (callingUid != Process.SHELL_UID &&
7431            callingUid != Process.ROOT_UID &&
7432            callingUid != pkg.applicationInfo.uid) {
7433            throw new SecurityException("dumpProfiles");
7434        }
7435
7436        synchronized (mInstallLock) {
7437            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7438            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7439            try {
7440                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7441                String gid = Integer.toString(sharedGid);
7442                String codePaths = TextUtils.join(";", allCodePaths);
7443                mInstaller.dumpProfiles(gid, packageName, codePaths);
7444            } catch (InstallerException e) {
7445                Slog.w(TAG, "Failed to dump profiles", e);
7446            }
7447            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7448        }
7449    }
7450
7451    @Override
7452    public void forceDexOpt(String packageName) {
7453        enforceSystemOrRoot("forceDexOpt");
7454
7455        PackageParser.Package pkg;
7456        synchronized (mPackages) {
7457            pkg = mPackages.get(packageName);
7458            if (pkg == null) {
7459                throw new IllegalArgumentException("Unknown package: " + packageName);
7460            }
7461        }
7462
7463        synchronized (mInstallLock) {
7464            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7465
7466            // Whoever is calling forceDexOpt wants a fully compiled package.
7467            // Don't use profiles since that may cause compilation to be skipped.
7468            final int res = performDexOptInternalWithDependenciesLI(pkg,
7469                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7470                    true /* force */);
7471
7472            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7473            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7474                throw new IllegalStateException("Failed to dexopt: " + res);
7475            }
7476        }
7477    }
7478
7479    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7480        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7481            Slog.w(TAG, "Unable to update from " + oldPkg.name
7482                    + " to " + newPkg.packageName
7483                    + ": old package not in system partition");
7484            return false;
7485        } else if (mPackages.get(oldPkg.name) != null) {
7486            Slog.w(TAG, "Unable to update from " + oldPkg.name
7487                    + " to " + newPkg.packageName
7488                    + ": old package still exists");
7489            return false;
7490        }
7491        return true;
7492    }
7493
7494    void removeCodePathLI(File codePath) {
7495        if (codePath.isDirectory()) {
7496            try {
7497                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7498            } catch (InstallerException e) {
7499                Slog.w(TAG, "Failed to remove code path", e);
7500            }
7501        } else {
7502            codePath.delete();
7503        }
7504    }
7505
7506    private int[] resolveUserIds(int userId) {
7507        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7508    }
7509
7510    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7511        if (pkg == null) {
7512            Slog.wtf(TAG, "Package was null!", new Throwable());
7513            return;
7514        }
7515        clearAppDataLeafLIF(pkg, userId, flags);
7516        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7517        for (int i = 0; i < childCount; i++) {
7518            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7519        }
7520    }
7521
7522    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7523        final PackageSetting ps;
7524        synchronized (mPackages) {
7525            ps = mSettings.mPackages.get(pkg.packageName);
7526        }
7527        for (int realUserId : resolveUserIds(userId)) {
7528            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7529            try {
7530                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7531                        ceDataInode);
7532            } catch (InstallerException e) {
7533                Slog.w(TAG, String.valueOf(e));
7534            }
7535        }
7536    }
7537
7538    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7539        if (pkg == null) {
7540            Slog.wtf(TAG, "Package was null!", new Throwable());
7541            return;
7542        }
7543        destroyAppDataLeafLIF(pkg, userId, flags);
7544        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7545        for (int i = 0; i < childCount; i++) {
7546            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7547        }
7548    }
7549
7550    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7551        final PackageSetting ps;
7552        synchronized (mPackages) {
7553            ps = mSettings.mPackages.get(pkg.packageName);
7554        }
7555        for (int realUserId : resolveUserIds(userId)) {
7556            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7557            try {
7558                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7559                        ceDataInode);
7560            } catch (InstallerException e) {
7561                Slog.w(TAG, String.valueOf(e));
7562            }
7563        }
7564    }
7565
7566    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7567        if (pkg == null) {
7568            Slog.wtf(TAG, "Package was null!", new Throwable());
7569            return;
7570        }
7571        destroyAppProfilesLeafLIF(pkg);
7572        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7573        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7574        for (int i = 0; i < childCount; i++) {
7575            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7576            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7577                    true /* removeBaseMarker */);
7578        }
7579    }
7580
7581    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7582            boolean removeBaseMarker) {
7583        if (pkg.isForwardLocked()) {
7584            return;
7585        }
7586
7587        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7588            try {
7589                path = PackageManagerServiceUtils.realpath(new File(path));
7590            } catch (IOException e) {
7591                // TODO: Should we return early here ?
7592                Slog.w(TAG, "Failed to get canonical path", e);
7593                continue;
7594            }
7595
7596            final String useMarker = path.replace('/', '@');
7597            for (int realUserId : resolveUserIds(userId)) {
7598                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7599                if (removeBaseMarker) {
7600                    File foreignUseMark = new File(profileDir, useMarker);
7601                    if (foreignUseMark.exists()) {
7602                        if (!foreignUseMark.delete()) {
7603                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7604                                    + pkg.packageName);
7605                        }
7606                    }
7607                }
7608
7609                File[] markers = profileDir.listFiles();
7610                if (markers != null) {
7611                    final String searchString = "@" + pkg.packageName + "@";
7612                    // We also delete all markers that contain the package name we're
7613                    // uninstalling. These are associated with secondary dex-files belonging
7614                    // to the package. Reconstructing the path of these dex files is messy
7615                    // in general.
7616                    for (File marker : markers) {
7617                        if (marker.getName().indexOf(searchString) > 0) {
7618                            if (!marker.delete()) {
7619                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7620                                    + pkg.packageName);
7621                            }
7622                        }
7623                    }
7624                }
7625            }
7626        }
7627    }
7628
7629    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7630        try {
7631            mInstaller.destroyAppProfiles(pkg.packageName);
7632        } catch (InstallerException e) {
7633            Slog.w(TAG, String.valueOf(e));
7634        }
7635    }
7636
7637    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7638        if (pkg == null) {
7639            Slog.wtf(TAG, "Package was null!", new Throwable());
7640            return;
7641        }
7642        clearAppProfilesLeafLIF(pkg);
7643        // We don't remove the base foreign use marker when clearing profiles because
7644        // we will rename it when the app is updated. Unlike the actual profile contents,
7645        // the foreign use marker is good across installs.
7646        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7647        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7648        for (int i = 0; i < childCount; i++) {
7649            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7650        }
7651    }
7652
7653    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7654        try {
7655            mInstaller.clearAppProfiles(pkg.packageName);
7656        } catch (InstallerException e) {
7657            Slog.w(TAG, String.valueOf(e));
7658        }
7659    }
7660
7661    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7662            long lastUpdateTime) {
7663        // Set parent install/update time
7664        PackageSetting ps = (PackageSetting) pkg.mExtras;
7665        if (ps != null) {
7666            ps.firstInstallTime = firstInstallTime;
7667            ps.lastUpdateTime = lastUpdateTime;
7668        }
7669        // Set children install/update time
7670        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7671        for (int i = 0; i < childCount; i++) {
7672            PackageParser.Package childPkg = pkg.childPackages.get(i);
7673            ps = (PackageSetting) childPkg.mExtras;
7674            if (ps != null) {
7675                ps.firstInstallTime = firstInstallTime;
7676                ps.lastUpdateTime = lastUpdateTime;
7677            }
7678        }
7679    }
7680
7681    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7682            PackageParser.Package changingLib) {
7683        if (file.path != null) {
7684            usesLibraryFiles.add(file.path);
7685            return;
7686        }
7687        PackageParser.Package p = mPackages.get(file.apk);
7688        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7689            // If we are doing this while in the middle of updating a library apk,
7690            // then we need to make sure to use that new apk for determining the
7691            // dependencies here.  (We haven't yet finished committing the new apk
7692            // to the package manager state.)
7693            if (p == null || p.packageName.equals(changingLib.packageName)) {
7694                p = changingLib;
7695            }
7696        }
7697        if (p != null) {
7698            usesLibraryFiles.addAll(p.getAllCodePaths());
7699        }
7700    }
7701
7702    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7703            PackageParser.Package changingLib) throws PackageManagerException {
7704        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7705            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7706            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7707            for (int i=0; i<N; i++) {
7708                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7709                if (file == null) {
7710                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7711                            "Package " + pkg.packageName + " requires unavailable shared library "
7712                            + pkg.usesLibraries.get(i) + "; failing!");
7713                }
7714                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7715            }
7716            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7717            for (int i=0; i<N; i++) {
7718                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7719                if (file == null) {
7720                    Slog.w(TAG, "Package " + pkg.packageName
7721                            + " desires unavailable shared library "
7722                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7723                } else {
7724                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7725                }
7726            }
7727            N = usesLibraryFiles.size();
7728            if (N > 0) {
7729                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7730            } else {
7731                pkg.usesLibraryFiles = null;
7732            }
7733        }
7734    }
7735
7736    private static boolean hasString(List<String> list, List<String> which) {
7737        if (list == null) {
7738            return false;
7739        }
7740        for (int i=list.size()-1; i>=0; i--) {
7741            for (int j=which.size()-1; j>=0; j--) {
7742                if (which.get(j).equals(list.get(i))) {
7743                    return true;
7744                }
7745            }
7746        }
7747        return false;
7748    }
7749
7750    private void updateAllSharedLibrariesLPw() {
7751        for (PackageParser.Package pkg : mPackages.values()) {
7752            try {
7753                updateSharedLibrariesLPw(pkg, null);
7754            } catch (PackageManagerException e) {
7755                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7756            }
7757        }
7758    }
7759
7760    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7761            PackageParser.Package changingPkg) {
7762        ArrayList<PackageParser.Package> res = null;
7763        for (PackageParser.Package pkg : mPackages.values()) {
7764            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7765                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7766                if (res == null) {
7767                    res = new ArrayList<PackageParser.Package>();
7768                }
7769                res.add(pkg);
7770                try {
7771                    updateSharedLibrariesLPw(pkg, changingPkg);
7772                } catch (PackageManagerException e) {
7773                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7774                }
7775            }
7776        }
7777        return res;
7778    }
7779
7780    /**
7781     * Derive the value of the {@code cpuAbiOverride} based on the provided
7782     * value and an optional stored value from the package settings.
7783     */
7784    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7785        String cpuAbiOverride = null;
7786
7787        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7788            cpuAbiOverride = null;
7789        } else if (abiOverride != null) {
7790            cpuAbiOverride = abiOverride;
7791        } else if (settings != null) {
7792            cpuAbiOverride = settings.cpuAbiOverrideString;
7793        }
7794
7795        return cpuAbiOverride;
7796    }
7797
7798    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7799            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7800                    throws PackageManagerException {
7801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7802        // If the package has children and this is the first dive in the function
7803        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7804        // whether all packages (parent and children) would be successfully scanned
7805        // before the actual scan since scanning mutates internal state and we want
7806        // to atomically install the package and its children.
7807        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7808            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7809                scanFlags |= SCAN_CHECK_ONLY;
7810            }
7811        } else {
7812            scanFlags &= ~SCAN_CHECK_ONLY;
7813        }
7814
7815        final PackageParser.Package scannedPkg;
7816        try {
7817            // Scan the parent
7818            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7819            // Scan the children
7820            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7821            for (int i = 0; i < childCount; i++) {
7822                PackageParser.Package childPkg = pkg.childPackages.get(i);
7823                scanPackageLI(childPkg, policyFlags,
7824                        scanFlags, currentTime, user);
7825            }
7826        } finally {
7827            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7828        }
7829
7830        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7831            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7832        }
7833
7834        return scannedPkg;
7835    }
7836
7837    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7838            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7839        boolean success = false;
7840        try {
7841            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7842                    currentTime, user);
7843            success = true;
7844            return res;
7845        } finally {
7846            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7847                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7848                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7849                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7850                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7851            }
7852        }
7853    }
7854
7855    /**
7856     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7857     */
7858    private static boolean apkHasCode(String fileName) {
7859        StrictJarFile jarFile = null;
7860        try {
7861            jarFile = new StrictJarFile(fileName,
7862                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7863            return jarFile.findEntry("classes.dex") != null;
7864        } catch (IOException ignore) {
7865        } finally {
7866            try {
7867                if (jarFile != null) {
7868                    jarFile.close();
7869                }
7870            } catch (IOException ignore) {}
7871        }
7872        return false;
7873    }
7874
7875    /**
7876     * Enforces code policy for the package. This ensures that if an APK has
7877     * declared hasCode="true" in its manifest that the APK actually contains
7878     * code.
7879     *
7880     * @throws PackageManagerException If bytecode could not be found when it should exist
7881     */
7882    private static void enforceCodePolicy(PackageParser.Package pkg)
7883            throws PackageManagerException {
7884        final boolean shouldHaveCode =
7885                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7886        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7887            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7888                    "Package " + pkg.baseCodePath + " code is missing");
7889        }
7890
7891        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7892            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7893                final boolean splitShouldHaveCode =
7894                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7895                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7896                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7897                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7898                }
7899            }
7900        }
7901    }
7902
7903    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7904            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7905            throws PackageManagerException {
7906        final File scanFile = new File(pkg.codePath);
7907        if (pkg.applicationInfo.getCodePath() == null ||
7908                pkg.applicationInfo.getResourcePath() == null) {
7909            // Bail out. The resource and code paths haven't been set.
7910            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7911                    "Code and resource paths haven't been set correctly");
7912        }
7913
7914        // Apply policy
7915        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7916            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7917            if (pkg.applicationInfo.isDirectBootAware()) {
7918                // we're direct boot aware; set for all components
7919                for (PackageParser.Service s : pkg.services) {
7920                    s.info.encryptionAware = s.info.directBootAware = true;
7921                }
7922                for (PackageParser.Provider p : pkg.providers) {
7923                    p.info.encryptionAware = p.info.directBootAware = true;
7924                }
7925                for (PackageParser.Activity a : pkg.activities) {
7926                    a.info.encryptionAware = a.info.directBootAware = true;
7927                }
7928                for (PackageParser.Activity r : pkg.receivers) {
7929                    r.info.encryptionAware = r.info.directBootAware = true;
7930                }
7931            }
7932        } else {
7933            // Only allow system apps to be flagged as core apps.
7934            pkg.coreApp = false;
7935            // clear flags not applicable to regular apps
7936            pkg.applicationInfo.privateFlags &=
7937                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7938            pkg.applicationInfo.privateFlags &=
7939                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7940        }
7941        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7942
7943        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7944            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7945        }
7946
7947        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7948            enforceCodePolicy(pkg);
7949        }
7950
7951        if (mCustomResolverComponentName != null &&
7952                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7953            setUpCustomResolverActivity(pkg);
7954        }
7955
7956        if (pkg.packageName.equals("android")) {
7957            synchronized (mPackages) {
7958                if (mAndroidApplication != null) {
7959                    Slog.w(TAG, "*************************************************");
7960                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7961                    Slog.w(TAG, " file=" + scanFile);
7962                    Slog.w(TAG, "*************************************************");
7963                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7964                            "Core android package being redefined.  Skipping.");
7965                }
7966
7967                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7968                    // Set up information for our fall-back user intent resolution activity.
7969                    mPlatformPackage = pkg;
7970                    pkg.mVersionCode = mSdkVersion;
7971                    mAndroidApplication = pkg.applicationInfo;
7972
7973                    if (!mResolverReplaced) {
7974                        mResolveActivity.applicationInfo = mAndroidApplication;
7975                        mResolveActivity.name = ResolverActivity.class.getName();
7976                        mResolveActivity.packageName = mAndroidApplication.packageName;
7977                        mResolveActivity.processName = "system:ui";
7978                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7979                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7980                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7981                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7982                        mResolveActivity.exported = true;
7983                        mResolveActivity.enabled = true;
7984                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7985                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7986                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7987                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7988                                | ActivityInfo.CONFIG_ORIENTATION
7989                                | ActivityInfo.CONFIG_KEYBOARD
7990                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7991                        mResolveInfo.activityInfo = mResolveActivity;
7992                        mResolveInfo.priority = 0;
7993                        mResolveInfo.preferredOrder = 0;
7994                        mResolveInfo.match = 0;
7995                        mResolveComponentName = new ComponentName(
7996                                mAndroidApplication.packageName, mResolveActivity.name);
7997                    }
7998                }
7999            }
8000        }
8001
8002        if (DEBUG_PACKAGE_SCANNING) {
8003            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8004                Log.d(TAG, "Scanning package " + pkg.packageName);
8005        }
8006
8007        synchronized (mPackages) {
8008            if (mPackages.containsKey(pkg.packageName)
8009                    || mSharedLibraries.containsKey(pkg.packageName)) {
8010                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8011                        "Application package " + pkg.packageName
8012                                + " already installed.  Skipping duplicate.");
8013            }
8014
8015            // If we're only installing presumed-existing packages, require that the
8016            // scanned APK is both already known and at the path previously established
8017            // for it.  Previously unknown packages we pick up normally, but if we have an
8018            // a priori expectation about this package's install presence, enforce it.
8019            // With a singular exception for new system packages. When an OTA contains
8020            // a new system package, we allow the codepath to change from a system location
8021            // to the user-installed location. If we don't allow this change, any newer,
8022            // user-installed version of the application will be ignored.
8023            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8024                if (mExpectingBetter.containsKey(pkg.packageName)) {
8025                    logCriticalInfo(Log.WARN,
8026                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8027                } else {
8028                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8029                    if (known != null) {
8030                        if (DEBUG_PACKAGE_SCANNING) {
8031                            Log.d(TAG, "Examining " + pkg.codePath
8032                                    + " and requiring known paths " + known.codePathString
8033                                    + " & " + known.resourcePathString);
8034                        }
8035                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8036                                || !pkg.applicationInfo.getResourcePath().equals(
8037                                known.resourcePathString)) {
8038                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8039                                    "Application package " + pkg.packageName
8040                                            + " found at " + pkg.applicationInfo.getCodePath()
8041                                            + " but expected at " + known.codePathString
8042                                            + "; ignoring.");
8043                        }
8044                    }
8045                }
8046            }
8047        }
8048
8049        // Initialize package source and resource directories
8050        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8051        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8052
8053        SharedUserSetting suid = null;
8054        PackageSetting pkgSetting = null;
8055
8056        if (!isSystemApp(pkg)) {
8057            // Only system apps can use these features.
8058            pkg.mOriginalPackages = null;
8059            pkg.mRealPackage = null;
8060            pkg.mAdoptPermissions = null;
8061        }
8062
8063        // Getting the package setting may have a side-effect, so if we
8064        // are only checking if scan would succeed, stash a copy of the
8065        // old setting to restore at the end.
8066        PackageSetting nonMutatedPs = null;
8067
8068        // writer
8069        synchronized (mPackages) {
8070            if (pkg.mSharedUserId != null) {
8071                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8072                if (suid == null) {
8073                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8074                            "Creating application package " + pkg.packageName
8075                            + " for shared user failed");
8076                }
8077                if (DEBUG_PACKAGE_SCANNING) {
8078                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8079                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8080                                + "): packages=" + suid.packages);
8081                }
8082            }
8083
8084            // Check if we are renaming from an original package name.
8085            PackageSetting origPackage = null;
8086            String realName = null;
8087            if (pkg.mOriginalPackages != null) {
8088                // This package may need to be renamed to a previously
8089                // installed name.  Let's check on that...
8090                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8091                if (pkg.mOriginalPackages.contains(renamed)) {
8092                    // This package had originally been installed as the
8093                    // original name, and we have already taken care of
8094                    // transitioning to the new one.  Just update the new
8095                    // one to continue using the old name.
8096                    realName = pkg.mRealPackage;
8097                    if (!pkg.packageName.equals(renamed)) {
8098                        // Callers into this function may have already taken
8099                        // care of renaming the package; only do it here if
8100                        // it is not already done.
8101                        pkg.setPackageName(renamed);
8102                    }
8103
8104                } else {
8105                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8106                        if ((origPackage = mSettings.peekPackageLPr(
8107                                pkg.mOriginalPackages.get(i))) != null) {
8108                            // We do have the package already installed under its
8109                            // original name...  should we use it?
8110                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8111                                // New package is not compatible with original.
8112                                origPackage = null;
8113                                continue;
8114                            } else if (origPackage.sharedUser != null) {
8115                                // Make sure uid is compatible between packages.
8116                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8117                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8118                                            + " to " + pkg.packageName + ": old uid "
8119                                            + origPackage.sharedUser.name
8120                                            + " differs from " + pkg.mSharedUserId);
8121                                    origPackage = null;
8122                                    continue;
8123                                }
8124                                // TODO: Add case when shared user id is added [b/28144775]
8125                            } else {
8126                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8127                                        + pkg.packageName + " to old name " + origPackage.name);
8128                            }
8129                            break;
8130                        }
8131                    }
8132                }
8133            }
8134
8135            if (mTransferedPackages.contains(pkg.packageName)) {
8136                Slog.w(TAG, "Package " + pkg.packageName
8137                        + " was transferred to another, but its .apk remains");
8138            }
8139
8140            // See comments in nonMutatedPs declaration
8141            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8142                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8143                if (foundPs != null) {
8144                    nonMutatedPs = new PackageSetting(foundPs);
8145                }
8146            }
8147
8148            // Just create the setting, don't add it yet. For already existing packages
8149            // the PkgSetting exists already and doesn't have to be created.
8150            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8151                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8152                    pkg.applicationInfo.primaryCpuAbi,
8153                    pkg.applicationInfo.secondaryCpuAbi,
8154                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8155                    user, false);
8156            if (pkgSetting == null) {
8157                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8158                        "Creating application package " + pkg.packageName + " failed");
8159            }
8160
8161            if (pkgSetting.origPackage != null) {
8162                // If we are first transitioning from an original package,
8163                // fix up the new package's name now.  We need to do this after
8164                // looking up the package under its new name, so getPackageLP
8165                // can take care of fiddling things correctly.
8166                pkg.setPackageName(origPackage.name);
8167
8168                // File a report about this.
8169                String msg = "New package " + pkgSetting.realName
8170                        + " renamed to replace old package " + pkgSetting.name;
8171                reportSettingsProblem(Log.WARN, msg);
8172
8173                // Make a note of it.
8174                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8175                    mTransferedPackages.add(origPackage.name);
8176                }
8177
8178                // No longer need to retain this.
8179                pkgSetting.origPackage = null;
8180            }
8181
8182            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8183                // Make a note of it.
8184                mTransferedPackages.add(pkg.packageName);
8185            }
8186
8187            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8188                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8189            }
8190
8191            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8192                // Check all shared libraries and map to their actual file path.
8193                // We only do this here for apps not on a system dir, because those
8194                // are the only ones that can fail an install due to this.  We
8195                // will take care of the system apps by updating all of their
8196                // library paths after the scan is done.
8197                updateSharedLibrariesLPw(pkg, null);
8198            }
8199
8200            if (mFoundPolicyFile) {
8201                SELinuxMMAC.assignSeinfoValue(pkg);
8202            }
8203
8204            pkg.applicationInfo.uid = pkgSetting.appId;
8205            pkg.mExtras = pkgSetting;
8206            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8207                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8208                    // We just determined the app is signed correctly, so bring
8209                    // over the latest parsed certs.
8210                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8211                } else {
8212                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8213                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8214                                "Package " + pkg.packageName + " upgrade keys do not match the "
8215                                + "previously installed version");
8216                    } else {
8217                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8218                        String msg = "System package " + pkg.packageName
8219                            + " signature changed; retaining data.";
8220                        reportSettingsProblem(Log.WARN, msg);
8221                    }
8222                }
8223            } else {
8224                try {
8225                    verifySignaturesLP(pkgSetting, pkg);
8226                    // We just determined the app is signed correctly, so bring
8227                    // over the latest parsed certs.
8228                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8229                } catch (PackageManagerException e) {
8230                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8231                        throw e;
8232                    }
8233                    // The signature has changed, but this package is in the system
8234                    // image...  let's recover!
8235                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8236                    // However...  if this package is part of a shared user, but it
8237                    // doesn't match the signature of the shared user, let's fail.
8238                    // What this means is that you can't change the signatures
8239                    // associated with an overall shared user, which doesn't seem all
8240                    // that unreasonable.
8241                    if (pkgSetting.sharedUser != null) {
8242                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8243                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8244                            throw new PackageManagerException(
8245                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8246                                            "Signature mismatch for shared user: "
8247                                            + pkgSetting.sharedUser);
8248                        }
8249                    }
8250                    // File a report about this.
8251                    String msg = "System package " + pkg.packageName
8252                        + " signature changed; retaining data.";
8253                    reportSettingsProblem(Log.WARN, msg);
8254                }
8255            }
8256            // Verify that this new package doesn't have any content providers
8257            // that conflict with existing packages.  Only do this if the
8258            // package isn't already installed, since we don't want to break
8259            // things that are installed.
8260            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8261                final int N = pkg.providers.size();
8262                int i;
8263                for (i=0; i<N; i++) {
8264                    PackageParser.Provider p = pkg.providers.get(i);
8265                    if (p.info.authority != null) {
8266                        String names[] = p.info.authority.split(";");
8267                        for (int j = 0; j < names.length; j++) {
8268                            if (mProvidersByAuthority.containsKey(names[j])) {
8269                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8270                                final String otherPackageName =
8271                                        ((other != null && other.getComponentName() != null) ?
8272                                                other.getComponentName().getPackageName() : "?");
8273                                throw new PackageManagerException(
8274                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8275                                                "Can't install because provider name " + names[j]
8276                                                + " (in package " + pkg.applicationInfo.packageName
8277                                                + ") is already used by " + otherPackageName);
8278                            }
8279                        }
8280                    }
8281                }
8282            }
8283
8284            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8285                // This package wants to adopt ownership of permissions from
8286                // another package.
8287                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8288                    final String origName = pkg.mAdoptPermissions.get(i);
8289                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8290                    if (orig != null) {
8291                        if (verifyPackageUpdateLPr(orig, pkg)) {
8292                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8293                                    + pkg.packageName);
8294                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8295                        }
8296                    }
8297                }
8298            }
8299        }
8300
8301        final String pkgName = pkg.packageName;
8302
8303        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8304        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8305        pkg.applicationInfo.processName = fixProcessName(
8306                pkg.applicationInfo.packageName,
8307                pkg.applicationInfo.processName,
8308                pkg.applicationInfo.uid);
8309
8310        if (pkg != mPlatformPackage) {
8311            // Get all of our default paths setup
8312            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8313        }
8314
8315        final String path = scanFile.getPath();
8316        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8317
8318        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8319            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8320
8321            // Some system apps still use directory structure for native libraries
8322            // in which case we might end up not detecting abi solely based on apk
8323            // structure. Try to detect abi based on directory structure.
8324            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8325                    pkg.applicationInfo.primaryCpuAbi == null) {
8326                setBundledAppAbisAndRoots(pkg, pkgSetting);
8327                setNativeLibraryPaths(pkg);
8328            }
8329
8330        } else {
8331            if ((scanFlags & SCAN_MOVE) != 0) {
8332                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8333                // but we already have this packages package info in the PackageSetting. We just
8334                // use that and derive the native library path based on the new codepath.
8335                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8336                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8337            }
8338
8339            // Set native library paths again. For moves, the path will be updated based on the
8340            // ABIs we've determined above. For non-moves, the path will be updated based on the
8341            // ABIs we determined during compilation, but the path will depend on the final
8342            // package path (after the rename away from the stage path).
8343            setNativeLibraryPaths(pkg);
8344        }
8345
8346        // This is a special case for the "system" package, where the ABI is
8347        // dictated by the zygote configuration (and init.rc). We should keep track
8348        // of this ABI so that we can deal with "normal" applications that run under
8349        // the same UID correctly.
8350        if (mPlatformPackage == pkg) {
8351            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8352                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8353        }
8354
8355        // If there's a mismatch between the abi-override in the package setting
8356        // and the abiOverride specified for the install. Warn about this because we
8357        // would've already compiled the app without taking the package setting into
8358        // account.
8359        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8360            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8361                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8362                        " for package " + pkg.packageName);
8363            }
8364        }
8365
8366        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8367        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8368        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8369
8370        // Copy the derived override back to the parsed package, so that we can
8371        // update the package settings accordingly.
8372        pkg.cpuAbiOverride = cpuAbiOverride;
8373
8374        if (DEBUG_ABI_SELECTION) {
8375            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8376                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8377                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8378        }
8379
8380        // Push the derived path down into PackageSettings so we know what to
8381        // clean up at uninstall time.
8382        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8383
8384        if (DEBUG_ABI_SELECTION) {
8385            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8386                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8387                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8388        }
8389
8390        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8391            // We don't do this here during boot because we can do it all
8392            // at once after scanning all existing packages.
8393            //
8394            // We also do this *before* we perform dexopt on this package, so that
8395            // we can avoid redundant dexopts, and also to make sure we've got the
8396            // code and package path correct.
8397            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8398                    pkg, true /* boot complete */);
8399        }
8400
8401        if (mFactoryTest && pkg.requestedPermissions.contains(
8402                android.Manifest.permission.FACTORY_TEST)) {
8403            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8404        }
8405
8406        ArrayList<PackageParser.Package> clientLibPkgs = null;
8407
8408        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8409            if (nonMutatedPs != null) {
8410                synchronized (mPackages) {
8411                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8412                }
8413            }
8414            return pkg;
8415        }
8416
8417        // Only privileged apps and updated privileged apps can add child packages.
8418        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8419            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8420                throw new PackageManagerException("Only privileged apps and updated "
8421                        + "privileged apps can add child packages. Ignoring package "
8422                        + pkg.packageName);
8423            }
8424            final int childCount = pkg.childPackages.size();
8425            for (int i = 0; i < childCount; i++) {
8426                PackageParser.Package childPkg = pkg.childPackages.get(i);
8427                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8428                        childPkg.packageName)) {
8429                    throw new PackageManagerException("Cannot override a child package of "
8430                            + "another disabled system app. Ignoring package " + pkg.packageName);
8431                }
8432            }
8433        }
8434
8435        // writer
8436        synchronized (mPackages) {
8437            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8438                // Only system apps can add new shared libraries.
8439                if (pkg.libraryNames != null) {
8440                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8441                        String name = pkg.libraryNames.get(i);
8442                        boolean allowed = false;
8443                        if (pkg.isUpdatedSystemApp()) {
8444                            // New library entries can only be added through the
8445                            // system image.  This is important to get rid of a lot
8446                            // of nasty edge cases: for example if we allowed a non-
8447                            // system update of the app to add a library, then uninstalling
8448                            // the update would make the library go away, and assumptions
8449                            // we made such as through app install filtering would now
8450                            // have allowed apps on the device which aren't compatible
8451                            // with it.  Better to just have the restriction here, be
8452                            // conservative, and create many fewer cases that can negatively
8453                            // impact the user experience.
8454                            final PackageSetting sysPs = mSettings
8455                                    .getDisabledSystemPkgLPr(pkg.packageName);
8456                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8457                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8458                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8459                                        allowed = true;
8460                                        break;
8461                                    }
8462                                }
8463                            }
8464                        } else {
8465                            allowed = true;
8466                        }
8467                        if (allowed) {
8468                            if (!mSharedLibraries.containsKey(name)) {
8469                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8470                            } else if (!name.equals(pkg.packageName)) {
8471                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8472                                        + name + " already exists; skipping");
8473                            }
8474                        } else {
8475                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8476                                    + name + " that is not declared on system image; skipping");
8477                        }
8478                    }
8479                    if ((scanFlags & SCAN_BOOTING) == 0) {
8480                        // If we are not booting, we need to update any applications
8481                        // that are clients of our shared library.  If we are booting,
8482                        // this will all be done once the scan is complete.
8483                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8484                    }
8485                }
8486            }
8487        }
8488
8489        if ((scanFlags & SCAN_BOOTING) != 0) {
8490            // No apps can run during boot scan, so they don't need to be frozen
8491        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8492            // Caller asked to not kill app, so it's probably not frozen
8493        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8494            // Caller asked us to ignore frozen check for some reason; they
8495            // probably didn't know the package name
8496        } else {
8497            // We're doing major surgery on this package, so it better be frozen
8498            // right now to keep it from launching
8499            checkPackageFrozen(pkgName);
8500        }
8501
8502        // Also need to kill any apps that are dependent on the library.
8503        if (clientLibPkgs != null) {
8504            for (int i=0; i<clientLibPkgs.size(); i++) {
8505                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8506                killApplication(clientPkg.applicationInfo.packageName,
8507                        clientPkg.applicationInfo.uid, "update lib");
8508            }
8509        }
8510
8511        // Make sure we're not adding any bogus keyset info
8512        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8513        ksms.assertScannedPackageValid(pkg);
8514
8515        // writer
8516        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8517
8518        boolean createIdmapFailed = false;
8519        synchronized (mPackages) {
8520            // We don't expect installation to fail beyond this point
8521
8522            if (pkgSetting.pkg != null) {
8523                // Note that |user| might be null during the initial boot scan. If a codePath
8524                // for an app has changed during a boot scan, it's due to an app update that's
8525                // part of the system partition and marker changes must be applied to all users.
8526                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8527                    (user != null) ? user : UserHandle.ALL);
8528            }
8529
8530            // Add the new setting to mSettings
8531            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8532            // Add the new setting to mPackages
8533            mPackages.put(pkg.applicationInfo.packageName, pkg);
8534            // Make sure we don't accidentally delete its data.
8535            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8536            while (iter.hasNext()) {
8537                PackageCleanItem item = iter.next();
8538                if (pkgName.equals(item.packageName)) {
8539                    iter.remove();
8540                }
8541            }
8542
8543            // Take care of first install / last update times.
8544            if (currentTime != 0) {
8545                if (pkgSetting.firstInstallTime == 0) {
8546                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8547                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8548                    pkgSetting.lastUpdateTime = currentTime;
8549                }
8550            } else if (pkgSetting.firstInstallTime == 0) {
8551                // We need *something*.  Take time time stamp of the file.
8552                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8553            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8554                if (scanFileTime != pkgSetting.timeStamp) {
8555                    // A package on the system image has changed; consider this
8556                    // to be an update.
8557                    pkgSetting.lastUpdateTime = scanFileTime;
8558                }
8559            }
8560
8561            // Add the package's KeySets to the global KeySetManagerService
8562            ksms.addScannedPackageLPw(pkg);
8563
8564            int N = pkg.providers.size();
8565            StringBuilder r = null;
8566            int i;
8567            for (i=0; i<N; i++) {
8568                PackageParser.Provider p = pkg.providers.get(i);
8569                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8570                        p.info.processName, pkg.applicationInfo.uid);
8571                mProviders.addProvider(p);
8572                p.syncable = p.info.isSyncable;
8573                if (p.info.authority != null) {
8574                    String names[] = p.info.authority.split(";");
8575                    p.info.authority = null;
8576                    for (int j = 0; j < names.length; j++) {
8577                        if (j == 1 && p.syncable) {
8578                            // We only want the first authority for a provider to possibly be
8579                            // syncable, so if we already added this provider using a different
8580                            // authority clear the syncable flag. We copy the provider before
8581                            // changing it because the mProviders object contains a reference
8582                            // to a provider that we don't want to change.
8583                            // Only do this for the second authority since the resulting provider
8584                            // object can be the same for all future authorities for this provider.
8585                            p = new PackageParser.Provider(p);
8586                            p.syncable = false;
8587                        }
8588                        if (!mProvidersByAuthority.containsKey(names[j])) {
8589                            mProvidersByAuthority.put(names[j], p);
8590                            if (p.info.authority == null) {
8591                                p.info.authority = names[j];
8592                            } else {
8593                                p.info.authority = p.info.authority + ";" + names[j];
8594                            }
8595                            if (DEBUG_PACKAGE_SCANNING) {
8596                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8597                                    Log.d(TAG, "Registered content provider: " + names[j]
8598                                            + ", className = " + p.info.name + ", isSyncable = "
8599                                            + p.info.isSyncable);
8600                            }
8601                        } else {
8602                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8603                            Slog.w(TAG, "Skipping provider name " + names[j] +
8604                                    " (in package " + pkg.applicationInfo.packageName +
8605                                    "): name already used by "
8606                                    + ((other != null && other.getComponentName() != null)
8607                                            ? other.getComponentName().getPackageName() : "?"));
8608                        }
8609                    }
8610                }
8611                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8612                    if (r == null) {
8613                        r = new StringBuilder(256);
8614                    } else {
8615                        r.append(' ');
8616                    }
8617                    r.append(p.info.name);
8618                }
8619            }
8620            if (r != null) {
8621                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8622            }
8623
8624            N = pkg.services.size();
8625            r = null;
8626            for (i=0; i<N; i++) {
8627                PackageParser.Service s = pkg.services.get(i);
8628                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8629                        s.info.processName, pkg.applicationInfo.uid);
8630                mServices.addService(s);
8631                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8632                    if (r == null) {
8633                        r = new StringBuilder(256);
8634                    } else {
8635                        r.append(' ');
8636                    }
8637                    r.append(s.info.name);
8638                }
8639            }
8640            if (r != null) {
8641                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8642            }
8643
8644            N = pkg.receivers.size();
8645            r = null;
8646            for (i=0; i<N; i++) {
8647                PackageParser.Activity a = pkg.receivers.get(i);
8648                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8649                        a.info.processName, pkg.applicationInfo.uid);
8650                mReceivers.addActivity(a, "receiver");
8651                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8652                    if (r == null) {
8653                        r = new StringBuilder(256);
8654                    } else {
8655                        r.append(' ');
8656                    }
8657                    r.append(a.info.name);
8658                }
8659            }
8660            if (r != null) {
8661                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8662            }
8663
8664            N = pkg.activities.size();
8665            r = null;
8666            for (i=0; i<N; i++) {
8667                PackageParser.Activity a = pkg.activities.get(i);
8668                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8669                        a.info.processName, pkg.applicationInfo.uid);
8670                mActivities.addActivity(a, "activity");
8671                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8672                    if (r == null) {
8673                        r = new StringBuilder(256);
8674                    } else {
8675                        r.append(' ');
8676                    }
8677                    r.append(a.info.name);
8678                }
8679            }
8680            if (r != null) {
8681                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8682            }
8683
8684            N = pkg.permissionGroups.size();
8685            r = null;
8686            for (i=0; i<N; i++) {
8687                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8688                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8689                if (cur == null) {
8690                    mPermissionGroups.put(pg.info.name, pg);
8691                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8692                        if (r == null) {
8693                            r = new StringBuilder(256);
8694                        } else {
8695                            r.append(' ');
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 = 1;
9237        mEphemeralInstallerInfo.isDefault = true;
9238        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9239                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9240
9241        if (DEBUG_EPHEMERAL) {
9242            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9243        }
9244    }
9245
9246    private static String calculateBundledApkRoot(final String codePathString) {
9247        final File codePath = new File(codePathString);
9248        final File codeRoot;
9249        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9250            codeRoot = Environment.getRootDirectory();
9251        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9252            codeRoot = Environment.getOemDirectory();
9253        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9254            codeRoot = Environment.getVendorDirectory();
9255        } else {
9256            // Unrecognized code path; take its top real segment as the apk root:
9257            // e.g. /something/app/blah.apk => /something
9258            try {
9259                File f = codePath.getCanonicalFile();
9260                File parent = f.getParentFile();    // non-null because codePath is a file
9261                File tmp;
9262                while ((tmp = parent.getParentFile()) != null) {
9263                    f = parent;
9264                    parent = tmp;
9265                }
9266                codeRoot = f;
9267                Slog.w(TAG, "Unrecognized code path "
9268                        + codePath + " - using " + codeRoot);
9269            } catch (IOException e) {
9270                // Can't canonicalize the code path -- shenanigans?
9271                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9272                return Environment.getRootDirectory().getPath();
9273            }
9274        }
9275        return codeRoot.getPath();
9276    }
9277
9278    /**
9279     * Derive and set the location of native libraries for the given package,
9280     * which varies depending on where and how the package was installed.
9281     */
9282    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9283        final ApplicationInfo info = pkg.applicationInfo;
9284        final String codePath = pkg.codePath;
9285        final File codeFile = new File(codePath);
9286        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9287        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9288
9289        info.nativeLibraryRootDir = null;
9290        info.nativeLibraryRootRequiresIsa = false;
9291        info.nativeLibraryDir = null;
9292        info.secondaryNativeLibraryDir = null;
9293
9294        if (isApkFile(codeFile)) {
9295            // Monolithic install
9296            if (bundledApp) {
9297                // If "/system/lib64/apkname" exists, assume that is the per-package
9298                // native library directory to use; otherwise use "/system/lib/apkname".
9299                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9300                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9301                        getPrimaryInstructionSet(info));
9302
9303                // This is a bundled system app so choose the path based on the ABI.
9304                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9305                // is just the default path.
9306                final String apkName = deriveCodePathName(codePath);
9307                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9308                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9309                        apkName).getAbsolutePath();
9310
9311                if (info.secondaryCpuAbi != null) {
9312                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9313                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9314                            secondaryLibDir, apkName).getAbsolutePath();
9315                }
9316            } else if (asecApp) {
9317                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9318                        .getAbsolutePath();
9319            } else {
9320                final String apkName = deriveCodePathName(codePath);
9321                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9322                        .getAbsolutePath();
9323            }
9324
9325            info.nativeLibraryRootRequiresIsa = false;
9326            info.nativeLibraryDir = info.nativeLibraryRootDir;
9327        } else {
9328            // Cluster install
9329            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9330            info.nativeLibraryRootRequiresIsa = true;
9331
9332            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9333                    getPrimaryInstructionSet(info)).getAbsolutePath();
9334
9335            if (info.secondaryCpuAbi != null) {
9336                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9337                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9338            }
9339        }
9340    }
9341
9342    /**
9343     * Calculate the abis and roots for a bundled app. These can uniquely
9344     * be determined from the contents of the system partition, i.e whether
9345     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9346     * of this information, and instead assume that the system was built
9347     * sensibly.
9348     */
9349    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9350                                           PackageSetting pkgSetting) {
9351        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9352
9353        // If "/system/lib64/apkname" exists, assume that is the per-package
9354        // native library directory to use; otherwise use "/system/lib/apkname".
9355        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9356        setBundledAppAbi(pkg, apkRoot, apkName);
9357        // pkgSetting might be null during rescan following uninstall of updates
9358        // to a bundled app, so accommodate that possibility.  The settings in
9359        // that case will be established later from the parsed package.
9360        //
9361        // If the settings aren't null, sync them up with what we've just derived.
9362        // note that apkRoot isn't stored in the package settings.
9363        if (pkgSetting != null) {
9364            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9365            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9366        }
9367    }
9368
9369    /**
9370     * Deduces the ABI of a bundled app and sets the relevant fields on the
9371     * parsed pkg object.
9372     *
9373     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9374     *        under which system libraries are installed.
9375     * @param apkName the name of the installed package.
9376     */
9377    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9378        final File codeFile = new File(pkg.codePath);
9379
9380        final boolean has64BitLibs;
9381        final boolean has32BitLibs;
9382        if (isApkFile(codeFile)) {
9383            // Monolithic install
9384            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9385            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9386        } else {
9387            // Cluster install
9388            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9389            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9390                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9391                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9392                has64BitLibs = (new File(rootDir, isa)).exists();
9393            } else {
9394                has64BitLibs = false;
9395            }
9396            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9397                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9398                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9399                has32BitLibs = (new File(rootDir, isa)).exists();
9400            } else {
9401                has32BitLibs = false;
9402            }
9403        }
9404
9405        if (has64BitLibs && !has32BitLibs) {
9406            // The package has 64 bit libs, but not 32 bit libs. Its primary
9407            // ABI should be 64 bit. We can safely assume here that the bundled
9408            // native libraries correspond to the most preferred ABI in the list.
9409
9410            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9411            pkg.applicationInfo.secondaryCpuAbi = null;
9412        } else if (has32BitLibs && !has64BitLibs) {
9413            // The package has 32 bit libs but not 64 bit libs. Its primary
9414            // ABI should be 32 bit.
9415
9416            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9417            pkg.applicationInfo.secondaryCpuAbi = null;
9418        } else if (has32BitLibs && has64BitLibs) {
9419            // The application has both 64 and 32 bit bundled libraries. We check
9420            // here that the app declares multiArch support, and warn if it doesn't.
9421            //
9422            // We will be lenient here and record both ABIs. The primary will be the
9423            // ABI that's higher on the list, i.e, a device that's configured to prefer
9424            // 64 bit apps will see a 64 bit primary ABI,
9425
9426            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9427                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9428            }
9429
9430            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9431                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9432                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9433            } else {
9434                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9435                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9436            }
9437        } else {
9438            pkg.applicationInfo.primaryCpuAbi = null;
9439            pkg.applicationInfo.secondaryCpuAbi = null;
9440        }
9441    }
9442
9443    private void killApplication(String pkgName, int appId, String reason) {
9444        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9445    }
9446
9447    private void killApplication(String pkgName, int appId, int userId, String reason) {
9448        // Request the ActivityManager to kill the process(only for existing packages)
9449        // so that we do not end up in a confused state while the user is still using the older
9450        // version of the application while the new one gets installed.
9451        final long token = Binder.clearCallingIdentity();
9452        try {
9453            IActivityManager am = ActivityManagerNative.getDefault();
9454            if (am != null) {
9455                try {
9456                    am.killApplication(pkgName, appId, userId, reason);
9457                } catch (RemoteException e) {
9458                }
9459            }
9460        } finally {
9461            Binder.restoreCallingIdentity(token);
9462        }
9463    }
9464
9465    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9466        // Remove the parent package setting
9467        PackageSetting ps = (PackageSetting) pkg.mExtras;
9468        if (ps != null) {
9469            removePackageLI(ps, chatty);
9470        }
9471        // Remove the child package setting
9472        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9473        for (int i = 0; i < childCount; i++) {
9474            PackageParser.Package childPkg = pkg.childPackages.get(i);
9475            ps = (PackageSetting) childPkg.mExtras;
9476            if (ps != null) {
9477                removePackageLI(ps, chatty);
9478            }
9479        }
9480    }
9481
9482    void removePackageLI(PackageSetting ps, boolean chatty) {
9483        if (DEBUG_INSTALL) {
9484            if (chatty)
9485                Log.d(TAG, "Removing package " + ps.name);
9486        }
9487
9488        // writer
9489        synchronized (mPackages) {
9490            mPackages.remove(ps.name);
9491            final PackageParser.Package pkg = ps.pkg;
9492            if (pkg != null) {
9493                cleanPackageDataStructuresLILPw(pkg, chatty);
9494            }
9495        }
9496    }
9497
9498    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9499        if (DEBUG_INSTALL) {
9500            if (chatty)
9501                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9502        }
9503
9504        // writer
9505        synchronized (mPackages) {
9506            // Remove the parent package
9507            mPackages.remove(pkg.applicationInfo.packageName);
9508            cleanPackageDataStructuresLILPw(pkg, chatty);
9509
9510            // Remove the child packages
9511            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9512            for (int i = 0; i < childCount; i++) {
9513                PackageParser.Package childPkg = pkg.childPackages.get(i);
9514                mPackages.remove(childPkg.applicationInfo.packageName);
9515                cleanPackageDataStructuresLILPw(childPkg, chatty);
9516            }
9517        }
9518    }
9519
9520    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9521        int N = pkg.providers.size();
9522        StringBuilder r = null;
9523        int i;
9524        for (i=0; i<N; i++) {
9525            PackageParser.Provider p = pkg.providers.get(i);
9526            mProviders.removeProvider(p);
9527            if (p.info.authority == null) {
9528
9529                /* There was another ContentProvider with this authority when
9530                 * this app was installed so this authority is null,
9531                 * Ignore it as we don't have to unregister the provider.
9532                 */
9533                continue;
9534            }
9535            String names[] = p.info.authority.split(";");
9536            for (int j = 0; j < names.length; j++) {
9537                if (mProvidersByAuthority.get(names[j]) == p) {
9538                    mProvidersByAuthority.remove(names[j]);
9539                    if (DEBUG_REMOVE) {
9540                        if (chatty)
9541                            Log.d(TAG, "Unregistered content provider: " + names[j]
9542                                    + ", className = " + p.info.name + ", isSyncable = "
9543                                    + p.info.isSyncable);
9544                    }
9545                }
9546            }
9547            if (DEBUG_REMOVE && chatty) {
9548                if (r == null) {
9549                    r = new StringBuilder(256);
9550                } else {
9551                    r.append(' ');
9552                }
9553                r.append(p.info.name);
9554            }
9555        }
9556        if (r != null) {
9557            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9558        }
9559
9560        N = pkg.services.size();
9561        r = null;
9562        for (i=0; i<N; i++) {
9563            PackageParser.Service s = pkg.services.get(i);
9564            mServices.removeService(s);
9565            if (chatty) {
9566                if (r == null) {
9567                    r = new StringBuilder(256);
9568                } else {
9569                    r.append(' ');
9570                }
9571                r.append(s.info.name);
9572            }
9573        }
9574        if (r != null) {
9575            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9576        }
9577
9578        N = pkg.receivers.size();
9579        r = null;
9580        for (i=0; i<N; i++) {
9581            PackageParser.Activity a = pkg.receivers.get(i);
9582            mReceivers.removeActivity(a, "receiver");
9583            if (DEBUG_REMOVE && chatty) {
9584                if (r == null) {
9585                    r = new StringBuilder(256);
9586                } else {
9587                    r.append(' ');
9588                }
9589                r.append(a.info.name);
9590            }
9591        }
9592        if (r != null) {
9593            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9594        }
9595
9596        N = pkg.activities.size();
9597        r = null;
9598        for (i=0; i<N; i++) {
9599            PackageParser.Activity a = pkg.activities.get(i);
9600            mActivities.removeActivity(a, "activity");
9601            if (DEBUG_REMOVE && chatty) {
9602                if (r == null) {
9603                    r = new StringBuilder(256);
9604                } else {
9605                    r.append(' ');
9606                }
9607                r.append(a.info.name);
9608            }
9609        }
9610        if (r != null) {
9611            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9612        }
9613
9614        N = pkg.permissions.size();
9615        r = null;
9616        for (i=0; i<N; i++) {
9617            PackageParser.Permission p = pkg.permissions.get(i);
9618            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9619            if (bp == null) {
9620                bp = mSettings.mPermissionTrees.get(p.info.name);
9621            }
9622            if (bp != null && bp.perm == p) {
9623                bp.perm = null;
9624                if (DEBUG_REMOVE && chatty) {
9625                    if (r == null) {
9626                        r = new StringBuilder(256);
9627                    } else {
9628                        r.append(' ');
9629                    }
9630                    r.append(p.info.name);
9631                }
9632            }
9633            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9634                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9635                if (appOpPkgs != null) {
9636                    appOpPkgs.remove(pkg.packageName);
9637                }
9638            }
9639        }
9640        if (r != null) {
9641            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9642        }
9643
9644        N = pkg.requestedPermissions.size();
9645        r = null;
9646        for (i=0; i<N; i++) {
9647            String perm = pkg.requestedPermissions.get(i);
9648            BasePermission bp = mSettings.mPermissions.get(perm);
9649            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9650                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9651                if (appOpPkgs != null) {
9652                    appOpPkgs.remove(pkg.packageName);
9653                    if (appOpPkgs.isEmpty()) {
9654                        mAppOpPermissionPackages.remove(perm);
9655                    }
9656                }
9657            }
9658        }
9659        if (r != null) {
9660            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9661        }
9662
9663        N = pkg.instrumentation.size();
9664        r = null;
9665        for (i=0; i<N; i++) {
9666            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9667            mInstrumentation.remove(a.getComponentName());
9668            if (DEBUG_REMOVE && chatty) {
9669                if (r == null) {
9670                    r = new StringBuilder(256);
9671                } else {
9672                    r.append(' ');
9673                }
9674                r.append(a.info.name);
9675            }
9676        }
9677        if (r != null) {
9678            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9679        }
9680
9681        r = null;
9682        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9683            // Only system apps can hold shared libraries.
9684            if (pkg.libraryNames != null) {
9685                for (i=0; i<pkg.libraryNames.size(); i++) {
9686                    String name = pkg.libraryNames.get(i);
9687                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9688                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9689                        mSharedLibraries.remove(name);
9690                        if (DEBUG_REMOVE && chatty) {
9691                            if (r == null) {
9692                                r = new StringBuilder(256);
9693                            } else {
9694                                r.append(' ');
9695                            }
9696                            r.append(name);
9697                        }
9698                    }
9699                }
9700            }
9701        }
9702        if (r != null) {
9703            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9704        }
9705    }
9706
9707    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9708        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9709            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9710                return true;
9711            }
9712        }
9713        return false;
9714    }
9715
9716    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9717    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9718    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9719
9720    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9721        // Update the parent permissions
9722        updatePermissionsLPw(pkg.packageName, pkg, flags);
9723        // Update the child permissions
9724        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9725        for (int i = 0; i < childCount; i++) {
9726            PackageParser.Package childPkg = pkg.childPackages.get(i);
9727            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9728        }
9729    }
9730
9731    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9732            int flags) {
9733        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9734        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9735    }
9736
9737    private void updatePermissionsLPw(String changingPkg,
9738            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9739        // Make sure there are no dangling permission trees.
9740        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9741        while (it.hasNext()) {
9742            final BasePermission bp = it.next();
9743            if (bp.packageSetting == null) {
9744                // We may not yet have parsed the package, so just see if
9745                // we still know about its settings.
9746                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9747            }
9748            if (bp.packageSetting == null) {
9749                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9750                        + " from package " + bp.sourcePackage);
9751                it.remove();
9752            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9753                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9754                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9755                            + " from package " + bp.sourcePackage);
9756                    flags |= UPDATE_PERMISSIONS_ALL;
9757                    it.remove();
9758                }
9759            }
9760        }
9761
9762        // Make sure all dynamic permissions have been assigned to a package,
9763        // and make sure there are no dangling permissions.
9764        it = mSettings.mPermissions.values().iterator();
9765        while (it.hasNext()) {
9766            final BasePermission bp = it.next();
9767            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9768                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9769                        + bp.name + " pkg=" + bp.sourcePackage
9770                        + " info=" + bp.pendingInfo);
9771                if (bp.packageSetting == null && bp.pendingInfo != null) {
9772                    final BasePermission tree = findPermissionTreeLP(bp.name);
9773                    if (tree != null && tree.perm != null) {
9774                        bp.packageSetting = tree.packageSetting;
9775                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9776                                new PermissionInfo(bp.pendingInfo));
9777                        bp.perm.info.packageName = tree.perm.info.packageName;
9778                        bp.perm.info.name = bp.name;
9779                        bp.uid = tree.uid;
9780                    }
9781                }
9782            }
9783            if (bp.packageSetting == null) {
9784                // We may not yet have parsed the package, so just see if
9785                // we still know about its settings.
9786                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9787            }
9788            if (bp.packageSetting == null) {
9789                Slog.w(TAG, "Removing dangling permission: " + bp.name
9790                        + " from package " + bp.sourcePackage);
9791                it.remove();
9792            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9793                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9794                    Slog.i(TAG, "Removing old permission: " + bp.name
9795                            + " from package " + bp.sourcePackage);
9796                    flags |= UPDATE_PERMISSIONS_ALL;
9797                    it.remove();
9798                }
9799            }
9800        }
9801
9802        // Now update the permissions for all packages, in particular
9803        // replace the granted permissions of the system packages.
9804        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9805            for (PackageParser.Package pkg : mPackages.values()) {
9806                if (pkg != pkgInfo) {
9807                    // Only replace for packages on requested volume
9808                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9809                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9810                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9811                    grantPermissionsLPw(pkg, replace, changingPkg);
9812                }
9813            }
9814        }
9815
9816        if (pkgInfo != null) {
9817            // Only replace for packages on requested volume
9818            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9819            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9820                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9821            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9822        }
9823    }
9824
9825    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9826            String packageOfInterest) {
9827        // IMPORTANT: There are two types of permissions: install and runtime.
9828        // Install time permissions are granted when the app is installed to
9829        // all device users and users added in the future. Runtime permissions
9830        // are granted at runtime explicitly to specific users. Normal and signature
9831        // protected permissions are install time permissions. Dangerous permissions
9832        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9833        // otherwise they are runtime permissions. This function does not manage
9834        // runtime permissions except for the case an app targeting Lollipop MR1
9835        // being upgraded to target a newer SDK, in which case dangerous permissions
9836        // are transformed from install time to runtime ones.
9837
9838        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9839        if (ps == null) {
9840            return;
9841        }
9842
9843        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9844
9845        PermissionsState permissionsState = ps.getPermissionsState();
9846        PermissionsState origPermissions = permissionsState;
9847
9848        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9849
9850        boolean runtimePermissionsRevoked = false;
9851        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9852
9853        boolean changedInstallPermission = false;
9854
9855        if (replace) {
9856            ps.installPermissionsFixed = false;
9857            if (!ps.isSharedUser()) {
9858                origPermissions = new PermissionsState(permissionsState);
9859                permissionsState.reset();
9860            } else {
9861                // We need to know only about runtime permission changes since the
9862                // calling code always writes the install permissions state but
9863                // the runtime ones are written only if changed. The only cases of
9864                // changed runtime permissions here are promotion of an install to
9865                // runtime and revocation of a runtime from a shared user.
9866                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9867                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9868                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9869                    runtimePermissionsRevoked = true;
9870                }
9871            }
9872        }
9873
9874        permissionsState.setGlobalGids(mGlobalGids);
9875
9876        final int N = pkg.requestedPermissions.size();
9877        for (int i=0; i<N; i++) {
9878            final String name = pkg.requestedPermissions.get(i);
9879            final BasePermission bp = mSettings.mPermissions.get(name);
9880
9881            if (DEBUG_INSTALL) {
9882                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9883            }
9884
9885            if (bp == null || bp.packageSetting == null) {
9886                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9887                    Slog.w(TAG, "Unknown permission " + name
9888                            + " in package " + pkg.packageName);
9889                }
9890                continue;
9891            }
9892
9893            final String perm = bp.name;
9894            boolean allowedSig = false;
9895            int grant = GRANT_DENIED;
9896
9897            // Keep track of app op permissions.
9898            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9899                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9900                if (pkgs == null) {
9901                    pkgs = new ArraySet<>();
9902                    mAppOpPermissionPackages.put(bp.name, pkgs);
9903                }
9904                pkgs.add(pkg.packageName);
9905            }
9906
9907            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9908            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9909                    >= Build.VERSION_CODES.M;
9910            switch (level) {
9911                case PermissionInfo.PROTECTION_NORMAL: {
9912                    // For all apps normal permissions are install time ones.
9913                    grant = GRANT_INSTALL;
9914                } break;
9915
9916                case PermissionInfo.PROTECTION_DANGEROUS: {
9917                    // If a permission review is required for legacy apps we represent
9918                    // their permissions as always granted runtime ones since we need
9919                    // to keep the review required permission flag per user while an
9920                    // install permission's state is shared across all users.
9921                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9922                        // For legacy apps dangerous permissions are install time ones.
9923                        grant = GRANT_INSTALL;
9924                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9925                        // For legacy apps that became modern, install becomes runtime.
9926                        grant = GRANT_UPGRADE;
9927                    } else if (mPromoteSystemApps
9928                            && isSystemApp(ps)
9929                            && mExistingSystemPackages.contains(ps.name)) {
9930                        // For legacy system apps, install becomes runtime.
9931                        // We cannot check hasInstallPermission() for system apps since those
9932                        // permissions were granted implicitly and not persisted pre-M.
9933                        grant = GRANT_UPGRADE;
9934                    } else {
9935                        // For modern apps keep runtime permissions unchanged.
9936                        grant = GRANT_RUNTIME;
9937                    }
9938                } break;
9939
9940                case PermissionInfo.PROTECTION_SIGNATURE: {
9941                    // For all apps signature permissions are install time ones.
9942                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9943                    if (allowedSig) {
9944                        grant = GRANT_INSTALL;
9945                    }
9946                } break;
9947            }
9948
9949            if (DEBUG_INSTALL) {
9950                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9951            }
9952
9953            if (grant != GRANT_DENIED) {
9954                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9955                    // If this is an existing, non-system package, then
9956                    // we can't add any new permissions to it.
9957                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9958                        // Except...  if this is a permission that was added
9959                        // to the platform (note: need to only do this when
9960                        // updating the platform).
9961                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9962                            grant = GRANT_DENIED;
9963                        }
9964                    }
9965                }
9966
9967                switch (grant) {
9968                    case GRANT_INSTALL: {
9969                        // Revoke this as runtime permission to handle the case of
9970                        // a runtime permission being downgraded to an install one.
9971                        // Also in permission review mode we keep dangerous permissions
9972                        // for legacy apps
9973                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9974                            if (origPermissions.getRuntimePermissionState(
9975                                    bp.name, userId) != null) {
9976                                // Revoke the runtime permission and clear the flags.
9977                                origPermissions.revokeRuntimePermission(bp, userId);
9978                                origPermissions.updatePermissionFlags(bp, userId,
9979                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9980                                // If we revoked a permission permission, we have to write.
9981                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9982                                        changedRuntimePermissionUserIds, userId);
9983                            }
9984                        }
9985                        // Grant an install permission.
9986                        if (permissionsState.grantInstallPermission(bp) !=
9987                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9988                            changedInstallPermission = true;
9989                        }
9990                    } break;
9991
9992                    case GRANT_RUNTIME: {
9993                        // Grant previously granted runtime permissions.
9994                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9995                            PermissionState permissionState = origPermissions
9996                                    .getRuntimePermissionState(bp.name, userId);
9997                            int flags = permissionState != null
9998                                    ? permissionState.getFlags() : 0;
9999                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10000                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10001                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10002                                    // If we cannot put the permission as it was, we have to write.
10003                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10004                                            changedRuntimePermissionUserIds, userId);
10005                                }
10006                                // If the app supports runtime permissions no need for a review.
10007                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10008                                        && appSupportsRuntimePermissions
10009                                        && (flags & PackageManager
10010                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10011                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10012                                    // Since we changed the flags, we have to write.
10013                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10014                                            changedRuntimePermissionUserIds, userId);
10015                                }
10016                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10017                                    && !appSupportsRuntimePermissions) {
10018                                // For legacy apps that need a permission review, every new
10019                                // runtime permission is granted but it is pending a review.
10020                                // We also need to review only platform defined runtime
10021                                // permissions as these are the only ones the platform knows
10022                                // how to disable the API to simulate revocation as legacy
10023                                // apps don't expect to run with revoked permissions.
10024                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10025                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10026                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10027                                        // We changed the flags, hence have to write.
10028                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10029                                                changedRuntimePermissionUserIds, userId);
10030                                    }
10031                                }
10032                                if (permissionsState.grantRuntimePermission(bp, userId)
10033                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10034                                    // We changed the permission, hence have to write.
10035                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10036                                            changedRuntimePermissionUserIds, userId);
10037                                }
10038                            }
10039                            // Propagate the permission flags.
10040                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10041                        }
10042                    } break;
10043
10044                    case GRANT_UPGRADE: {
10045                        // Grant runtime permissions for a previously held install permission.
10046                        PermissionState permissionState = origPermissions
10047                                .getInstallPermissionState(bp.name);
10048                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10049
10050                        if (origPermissions.revokeInstallPermission(bp)
10051                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10052                            // We will be transferring the permission flags, so clear them.
10053                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10054                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10055                            changedInstallPermission = true;
10056                        }
10057
10058                        // If the permission is not to be promoted to runtime we ignore it and
10059                        // also its other flags as they are not applicable to install permissions.
10060                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10061                            for (int userId : currentUserIds) {
10062                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10063                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10064                                    // Transfer the permission flags.
10065                                    permissionsState.updatePermissionFlags(bp, userId,
10066                                            flags, flags);
10067                                    // If we granted the permission, we have to write.
10068                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10069                                            changedRuntimePermissionUserIds, userId);
10070                                }
10071                            }
10072                        }
10073                    } break;
10074
10075                    default: {
10076                        if (packageOfInterest == null
10077                                || packageOfInterest.equals(pkg.packageName)) {
10078                            Slog.w(TAG, "Not granting permission " + perm
10079                                    + " to package " + pkg.packageName
10080                                    + " because it was previously installed without");
10081                        }
10082                    } break;
10083                }
10084            } else {
10085                if (permissionsState.revokeInstallPermission(bp) !=
10086                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10087                    // Also drop the permission flags.
10088                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10089                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10090                    changedInstallPermission = true;
10091                    Slog.i(TAG, "Un-granting permission " + perm
10092                            + " from package " + pkg.packageName
10093                            + " (protectionLevel=" + bp.protectionLevel
10094                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10095                            + ")");
10096                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10097                    // Don't print warning for app op permissions, since it is fine for them
10098                    // not to be granted, there is a UI for the user to decide.
10099                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10100                        Slog.w(TAG, "Not granting permission " + perm
10101                                + " to package " + pkg.packageName
10102                                + " (protectionLevel=" + bp.protectionLevel
10103                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10104                                + ")");
10105                    }
10106                }
10107            }
10108        }
10109
10110        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10111                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10112            // This is the first that we have heard about this package, so the
10113            // permissions we have now selected are fixed until explicitly
10114            // changed.
10115            ps.installPermissionsFixed = true;
10116        }
10117
10118        // Persist the runtime permissions state for users with changes. If permissions
10119        // were revoked because no app in the shared user declares them we have to
10120        // write synchronously to avoid losing runtime permissions state.
10121        for (int userId : changedRuntimePermissionUserIds) {
10122            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10123        }
10124
10125        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10126    }
10127
10128    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10129        boolean allowed = false;
10130        final int NP = PackageParser.NEW_PERMISSIONS.length;
10131        for (int ip=0; ip<NP; ip++) {
10132            final PackageParser.NewPermissionInfo npi
10133                    = PackageParser.NEW_PERMISSIONS[ip];
10134            if (npi.name.equals(perm)
10135                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10136                allowed = true;
10137                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10138                        + pkg.packageName);
10139                break;
10140            }
10141        }
10142        return allowed;
10143    }
10144
10145    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10146            BasePermission bp, PermissionsState origPermissions) {
10147        boolean allowed;
10148        allowed = (compareSignatures(
10149                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10150                        == PackageManager.SIGNATURE_MATCH)
10151                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10152                        == PackageManager.SIGNATURE_MATCH);
10153        if (!allowed && (bp.protectionLevel
10154                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10155            if (isSystemApp(pkg)) {
10156                // For updated system applications, a system permission
10157                // is granted only if it had been defined by the original application.
10158                if (pkg.isUpdatedSystemApp()) {
10159                    final PackageSetting sysPs = mSettings
10160                            .getDisabledSystemPkgLPr(pkg.packageName);
10161                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10162                        // If the original was granted this permission, we take
10163                        // that grant decision as read and propagate it to the
10164                        // update.
10165                        if (sysPs.isPrivileged()) {
10166                            allowed = true;
10167                        }
10168                    } else {
10169                        // The system apk may have been updated with an older
10170                        // version of the one on the data partition, but which
10171                        // granted a new system permission that it didn't have
10172                        // before.  In this case we do want to allow the app to
10173                        // now get the new permission if the ancestral apk is
10174                        // privileged to get it.
10175                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10176                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10177                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10178                                    allowed = true;
10179                                    break;
10180                                }
10181                            }
10182                        }
10183                        // Also if a privileged parent package on the system image or any of
10184                        // its children requested a privileged permission, the updated child
10185                        // packages can also get the permission.
10186                        if (pkg.parentPackage != null) {
10187                            final PackageSetting disabledSysParentPs = mSettings
10188                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10189                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10190                                    && disabledSysParentPs.isPrivileged()) {
10191                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10192                                    allowed = true;
10193                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10194                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10195                                    for (int i = 0; i < count; i++) {
10196                                        PackageParser.Package disabledSysChildPkg =
10197                                                disabledSysParentPs.pkg.childPackages.get(i);
10198                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10199                                                perm)) {
10200                                            allowed = true;
10201                                            break;
10202                                        }
10203                                    }
10204                                }
10205                            }
10206                        }
10207                    }
10208                } else {
10209                    allowed = isPrivilegedApp(pkg);
10210                }
10211            }
10212        }
10213        if (!allowed) {
10214            if (!allowed && (bp.protectionLevel
10215                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10216                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10217                // If this was a previously normal/dangerous permission that got moved
10218                // to a system permission as part of the runtime permission redesign, then
10219                // we still want to blindly grant it to old apps.
10220                allowed = true;
10221            }
10222            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10223                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10224                // If this permission is to be granted to the system installer and
10225                // this app is an installer, then it gets the permission.
10226                allowed = true;
10227            }
10228            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10229                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10230                // If this permission is to be granted to the system verifier and
10231                // this app is a verifier, then it gets the permission.
10232                allowed = true;
10233            }
10234            if (!allowed && (bp.protectionLevel
10235                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10236                    && isSystemApp(pkg)) {
10237                // Any pre-installed system app is allowed to get this permission.
10238                allowed = true;
10239            }
10240            if (!allowed && (bp.protectionLevel
10241                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10242                // For development permissions, a development permission
10243                // is granted only if it was already granted.
10244                allowed = origPermissions.hasInstallPermission(perm);
10245            }
10246            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10247                    && pkg.packageName.equals(mSetupWizardPackage)) {
10248                // If this permission is to be granted to the system setup wizard and
10249                // this app is a setup wizard, then it gets the permission.
10250                allowed = true;
10251            }
10252        }
10253        return allowed;
10254    }
10255
10256    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10257        final int permCount = pkg.requestedPermissions.size();
10258        for (int j = 0; j < permCount; j++) {
10259            String requestedPermission = pkg.requestedPermissions.get(j);
10260            if (permission.equals(requestedPermission)) {
10261                return true;
10262            }
10263        }
10264        return false;
10265    }
10266
10267    final class ActivityIntentResolver
10268            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10269        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10270                boolean defaultOnly, int userId) {
10271            if (!sUserManager.exists(userId)) return null;
10272            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10273            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10274        }
10275
10276        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10277                int userId) {
10278            if (!sUserManager.exists(userId)) return null;
10279            mFlags = flags;
10280            return super.queryIntent(intent, resolvedType,
10281                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10282        }
10283
10284        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10285                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10286            if (!sUserManager.exists(userId)) return null;
10287            if (packageActivities == null) {
10288                return null;
10289            }
10290            mFlags = flags;
10291            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10292            final int N = packageActivities.size();
10293            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10294                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10295
10296            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10297            for (int i = 0; i < N; ++i) {
10298                intentFilters = packageActivities.get(i).intents;
10299                if (intentFilters != null && intentFilters.size() > 0) {
10300                    PackageParser.ActivityIntentInfo[] array =
10301                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10302                    intentFilters.toArray(array);
10303                    listCut.add(array);
10304                }
10305            }
10306            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10307        }
10308
10309        /**
10310         * Finds a privileged activity that matches the specified activity names.
10311         */
10312        private PackageParser.Activity findMatchingActivity(
10313                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10314            for (PackageParser.Activity sysActivity : activityList) {
10315                if (sysActivity.info.name.equals(activityInfo.name)) {
10316                    return sysActivity;
10317                }
10318                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10319                    return sysActivity;
10320                }
10321                if (sysActivity.info.targetActivity != null) {
10322                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10323                        return sysActivity;
10324                    }
10325                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10326                        return sysActivity;
10327                    }
10328                }
10329            }
10330            return null;
10331        }
10332
10333        public class IterGenerator<E> {
10334            public Iterator<E> generate(ActivityIntentInfo info) {
10335                return null;
10336            }
10337        }
10338
10339        public class ActionIterGenerator extends IterGenerator<String> {
10340            @Override
10341            public Iterator<String> generate(ActivityIntentInfo info) {
10342                return info.actionsIterator();
10343            }
10344        }
10345
10346        public class CategoriesIterGenerator extends IterGenerator<String> {
10347            @Override
10348            public Iterator<String> generate(ActivityIntentInfo info) {
10349                return info.categoriesIterator();
10350            }
10351        }
10352
10353        public class SchemesIterGenerator extends IterGenerator<String> {
10354            @Override
10355            public Iterator<String> generate(ActivityIntentInfo info) {
10356                return info.schemesIterator();
10357            }
10358        }
10359
10360        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10361            @Override
10362            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10363                return info.authoritiesIterator();
10364            }
10365        }
10366
10367        /**
10368         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10369         * MODIFIED. Do not pass in a list that should not be changed.
10370         */
10371        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10372                IterGenerator<T> generator, Iterator<T> searchIterator) {
10373            // loop through the set of actions; every one must be found in the intent filter
10374            while (searchIterator.hasNext()) {
10375                // we must have at least one filter in the list to consider a match
10376                if (intentList.size() == 0) {
10377                    break;
10378                }
10379
10380                final T searchAction = searchIterator.next();
10381
10382                // loop through the set of intent filters
10383                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10384                while (intentIter.hasNext()) {
10385                    final ActivityIntentInfo intentInfo = intentIter.next();
10386                    boolean selectionFound = false;
10387
10388                    // loop through the intent filter's selection criteria; at least one
10389                    // of them must match the searched criteria
10390                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10391                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10392                        final T intentSelection = intentSelectionIter.next();
10393                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10394                            selectionFound = true;
10395                            break;
10396                        }
10397                    }
10398
10399                    // the selection criteria wasn't found in this filter's set; this filter
10400                    // is not a potential match
10401                    if (!selectionFound) {
10402                        intentIter.remove();
10403                    }
10404                }
10405            }
10406        }
10407
10408        private boolean isProtectedAction(ActivityIntentInfo filter) {
10409            final Iterator<String> actionsIter = filter.actionsIterator();
10410            while (actionsIter != null && actionsIter.hasNext()) {
10411                final String filterAction = actionsIter.next();
10412                if (PROTECTED_ACTIONS.contains(filterAction)) {
10413                    return true;
10414                }
10415            }
10416            return false;
10417        }
10418
10419        /**
10420         * Adjusts the priority of the given intent filter according to policy.
10421         * <p>
10422         * <ul>
10423         * <li>The priority for non privileged applications is capped to '0'</li>
10424         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10425         * <li>The priority for unbundled updates to privileged applications is capped to the
10426         *      priority defined on the system partition</li>
10427         * </ul>
10428         * <p>
10429         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10430         * allowed to obtain any priority on any action.
10431         */
10432        private void adjustPriority(
10433                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10434            // nothing to do; priority is fine as-is
10435            if (intent.getPriority() <= 0) {
10436                return;
10437            }
10438
10439            final ActivityInfo activityInfo = intent.activity.info;
10440            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10441
10442            final boolean privilegedApp =
10443                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10444            if (!privilegedApp) {
10445                // non-privileged applications can never define a priority >0
10446                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10447                        + " package: " + applicationInfo.packageName
10448                        + " activity: " + intent.activity.className
10449                        + " origPrio: " + intent.getPriority());
10450                intent.setPriority(0);
10451                return;
10452            }
10453
10454            if (systemActivities == null) {
10455                // the system package is not disabled; we're parsing the system partition
10456                if (isProtectedAction(intent)) {
10457                    if (mDeferProtectedFilters) {
10458                        // We can't deal with these just yet. No component should ever obtain a
10459                        // >0 priority for a protected actions, with ONE exception -- the setup
10460                        // wizard. The setup wizard, however, cannot be known until we're able to
10461                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10462                        // until all intent filters have been processed. Chicken, meet egg.
10463                        // Let the filter temporarily have a high priority and rectify the
10464                        // priorities after all system packages have been scanned.
10465                        mProtectedFilters.add(intent);
10466                        if (DEBUG_FILTERS) {
10467                            Slog.i(TAG, "Protected action; save for later;"
10468                                    + " package: " + applicationInfo.packageName
10469                                    + " activity: " + intent.activity.className
10470                                    + " origPrio: " + intent.getPriority());
10471                        }
10472                        return;
10473                    } else {
10474                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10475                            Slog.i(TAG, "No setup wizard;"
10476                                + " All protected intents capped to priority 0");
10477                        }
10478                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10479                            if (DEBUG_FILTERS) {
10480                                Slog.i(TAG, "Found setup wizard;"
10481                                    + " allow priority " + intent.getPriority() + ";"
10482                                    + " package: " + intent.activity.info.packageName
10483                                    + " activity: " + intent.activity.className
10484                                    + " priority: " + intent.getPriority());
10485                            }
10486                            // setup wizard gets whatever it wants
10487                            return;
10488                        }
10489                        Slog.w(TAG, "Protected action; cap priority to 0;"
10490                                + " package: " + intent.activity.info.packageName
10491                                + " activity: " + intent.activity.className
10492                                + " origPrio: " + intent.getPriority());
10493                        intent.setPriority(0);
10494                        return;
10495                    }
10496                }
10497                // privileged apps on the system image get whatever priority they request
10498                return;
10499            }
10500
10501            // privileged app unbundled update ... try to find the same activity
10502            final PackageParser.Activity foundActivity =
10503                    findMatchingActivity(systemActivities, activityInfo);
10504            if (foundActivity == null) {
10505                // this is a new activity; it cannot obtain >0 priority
10506                if (DEBUG_FILTERS) {
10507                    Slog.i(TAG, "New activity; cap priority to 0;"
10508                            + " package: " + applicationInfo.packageName
10509                            + " activity: " + intent.activity.className
10510                            + " origPrio: " + intent.getPriority());
10511                }
10512                intent.setPriority(0);
10513                return;
10514            }
10515
10516            // found activity, now check for filter equivalence
10517
10518            // a shallow copy is enough; we modify the list, not its contents
10519            final List<ActivityIntentInfo> intentListCopy =
10520                    new ArrayList<>(foundActivity.intents);
10521            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10522
10523            // find matching action subsets
10524            final Iterator<String> actionsIterator = intent.actionsIterator();
10525            if (actionsIterator != null) {
10526                getIntentListSubset(
10527                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10528                if (intentListCopy.size() == 0) {
10529                    // no more intents to match; we're not equivalent
10530                    if (DEBUG_FILTERS) {
10531                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10532                                + " package: " + applicationInfo.packageName
10533                                + " activity: " + intent.activity.className
10534                                + " origPrio: " + intent.getPriority());
10535                    }
10536                    intent.setPriority(0);
10537                    return;
10538                }
10539            }
10540
10541            // find matching category subsets
10542            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10543            if (categoriesIterator != null) {
10544                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10545                        categoriesIterator);
10546                if (intentListCopy.size() == 0) {
10547                    // no more intents to match; we're not equivalent
10548                    if (DEBUG_FILTERS) {
10549                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10550                                + " package: " + applicationInfo.packageName
10551                                + " activity: " + intent.activity.className
10552                                + " origPrio: " + intent.getPriority());
10553                    }
10554                    intent.setPriority(0);
10555                    return;
10556                }
10557            }
10558
10559            // find matching schemes subsets
10560            final Iterator<String> schemesIterator = intent.schemesIterator();
10561            if (schemesIterator != null) {
10562                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10563                        schemesIterator);
10564                if (intentListCopy.size() == 0) {
10565                    // no more intents to match; we're not equivalent
10566                    if (DEBUG_FILTERS) {
10567                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10568                                + " package: " + applicationInfo.packageName
10569                                + " activity: " + intent.activity.className
10570                                + " origPrio: " + intent.getPriority());
10571                    }
10572                    intent.setPriority(0);
10573                    return;
10574                }
10575            }
10576
10577            // find matching authorities subsets
10578            final Iterator<IntentFilter.AuthorityEntry>
10579                    authoritiesIterator = intent.authoritiesIterator();
10580            if (authoritiesIterator != null) {
10581                getIntentListSubset(intentListCopy,
10582                        new AuthoritiesIterGenerator(),
10583                        authoritiesIterator);
10584                if (intentListCopy.size() == 0) {
10585                    // no more intents to match; we're not equivalent
10586                    if (DEBUG_FILTERS) {
10587                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10588                                + " package: " + applicationInfo.packageName
10589                                + " activity: " + intent.activity.className
10590                                + " origPrio: " + intent.getPriority());
10591                    }
10592                    intent.setPriority(0);
10593                    return;
10594                }
10595            }
10596
10597            // we found matching filter(s); app gets the max priority of all intents
10598            int cappedPriority = 0;
10599            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10600                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10601            }
10602            if (intent.getPriority() > cappedPriority) {
10603                if (DEBUG_FILTERS) {
10604                    Slog.i(TAG, "Found matching filter(s);"
10605                            + " cap priority to " + cappedPriority + ";"
10606                            + " package: " + applicationInfo.packageName
10607                            + " activity: " + intent.activity.className
10608                            + " origPrio: " + intent.getPriority());
10609                }
10610                intent.setPriority(cappedPriority);
10611                return;
10612            }
10613            // all this for nothing; the requested priority was <= what was on the system
10614        }
10615
10616        public final void addActivity(PackageParser.Activity a, String type) {
10617            mActivities.put(a.getComponentName(), a);
10618            if (DEBUG_SHOW_INFO)
10619                Log.v(
10620                TAG, "  " + type + " " +
10621                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10622            if (DEBUG_SHOW_INFO)
10623                Log.v(TAG, "    Class=" + a.info.name);
10624            final int NI = a.intents.size();
10625            for (int j=0; j<NI; j++) {
10626                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10627                if ("activity".equals(type)) {
10628                    final PackageSetting ps =
10629                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10630                    final List<PackageParser.Activity> systemActivities =
10631                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10632                    adjustPriority(systemActivities, intent);
10633                }
10634                if (DEBUG_SHOW_INFO) {
10635                    Log.v(TAG, "    IntentFilter:");
10636                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10637                }
10638                if (!intent.debugCheck()) {
10639                    Log.w(TAG, "==> For Activity " + a.info.name);
10640                }
10641                addFilter(intent);
10642            }
10643        }
10644
10645        public final void removeActivity(PackageParser.Activity a, String type) {
10646            mActivities.remove(a.getComponentName());
10647            if (DEBUG_SHOW_INFO) {
10648                Log.v(TAG, "  " + type + " "
10649                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10650                                : a.info.name) + ":");
10651                Log.v(TAG, "    Class=" + a.info.name);
10652            }
10653            final int NI = a.intents.size();
10654            for (int j=0; j<NI; j++) {
10655                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10656                if (DEBUG_SHOW_INFO) {
10657                    Log.v(TAG, "    IntentFilter:");
10658                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10659                }
10660                removeFilter(intent);
10661            }
10662        }
10663
10664        @Override
10665        protected boolean allowFilterResult(
10666                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10667            ActivityInfo filterAi = filter.activity.info;
10668            for (int i=dest.size()-1; i>=0; i--) {
10669                ActivityInfo destAi = dest.get(i).activityInfo;
10670                if (destAi.name == filterAi.name
10671                        && destAi.packageName == filterAi.packageName) {
10672                    return false;
10673                }
10674            }
10675            return true;
10676        }
10677
10678        @Override
10679        protected ActivityIntentInfo[] newArray(int size) {
10680            return new ActivityIntentInfo[size];
10681        }
10682
10683        @Override
10684        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10685            if (!sUserManager.exists(userId)) return true;
10686            PackageParser.Package p = filter.activity.owner;
10687            if (p != null) {
10688                PackageSetting ps = (PackageSetting)p.mExtras;
10689                if (ps != null) {
10690                    // System apps are never considered stopped for purposes of
10691                    // filtering, because there may be no way for the user to
10692                    // actually re-launch them.
10693                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10694                            && ps.getStopped(userId);
10695                }
10696            }
10697            return false;
10698        }
10699
10700        @Override
10701        protected boolean isPackageForFilter(String packageName,
10702                PackageParser.ActivityIntentInfo info) {
10703            return packageName.equals(info.activity.owner.packageName);
10704        }
10705
10706        @Override
10707        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10708                int match, int userId) {
10709            if (!sUserManager.exists(userId)) return null;
10710            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10711                return null;
10712            }
10713            final PackageParser.Activity activity = info.activity;
10714            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10715            if (ps == null) {
10716                return null;
10717            }
10718            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10719                    ps.readUserState(userId), userId);
10720            if (ai == null) {
10721                return null;
10722            }
10723            final ResolveInfo res = new ResolveInfo();
10724            res.activityInfo = ai;
10725            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10726                res.filter = info;
10727            }
10728            if (info != null) {
10729                res.handleAllWebDataURI = info.handleAllWebDataURI();
10730            }
10731            res.priority = info.getPriority();
10732            res.preferredOrder = activity.owner.mPreferredOrder;
10733            //System.out.println("Result: " + res.activityInfo.className +
10734            //                   " = " + res.priority);
10735            res.match = match;
10736            res.isDefault = info.hasDefault;
10737            res.labelRes = info.labelRes;
10738            res.nonLocalizedLabel = info.nonLocalizedLabel;
10739            if (userNeedsBadging(userId)) {
10740                res.noResourceId = true;
10741            } else {
10742                res.icon = info.icon;
10743            }
10744            res.iconResourceId = info.icon;
10745            res.system = res.activityInfo.applicationInfo.isSystemApp();
10746            return res;
10747        }
10748
10749        @Override
10750        protected void sortResults(List<ResolveInfo> results) {
10751            Collections.sort(results, mResolvePrioritySorter);
10752        }
10753
10754        @Override
10755        protected void dumpFilter(PrintWriter out, String prefix,
10756                PackageParser.ActivityIntentInfo filter) {
10757            out.print(prefix); out.print(
10758                    Integer.toHexString(System.identityHashCode(filter.activity)));
10759                    out.print(' ');
10760                    filter.activity.printComponentShortName(out);
10761                    out.print(" filter ");
10762                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10763        }
10764
10765        @Override
10766        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10767            return filter.activity;
10768        }
10769
10770        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10771            PackageParser.Activity activity = (PackageParser.Activity)label;
10772            out.print(prefix); out.print(
10773                    Integer.toHexString(System.identityHashCode(activity)));
10774                    out.print(' ');
10775                    activity.printComponentShortName(out);
10776            if (count > 1) {
10777                out.print(" ("); out.print(count); out.print(" filters)");
10778            }
10779            out.println();
10780        }
10781
10782        // Keys are String (activity class name), values are Activity.
10783        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10784                = new ArrayMap<ComponentName, PackageParser.Activity>();
10785        private int mFlags;
10786    }
10787
10788    private final class ServiceIntentResolver
10789            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10790        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10791                boolean defaultOnly, int userId) {
10792            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10793            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10794        }
10795
10796        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10797                int userId) {
10798            if (!sUserManager.exists(userId)) return null;
10799            mFlags = flags;
10800            return super.queryIntent(intent, resolvedType,
10801                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10802        }
10803
10804        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10805                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10806            if (!sUserManager.exists(userId)) return null;
10807            if (packageServices == null) {
10808                return null;
10809            }
10810            mFlags = flags;
10811            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10812            final int N = packageServices.size();
10813            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10814                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10815
10816            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10817            for (int i = 0; i < N; ++i) {
10818                intentFilters = packageServices.get(i).intents;
10819                if (intentFilters != null && intentFilters.size() > 0) {
10820                    PackageParser.ServiceIntentInfo[] array =
10821                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10822                    intentFilters.toArray(array);
10823                    listCut.add(array);
10824                }
10825            }
10826            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10827        }
10828
10829        public final void addService(PackageParser.Service s) {
10830            mServices.put(s.getComponentName(), s);
10831            if (DEBUG_SHOW_INFO) {
10832                Log.v(TAG, "  "
10833                        + (s.info.nonLocalizedLabel != null
10834                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10835                Log.v(TAG, "    Class=" + s.info.name);
10836            }
10837            final int NI = s.intents.size();
10838            int j;
10839            for (j=0; j<NI; j++) {
10840                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10841                if (DEBUG_SHOW_INFO) {
10842                    Log.v(TAG, "    IntentFilter:");
10843                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10844                }
10845                if (!intent.debugCheck()) {
10846                    Log.w(TAG, "==> For Service " + s.info.name);
10847                }
10848                addFilter(intent);
10849            }
10850        }
10851
10852        public final void removeService(PackageParser.Service s) {
10853            mServices.remove(s.getComponentName());
10854            if (DEBUG_SHOW_INFO) {
10855                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10856                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10857                Log.v(TAG, "    Class=" + s.info.name);
10858            }
10859            final int NI = s.intents.size();
10860            int j;
10861            for (j=0; j<NI; j++) {
10862                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10863                if (DEBUG_SHOW_INFO) {
10864                    Log.v(TAG, "    IntentFilter:");
10865                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10866                }
10867                removeFilter(intent);
10868            }
10869        }
10870
10871        @Override
10872        protected boolean allowFilterResult(
10873                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10874            ServiceInfo filterSi = filter.service.info;
10875            for (int i=dest.size()-1; i>=0; i--) {
10876                ServiceInfo destAi = dest.get(i).serviceInfo;
10877                if (destAi.name == filterSi.name
10878                        && destAi.packageName == filterSi.packageName) {
10879                    return false;
10880                }
10881            }
10882            return true;
10883        }
10884
10885        @Override
10886        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10887            return new PackageParser.ServiceIntentInfo[size];
10888        }
10889
10890        @Override
10891        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10892            if (!sUserManager.exists(userId)) return true;
10893            PackageParser.Package p = filter.service.owner;
10894            if (p != null) {
10895                PackageSetting ps = (PackageSetting)p.mExtras;
10896                if (ps != null) {
10897                    // System apps are never considered stopped for purposes of
10898                    // filtering, because there may be no way for the user to
10899                    // actually re-launch them.
10900                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10901                            && ps.getStopped(userId);
10902                }
10903            }
10904            return false;
10905        }
10906
10907        @Override
10908        protected boolean isPackageForFilter(String packageName,
10909                PackageParser.ServiceIntentInfo info) {
10910            return packageName.equals(info.service.owner.packageName);
10911        }
10912
10913        @Override
10914        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10915                int match, int userId) {
10916            if (!sUserManager.exists(userId)) return null;
10917            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10918            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10919                return null;
10920            }
10921            final PackageParser.Service service = info.service;
10922            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10923            if (ps == null) {
10924                return null;
10925            }
10926            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10927                    ps.readUserState(userId), userId);
10928            if (si == null) {
10929                return null;
10930            }
10931            final ResolveInfo res = new ResolveInfo();
10932            res.serviceInfo = si;
10933            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10934                res.filter = filter;
10935            }
10936            res.priority = info.getPriority();
10937            res.preferredOrder = service.owner.mPreferredOrder;
10938            res.match = match;
10939            res.isDefault = info.hasDefault;
10940            res.labelRes = info.labelRes;
10941            res.nonLocalizedLabel = info.nonLocalizedLabel;
10942            res.icon = info.icon;
10943            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10944            return res;
10945        }
10946
10947        @Override
10948        protected void sortResults(List<ResolveInfo> results) {
10949            Collections.sort(results, mResolvePrioritySorter);
10950        }
10951
10952        @Override
10953        protected void dumpFilter(PrintWriter out, String prefix,
10954                PackageParser.ServiceIntentInfo filter) {
10955            out.print(prefix); out.print(
10956                    Integer.toHexString(System.identityHashCode(filter.service)));
10957                    out.print(' ');
10958                    filter.service.printComponentShortName(out);
10959                    out.print(" filter ");
10960                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10961        }
10962
10963        @Override
10964        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10965            return filter.service;
10966        }
10967
10968        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10969            PackageParser.Service service = (PackageParser.Service)label;
10970            out.print(prefix); out.print(
10971                    Integer.toHexString(System.identityHashCode(service)));
10972                    out.print(' ');
10973                    service.printComponentShortName(out);
10974            if (count > 1) {
10975                out.print(" ("); out.print(count); out.print(" filters)");
10976            }
10977            out.println();
10978        }
10979
10980//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10981//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10982//            final List<ResolveInfo> retList = Lists.newArrayList();
10983//            while (i.hasNext()) {
10984//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10985//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10986//                    retList.add(resolveInfo);
10987//                }
10988//            }
10989//            return retList;
10990//        }
10991
10992        // Keys are String (activity class name), values are Activity.
10993        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10994                = new ArrayMap<ComponentName, PackageParser.Service>();
10995        private int mFlags;
10996    };
10997
10998    private final class ProviderIntentResolver
10999            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11000        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11001                boolean defaultOnly, int userId) {
11002            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11003            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11004        }
11005
11006        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11007                int userId) {
11008            if (!sUserManager.exists(userId))
11009                return null;
11010            mFlags = flags;
11011            return super.queryIntent(intent, resolvedType,
11012                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11013        }
11014
11015        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11016                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11017            if (!sUserManager.exists(userId))
11018                return null;
11019            if (packageProviders == null) {
11020                return null;
11021            }
11022            mFlags = flags;
11023            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11024            final int N = packageProviders.size();
11025            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11026                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11027
11028            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11029            for (int i = 0; i < N; ++i) {
11030                intentFilters = packageProviders.get(i).intents;
11031                if (intentFilters != null && intentFilters.size() > 0) {
11032                    PackageParser.ProviderIntentInfo[] array =
11033                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11034                    intentFilters.toArray(array);
11035                    listCut.add(array);
11036                }
11037            }
11038            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11039        }
11040
11041        public final void addProvider(PackageParser.Provider p) {
11042            if (mProviders.containsKey(p.getComponentName())) {
11043                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11044                return;
11045            }
11046
11047            mProviders.put(p.getComponentName(), p);
11048            if (DEBUG_SHOW_INFO) {
11049                Log.v(TAG, "  "
11050                        + (p.info.nonLocalizedLabel != null
11051                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11052                Log.v(TAG, "    Class=" + p.info.name);
11053            }
11054            final int NI = p.intents.size();
11055            int j;
11056            for (j = 0; j < NI; j++) {
11057                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11058                if (DEBUG_SHOW_INFO) {
11059                    Log.v(TAG, "    IntentFilter:");
11060                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11061                }
11062                if (!intent.debugCheck()) {
11063                    Log.w(TAG, "==> For Provider " + p.info.name);
11064                }
11065                addFilter(intent);
11066            }
11067        }
11068
11069        public final void removeProvider(PackageParser.Provider p) {
11070            mProviders.remove(p.getComponentName());
11071            if (DEBUG_SHOW_INFO) {
11072                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11073                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11074                Log.v(TAG, "    Class=" + p.info.name);
11075            }
11076            final int NI = p.intents.size();
11077            int j;
11078            for (j = 0; j < NI; j++) {
11079                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11080                if (DEBUG_SHOW_INFO) {
11081                    Log.v(TAG, "    IntentFilter:");
11082                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11083                }
11084                removeFilter(intent);
11085            }
11086        }
11087
11088        @Override
11089        protected boolean allowFilterResult(
11090                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11091            ProviderInfo filterPi = filter.provider.info;
11092            for (int i = dest.size() - 1; i >= 0; i--) {
11093                ProviderInfo destPi = dest.get(i).providerInfo;
11094                if (destPi.name == filterPi.name
11095                        && destPi.packageName == filterPi.packageName) {
11096                    return false;
11097                }
11098            }
11099            return true;
11100        }
11101
11102        @Override
11103        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11104            return new PackageParser.ProviderIntentInfo[size];
11105        }
11106
11107        @Override
11108        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11109            if (!sUserManager.exists(userId))
11110                return true;
11111            PackageParser.Package p = filter.provider.owner;
11112            if (p != null) {
11113                PackageSetting ps = (PackageSetting) p.mExtras;
11114                if (ps != null) {
11115                    // System apps are never considered stopped for purposes of
11116                    // filtering, because there may be no way for the user to
11117                    // actually re-launch them.
11118                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11119                            && ps.getStopped(userId);
11120                }
11121            }
11122            return false;
11123        }
11124
11125        @Override
11126        protected boolean isPackageForFilter(String packageName,
11127                PackageParser.ProviderIntentInfo info) {
11128            return packageName.equals(info.provider.owner.packageName);
11129        }
11130
11131        @Override
11132        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11133                int match, int userId) {
11134            if (!sUserManager.exists(userId))
11135                return null;
11136            final PackageParser.ProviderIntentInfo info = filter;
11137            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11138                return null;
11139            }
11140            final PackageParser.Provider provider = info.provider;
11141            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11142            if (ps == null) {
11143                return null;
11144            }
11145            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11146                    ps.readUserState(userId), userId);
11147            if (pi == null) {
11148                return null;
11149            }
11150            final ResolveInfo res = new ResolveInfo();
11151            res.providerInfo = pi;
11152            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11153                res.filter = filter;
11154            }
11155            res.priority = info.getPriority();
11156            res.preferredOrder = provider.owner.mPreferredOrder;
11157            res.match = match;
11158            res.isDefault = info.hasDefault;
11159            res.labelRes = info.labelRes;
11160            res.nonLocalizedLabel = info.nonLocalizedLabel;
11161            res.icon = info.icon;
11162            res.system = res.providerInfo.applicationInfo.isSystemApp();
11163            return res;
11164        }
11165
11166        @Override
11167        protected void sortResults(List<ResolveInfo> results) {
11168            Collections.sort(results, mResolvePrioritySorter);
11169        }
11170
11171        @Override
11172        protected void dumpFilter(PrintWriter out, String prefix,
11173                PackageParser.ProviderIntentInfo filter) {
11174            out.print(prefix);
11175            out.print(
11176                    Integer.toHexString(System.identityHashCode(filter.provider)));
11177            out.print(' ');
11178            filter.provider.printComponentShortName(out);
11179            out.print(" filter ");
11180            out.println(Integer.toHexString(System.identityHashCode(filter)));
11181        }
11182
11183        @Override
11184        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11185            return filter.provider;
11186        }
11187
11188        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11189            PackageParser.Provider provider = (PackageParser.Provider)label;
11190            out.print(prefix); out.print(
11191                    Integer.toHexString(System.identityHashCode(provider)));
11192                    out.print(' ');
11193                    provider.printComponentShortName(out);
11194            if (count > 1) {
11195                out.print(" ("); out.print(count); out.print(" filters)");
11196            }
11197            out.println();
11198        }
11199
11200        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11201                = new ArrayMap<ComponentName, PackageParser.Provider>();
11202        private int mFlags;
11203    }
11204
11205    private static final class EphemeralIntentResolver
11206            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11207        @Override
11208        protected EphemeralResolveIntentInfo[] newArray(int size) {
11209            return new EphemeralResolveIntentInfo[size];
11210        }
11211
11212        @Override
11213        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11214            return true;
11215        }
11216
11217        @Override
11218        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11219                int userId) {
11220            if (!sUserManager.exists(userId)) {
11221                return null;
11222            }
11223            return info.getEphemeralResolveInfo();
11224        }
11225    }
11226
11227    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11228            new Comparator<ResolveInfo>() {
11229        public int compare(ResolveInfo r1, ResolveInfo r2) {
11230            int v1 = r1.priority;
11231            int v2 = r2.priority;
11232            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11233            if (v1 != v2) {
11234                return (v1 > v2) ? -1 : 1;
11235            }
11236            v1 = r1.preferredOrder;
11237            v2 = r2.preferredOrder;
11238            if (v1 != v2) {
11239                return (v1 > v2) ? -1 : 1;
11240            }
11241            if (r1.isDefault != r2.isDefault) {
11242                return r1.isDefault ? -1 : 1;
11243            }
11244            v1 = r1.match;
11245            v2 = r2.match;
11246            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11247            if (v1 != v2) {
11248                return (v1 > v2) ? -1 : 1;
11249            }
11250            if (r1.system != r2.system) {
11251                return r1.system ? -1 : 1;
11252            }
11253            if (r1.activityInfo != null) {
11254                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11255            }
11256            if (r1.serviceInfo != null) {
11257                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11258            }
11259            if (r1.providerInfo != null) {
11260                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11261            }
11262            return 0;
11263        }
11264    };
11265
11266    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11267            new Comparator<ProviderInfo>() {
11268        public int compare(ProviderInfo p1, ProviderInfo p2) {
11269            final int v1 = p1.initOrder;
11270            final int v2 = p2.initOrder;
11271            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11272        }
11273    };
11274
11275    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11276            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11277            final int[] userIds) {
11278        mHandler.post(new Runnable() {
11279            @Override
11280            public void run() {
11281                try {
11282                    final IActivityManager am = ActivityManagerNative.getDefault();
11283                    if (am == null) return;
11284                    final int[] resolvedUserIds;
11285                    if (userIds == null) {
11286                        resolvedUserIds = am.getRunningUserIds();
11287                    } else {
11288                        resolvedUserIds = userIds;
11289                    }
11290                    for (int id : resolvedUserIds) {
11291                        final Intent intent = new Intent(action,
11292                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11293                        if (extras != null) {
11294                            intent.putExtras(extras);
11295                        }
11296                        if (targetPkg != null) {
11297                            intent.setPackage(targetPkg);
11298                        }
11299                        // Modify the UID when posting to other users
11300                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11301                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11302                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11303                            intent.putExtra(Intent.EXTRA_UID, uid);
11304                        }
11305                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11306                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11307                        if (DEBUG_BROADCASTS) {
11308                            RuntimeException here = new RuntimeException("here");
11309                            here.fillInStackTrace();
11310                            Slog.d(TAG, "Sending to user " + id + ": "
11311                                    + intent.toShortString(false, true, false, false)
11312                                    + " " + intent.getExtras(), here);
11313                        }
11314                        am.broadcastIntent(null, intent, null, finishedReceiver,
11315                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11316                                null, finishedReceiver != null, false, id);
11317                    }
11318                } catch (RemoteException ex) {
11319                }
11320            }
11321        });
11322    }
11323
11324    /**
11325     * Check if the external storage media is available. This is true if there
11326     * is a mounted external storage medium or if the external storage is
11327     * emulated.
11328     */
11329    private boolean isExternalMediaAvailable() {
11330        return mMediaMounted || Environment.isExternalStorageEmulated();
11331    }
11332
11333    @Override
11334    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11335        // writer
11336        synchronized (mPackages) {
11337            if (!isExternalMediaAvailable()) {
11338                // If the external storage is no longer mounted at this point,
11339                // the caller may not have been able to delete all of this
11340                // packages files and can not delete any more.  Bail.
11341                return null;
11342            }
11343            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11344            if (lastPackage != null) {
11345                pkgs.remove(lastPackage);
11346            }
11347            if (pkgs.size() > 0) {
11348                return pkgs.get(0);
11349            }
11350        }
11351        return null;
11352    }
11353
11354    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11355        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11356                userId, andCode ? 1 : 0, packageName);
11357        if (mSystemReady) {
11358            msg.sendToTarget();
11359        } else {
11360            if (mPostSystemReadyMessages == null) {
11361                mPostSystemReadyMessages = new ArrayList<>();
11362            }
11363            mPostSystemReadyMessages.add(msg);
11364        }
11365    }
11366
11367    void startCleaningPackages() {
11368        // reader
11369        if (!isExternalMediaAvailable()) {
11370            return;
11371        }
11372        synchronized (mPackages) {
11373            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11374                return;
11375            }
11376        }
11377        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11378        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11379        IActivityManager am = ActivityManagerNative.getDefault();
11380        if (am != null) {
11381            try {
11382                am.startService(null, intent, null, mContext.getOpPackageName(),
11383                        UserHandle.USER_SYSTEM);
11384            } catch (RemoteException e) {
11385            }
11386        }
11387    }
11388
11389    @Override
11390    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11391            int installFlags, String installerPackageName, int userId) {
11392        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11393
11394        final int callingUid = Binder.getCallingUid();
11395        enforceCrossUserPermission(callingUid, userId,
11396                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11397
11398        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11399            try {
11400                if (observer != null) {
11401                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11402                }
11403            } catch (RemoteException re) {
11404            }
11405            return;
11406        }
11407
11408        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11409            installFlags |= PackageManager.INSTALL_FROM_ADB;
11410
11411        } else {
11412            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11413            // about installerPackageName.
11414
11415            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11416            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11417        }
11418
11419        UserHandle user;
11420        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11421            user = UserHandle.ALL;
11422        } else {
11423            user = new UserHandle(userId);
11424        }
11425
11426        // Only system components can circumvent runtime permissions when installing.
11427        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11428                && mContext.checkCallingOrSelfPermission(Manifest.permission
11429                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11430            throw new SecurityException("You need the "
11431                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11432                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11433        }
11434
11435        final File originFile = new File(originPath);
11436        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11437
11438        final Message msg = mHandler.obtainMessage(INIT_COPY);
11439        final VerificationInfo verificationInfo = new VerificationInfo(
11440                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11441        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11442                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11443                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11444                null /*certificates*/);
11445        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11446        msg.obj = params;
11447
11448        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11449                System.identityHashCode(msg.obj));
11450        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11451                System.identityHashCode(msg.obj));
11452
11453        mHandler.sendMessage(msg);
11454    }
11455
11456    void installStage(String packageName, File stagedDir, String stagedCid,
11457            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11458            String installerPackageName, int installerUid, UserHandle user,
11459            Certificate[][] certificates) {
11460        if (DEBUG_EPHEMERAL) {
11461            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11462                Slog.d(TAG, "Ephemeral install of " + packageName);
11463            }
11464        }
11465        final VerificationInfo verificationInfo = new VerificationInfo(
11466                sessionParams.originatingUri, sessionParams.referrerUri,
11467                sessionParams.originatingUid, installerUid);
11468
11469        final OriginInfo origin;
11470        if (stagedDir != null) {
11471            origin = OriginInfo.fromStagedFile(stagedDir);
11472        } else {
11473            origin = OriginInfo.fromStagedContainer(stagedCid);
11474        }
11475
11476        final Message msg = mHandler.obtainMessage(INIT_COPY);
11477        final InstallParams params = new InstallParams(origin, null, observer,
11478                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11479                verificationInfo, user, sessionParams.abiOverride,
11480                sessionParams.grantedRuntimePermissions, certificates);
11481        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11482        msg.obj = params;
11483
11484        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11485                System.identityHashCode(msg.obj));
11486        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11487                System.identityHashCode(msg.obj));
11488
11489        mHandler.sendMessage(msg);
11490    }
11491
11492    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11493            int userId) {
11494        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11495        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11496    }
11497
11498    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11499            int appId, int userId) {
11500        Bundle extras = new Bundle(1);
11501        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11502
11503        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11504                packageName, extras, 0, null, null, new int[] {userId});
11505        try {
11506            IActivityManager am = ActivityManagerNative.getDefault();
11507            if (isSystem && am.isUserRunning(userId, 0)) {
11508                // The just-installed/enabled app is bundled on the system, so presumed
11509                // to be able to run automatically without needing an explicit launch.
11510                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11511                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11512                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11513                        .setPackage(packageName);
11514                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11515                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11516            }
11517        } catch (RemoteException e) {
11518            // shouldn't happen
11519            Slog.w(TAG, "Unable to bootstrap installed package", e);
11520        }
11521    }
11522
11523    @Override
11524    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11525            int userId) {
11526        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11527        PackageSetting pkgSetting;
11528        final int uid = Binder.getCallingUid();
11529        enforceCrossUserPermission(uid, userId,
11530                true /* requireFullPermission */, true /* checkShell */,
11531                "setApplicationHiddenSetting for user " + userId);
11532
11533        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11534            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11535            return false;
11536        }
11537
11538        long callingId = Binder.clearCallingIdentity();
11539        try {
11540            boolean sendAdded = false;
11541            boolean sendRemoved = false;
11542            // writer
11543            synchronized (mPackages) {
11544                pkgSetting = mSettings.mPackages.get(packageName);
11545                if (pkgSetting == null) {
11546                    return false;
11547                }
11548                // Do not allow "android" is being disabled
11549                if ("android".equals(packageName)) {
11550                    Slog.w(TAG, "Cannot hide package: android");
11551                    return false;
11552                }
11553                // Only allow protected packages to hide themselves.
11554                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11555                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11556                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11557                    return false;
11558                }
11559
11560                if (pkgSetting.getHidden(userId) != hidden) {
11561                    pkgSetting.setHidden(hidden, userId);
11562                    mSettings.writePackageRestrictionsLPr(userId);
11563                    if (hidden) {
11564                        sendRemoved = true;
11565                    } else {
11566                        sendAdded = true;
11567                    }
11568                }
11569            }
11570            if (sendAdded) {
11571                sendPackageAddedForUser(packageName, pkgSetting, userId);
11572                return true;
11573            }
11574            if (sendRemoved) {
11575                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11576                        "hiding pkg");
11577                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11578                return true;
11579            }
11580        } finally {
11581            Binder.restoreCallingIdentity(callingId);
11582        }
11583        return false;
11584    }
11585
11586    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11587            int userId) {
11588        final PackageRemovedInfo info = new PackageRemovedInfo();
11589        info.removedPackage = packageName;
11590        info.removedUsers = new int[] {userId};
11591        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11592        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11593    }
11594
11595    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11596        if (pkgList.length > 0) {
11597            Bundle extras = new Bundle(1);
11598            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11599
11600            sendPackageBroadcast(
11601                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11602                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11603                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11604                    new int[] {userId});
11605        }
11606    }
11607
11608    /**
11609     * Returns true if application is not found or there was an error. Otherwise it returns
11610     * the hidden state of the package for the given user.
11611     */
11612    @Override
11613    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11614        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11615        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11616                true /* requireFullPermission */, false /* checkShell */,
11617                "getApplicationHidden for user " + userId);
11618        PackageSetting pkgSetting;
11619        long callingId = Binder.clearCallingIdentity();
11620        try {
11621            // writer
11622            synchronized (mPackages) {
11623                pkgSetting = mSettings.mPackages.get(packageName);
11624                if (pkgSetting == null) {
11625                    return true;
11626                }
11627                return pkgSetting.getHidden(userId);
11628            }
11629        } finally {
11630            Binder.restoreCallingIdentity(callingId);
11631        }
11632    }
11633
11634    /**
11635     * @hide
11636     */
11637    @Override
11638    public int installExistingPackageAsUser(String packageName, int userId) {
11639        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11640                null);
11641        PackageSetting pkgSetting;
11642        final int uid = Binder.getCallingUid();
11643        enforceCrossUserPermission(uid, userId,
11644                true /* requireFullPermission */, true /* checkShell */,
11645                "installExistingPackage for user " + userId);
11646        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11647            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11648        }
11649
11650        long callingId = Binder.clearCallingIdentity();
11651        try {
11652            boolean installed = false;
11653
11654            // writer
11655            synchronized (mPackages) {
11656                pkgSetting = mSettings.mPackages.get(packageName);
11657                if (pkgSetting == null) {
11658                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11659                }
11660                if (!pkgSetting.getInstalled(userId)) {
11661                    pkgSetting.setInstalled(true, userId);
11662                    pkgSetting.setHidden(false, userId);
11663                    mSettings.writePackageRestrictionsLPr(userId);
11664                    installed = true;
11665                }
11666            }
11667
11668            if (installed) {
11669                if (pkgSetting.pkg != null) {
11670                    synchronized (mInstallLock) {
11671                        // We don't need to freeze for a brand new install
11672                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11673                    }
11674                }
11675                sendPackageAddedForUser(packageName, pkgSetting, userId);
11676            }
11677        } finally {
11678            Binder.restoreCallingIdentity(callingId);
11679        }
11680
11681        return PackageManager.INSTALL_SUCCEEDED;
11682    }
11683
11684    boolean isUserRestricted(int userId, String restrictionKey) {
11685        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11686        if (restrictions.getBoolean(restrictionKey, false)) {
11687            Log.w(TAG, "User is restricted: " + restrictionKey);
11688            return true;
11689        }
11690        return false;
11691    }
11692
11693    @Override
11694    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11695            int userId) {
11696        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11697        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11698                true /* requireFullPermission */, true /* checkShell */,
11699                "setPackagesSuspended for user " + userId);
11700
11701        if (ArrayUtils.isEmpty(packageNames)) {
11702            return packageNames;
11703        }
11704
11705        // List of package names for whom the suspended state has changed.
11706        List<String> changedPackages = new ArrayList<>(packageNames.length);
11707        // List of package names for whom the suspended state is not set as requested in this
11708        // method.
11709        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11710        long callingId = Binder.clearCallingIdentity();
11711        try {
11712            for (int i = 0; i < packageNames.length; i++) {
11713                String packageName = packageNames[i];
11714                boolean changed = false;
11715                final int appId;
11716                synchronized (mPackages) {
11717                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11718                    if (pkgSetting == null) {
11719                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11720                                + "\". Skipping suspending/un-suspending.");
11721                        unactionedPackages.add(packageName);
11722                        continue;
11723                    }
11724                    appId = pkgSetting.appId;
11725                    if (pkgSetting.getSuspended(userId) != suspended) {
11726                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11727                            unactionedPackages.add(packageName);
11728                            continue;
11729                        }
11730                        pkgSetting.setSuspended(suspended, userId);
11731                        mSettings.writePackageRestrictionsLPr(userId);
11732                        changed = true;
11733                        changedPackages.add(packageName);
11734                    }
11735                }
11736
11737                if (changed && suspended) {
11738                    killApplication(packageName, UserHandle.getUid(userId, appId),
11739                            "suspending package");
11740                }
11741            }
11742        } finally {
11743            Binder.restoreCallingIdentity(callingId);
11744        }
11745
11746        if (!changedPackages.isEmpty()) {
11747            sendPackagesSuspendedForUser(changedPackages.toArray(
11748                    new String[changedPackages.size()]), userId, suspended);
11749        }
11750
11751        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11752    }
11753
11754    @Override
11755    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11756        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11757                true /* requireFullPermission */, false /* checkShell */,
11758                "isPackageSuspendedForUser for user " + userId);
11759        synchronized (mPackages) {
11760            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11761            if (pkgSetting == null) {
11762                throw new IllegalArgumentException("Unknown target package: " + packageName);
11763            }
11764            return pkgSetting.getSuspended(userId);
11765        }
11766    }
11767
11768    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11769        if (isPackageDeviceAdmin(packageName, userId)) {
11770            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11771                    + "\": has an active device admin");
11772            return false;
11773        }
11774
11775        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11776        if (packageName.equals(activeLauncherPackageName)) {
11777            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11778                    + "\": contains the active launcher");
11779            return false;
11780        }
11781
11782        if (packageName.equals(mRequiredInstallerPackage)) {
11783            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11784                    + "\": required for package installation");
11785            return false;
11786        }
11787
11788        if (packageName.equals(mRequiredVerifierPackage)) {
11789            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11790                    + "\": required for package verification");
11791            return false;
11792        }
11793
11794        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11795            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11796                    + "\": is the default dialer");
11797            return false;
11798        }
11799
11800        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11801            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11802                    + "\": protected package");
11803            return false;
11804        }
11805
11806        return true;
11807    }
11808
11809    private String getActiveLauncherPackageName(int userId) {
11810        Intent intent = new Intent(Intent.ACTION_MAIN);
11811        intent.addCategory(Intent.CATEGORY_HOME);
11812        ResolveInfo resolveInfo = resolveIntent(
11813                intent,
11814                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11815                PackageManager.MATCH_DEFAULT_ONLY,
11816                userId);
11817
11818        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11819    }
11820
11821    private String getDefaultDialerPackageName(int userId) {
11822        synchronized (mPackages) {
11823            return mSettings.getDefaultDialerPackageNameLPw(userId);
11824        }
11825    }
11826
11827    @Override
11828    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11829        mContext.enforceCallingOrSelfPermission(
11830                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11831                "Only package verification agents can verify applications");
11832
11833        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11834        final PackageVerificationResponse response = new PackageVerificationResponse(
11835                verificationCode, Binder.getCallingUid());
11836        msg.arg1 = id;
11837        msg.obj = response;
11838        mHandler.sendMessage(msg);
11839    }
11840
11841    @Override
11842    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11843            long millisecondsToDelay) {
11844        mContext.enforceCallingOrSelfPermission(
11845                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11846                "Only package verification agents can extend verification timeouts");
11847
11848        final PackageVerificationState state = mPendingVerification.get(id);
11849        final PackageVerificationResponse response = new PackageVerificationResponse(
11850                verificationCodeAtTimeout, Binder.getCallingUid());
11851
11852        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11853            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11854        }
11855        if (millisecondsToDelay < 0) {
11856            millisecondsToDelay = 0;
11857        }
11858        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11859                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11860            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11861        }
11862
11863        if ((state != null) && !state.timeoutExtended()) {
11864            state.extendTimeout();
11865
11866            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11867            msg.arg1 = id;
11868            msg.obj = response;
11869            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11870        }
11871    }
11872
11873    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11874            int verificationCode, UserHandle user) {
11875        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11876        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11877        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11878        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11879        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11880
11881        mContext.sendBroadcastAsUser(intent, user,
11882                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11883    }
11884
11885    private ComponentName matchComponentForVerifier(String packageName,
11886            List<ResolveInfo> receivers) {
11887        ActivityInfo targetReceiver = null;
11888
11889        final int NR = receivers.size();
11890        for (int i = 0; i < NR; i++) {
11891            final ResolveInfo info = receivers.get(i);
11892            if (info.activityInfo == null) {
11893                continue;
11894            }
11895
11896            if (packageName.equals(info.activityInfo.packageName)) {
11897                targetReceiver = info.activityInfo;
11898                break;
11899            }
11900        }
11901
11902        if (targetReceiver == null) {
11903            return null;
11904        }
11905
11906        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11907    }
11908
11909    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11910            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11911        if (pkgInfo.verifiers.length == 0) {
11912            return null;
11913        }
11914
11915        final int N = pkgInfo.verifiers.length;
11916        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11917        for (int i = 0; i < N; i++) {
11918            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11919
11920            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11921                    receivers);
11922            if (comp == null) {
11923                continue;
11924            }
11925
11926            final int verifierUid = getUidForVerifier(verifierInfo);
11927            if (verifierUid == -1) {
11928                continue;
11929            }
11930
11931            if (DEBUG_VERIFY) {
11932                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11933                        + " with the correct signature");
11934            }
11935            sufficientVerifiers.add(comp);
11936            verificationState.addSufficientVerifier(verifierUid);
11937        }
11938
11939        return sufficientVerifiers;
11940    }
11941
11942    private int getUidForVerifier(VerifierInfo verifierInfo) {
11943        synchronized (mPackages) {
11944            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11945            if (pkg == null) {
11946                return -1;
11947            } else if (pkg.mSignatures.length != 1) {
11948                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11949                        + " has more than one signature; ignoring");
11950                return -1;
11951            }
11952
11953            /*
11954             * If the public key of the package's signature does not match
11955             * our expected public key, then this is a different package and
11956             * we should skip.
11957             */
11958
11959            final byte[] expectedPublicKey;
11960            try {
11961                final Signature verifierSig = pkg.mSignatures[0];
11962                final PublicKey publicKey = verifierSig.getPublicKey();
11963                expectedPublicKey = publicKey.getEncoded();
11964            } catch (CertificateException e) {
11965                return -1;
11966            }
11967
11968            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11969
11970            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11971                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11972                        + " does not have the expected public key; ignoring");
11973                return -1;
11974            }
11975
11976            return pkg.applicationInfo.uid;
11977        }
11978    }
11979
11980    @Override
11981    public void finishPackageInstall(int token, boolean didLaunch) {
11982        enforceSystemOrRoot("Only the system is allowed to finish installs");
11983
11984        if (DEBUG_INSTALL) {
11985            Slog.v(TAG, "BM finishing package install for " + token);
11986        }
11987        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11988
11989        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11990        mHandler.sendMessage(msg);
11991    }
11992
11993    /**
11994     * Get the verification agent timeout.
11995     *
11996     * @return verification timeout in milliseconds
11997     */
11998    private long getVerificationTimeout() {
11999        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12000                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12001                DEFAULT_VERIFICATION_TIMEOUT);
12002    }
12003
12004    /**
12005     * Get the default verification agent response code.
12006     *
12007     * @return default verification response code
12008     */
12009    private int getDefaultVerificationResponse() {
12010        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12011                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12012                DEFAULT_VERIFICATION_RESPONSE);
12013    }
12014
12015    /**
12016     * Check whether or not package verification has been enabled.
12017     *
12018     * @return true if verification should be performed
12019     */
12020    private boolean isVerificationEnabled(int userId, int installFlags) {
12021        if (!DEFAULT_VERIFY_ENABLE) {
12022            return false;
12023        }
12024        // Ephemeral apps don't get the full verification treatment
12025        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12026            if (DEBUG_EPHEMERAL) {
12027                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12028            }
12029            return false;
12030        }
12031
12032        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12033
12034        // Check if installing from ADB
12035        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12036            // Do not run verification in a test harness environment
12037            if (ActivityManager.isRunningInTestHarness()) {
12038                return false;
12039            }
12040            if (ensureVerifyAppsEnabled) {
12041                return true;
12042            }
12043            // Check if the developer does not want package verification for ADB installs
12044            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12045                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12046                return false;
12047            }
12048        }
12049
12050        if (ensureVerifyAppsEnabled) {
12051            return true;
12052        }
12053
12054        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12055                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12056    }
12057
12058    @Override
12059    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12060            throws RemoteException {
12061        mContext.enforceCallingOrSelfPermission(
12062                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12063                "Only intentfilter verification agents can verify applications");
12064
12065        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12066        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12067                Binder.getCallingUid(), verificationCode, failedDomains);
12068        msg.arg1 = id;
12069        msg.obj = response;
12070        mHandler.sendMessage(msg);
12071    }
12072
12073    @Override
12074    public int getIntentVerificationStatus(String packageName, int userId) {
12075        synchronized (mPackages) {
12076            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12077        }
12078    }
12079
12080    @Override
12081    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12082        mContext.enforceCallingOrSelfPermission(
12083                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12084
12085        boolean result = false;
12086        synchronized (mPackages) {
12087            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12088        }
12089        if (result) {
12090            scheduleWritePackageRestrictionsLocked(userId);
12091        }
12092        return result;
12093    }
12094
12095    @Override
12096    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12097            String packageName) {
12098        synchronized (mPackages) {
12099            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12100        }
12101    }
12102
12103    @Override
12104    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12105        if (TextUtils.isEmpty(packageName)) {
12106            return ParceledListSlice.emptyList();
12107        }
12108        synchronized (mPackages) {
12109            PackageParser.Package pkg = mPackages.get(packageName);
12110            if (pkg == null || pkg.activities == null) {
12111                return ParceledListSlice.emptyList();
12112            }
12113            final int count = pkg.activities.size();
12114            ArrayList<IntentFilter> result = new ArrayList<>();
12115            for (int n=0; n<count; n++) {
12116                PackageParser.Activity activity = pkg.activities.get(n);
12117                if (activity.intents != null && activity.intents.size() > 0) {
12118                    result.addAll(activity.intents);
12119                }
12120            }
12121            return new ParceledListSlice<>(result);
12122        }
12123    }
12124
12125    @Override
12126    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12127        mContext.enforceCallingOrSelfPermission(
12128                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12129
12130        synchronized (mPackages) {
12131            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12132            if (packageName != null) {
12133                result |= updateIntentVerificationStatus(packageName,
12134                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12135                        userId);
12136                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12137                        packageName, userId);
12138            }
12139            return result;
12140        }
12141    }
12142
12143    @Override
12144    public String getDefaultBrowserPackageName(int userId) {
12145        synchronized (mPackages) {
12146            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12147        }
12148    }
12149
12150    /**
12151     * Get the "allow unknown sources" setting.
12152     *
12153     * @return the current "allow unknown sources" setting
12154     */
12155    private int getUnknownSourcesSettings() {
12156        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12157                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12158                -1);
12159    }
12160
12161    @Override
12162    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12163        final int uid = Binder.getCallingUid();
12164        // writer
12165        synchronized (mPackages) {
12166            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12167            if (targetPackageSetting == null) {
12168                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12169            }
12170
12171            PackageSetting installerPackageSetting;
12172            if (installerPackageName != null) {
12173                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12174                if (installerPackageSetting == null) {
12175                    throw new IllegalArgumentException("Unknown installer package: "
12176                            + installerPackageName);
12177                }
12178            } else {
12179                installerPackageSetting = null;
12180            }
12181
12182            Signature[] callerSignature;
12183            Object obj = mSettings.getUserIdLPr(uid);
12184            if (obj != null) {
12185                if (obj instanceof SharedUserSetting) {
12186                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12187                } else if (obj instanceof PackageSetting) {
12188                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12189                } else {
12190                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12191                }
12192            } else {
12193                throw new SecurityException("Unknown calling UID: " + uid);
12194            }
12195
12196            // Verify: can't set installerPackageName to a package that is
12197            // not signed with the same cert as the caller.
12198            if (installerPackageSetting != null) {
12199                if (compareSignatures(callerSignature,
12200                        installerPackageSetting.signatures.mSignatures)
12201                        != PackageManager.SIGNATURE_MATCH) {
12202                    throw new SecurityException(
12203                            "Caller does not have same cert as new installer package "
12204                            + installerPackageName);
12205                }
12206            }
12207
12208            // Verify: if target already has an installer package, it must
12209            // be signed with the same cert as the caller.
12210            if (targetPackageSetting.installerPackageName != null) {
12211                PackageSetting setting = mSettings.mPackages.get(
12212                        targetPackageSetting.installerPackageName);
12213                // If the currently set package isn't valid, then it's always
12214                // okay to change it.
12215                if (setting != null) {
12216                    if (compareSignatures(callerSignature,
12217                            setting.signatures.mSignatures)
12218                            != PackageManager.SIGNATURE_MATCH) {
12219                        throw new SecurityException(
12220                                "Caller does not have same cert as old installer package "
12221                                + targetPackageSetting.installerPackageName);
12222                    }
12223                }
12224            }
12225
12226            // Okay!
12227            targetPackageSetting.installerPackageName = installerPackageName;
12228            if (installerPackageName != null) {
12229                mSettings.mInstallerPackages.add(installerPackageName);
12230            }
12231            scheduleWriteSettingsLocked();
12232        }
12233    }
12234
12235    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12236        // Queue up an async operation since the package installation may take a little while.
12237        mHandler.post(new Runnable() {
12238            public void run() {
12239                mHandler.removeCallbacks(this);
12240                 // Result object to be returned
12241                PackageInstalledInfo res = new PackageInstalledInfo();
12242                res.setReturnCode(currentStatus);
12243                res.uid = -1;
12244                res.pkg = null;
12245                res.removedInfo = null;
12246                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12247                    args.doPreInstall(res.returnCode);
12248                    synchronized (mInstallLock) {
12249                        installPackageTracedLI(args, res);
12250                    }
12251                    args.doPostInstall(res.returnCode, res.uid);
12252                }
12253
12254                // A restore should be performed at this point if (a) the install
12255                // succeeded, (b) the operation is not an update, and (c) the new
12256                // package has not opted out of backup participation.
12257                final boolean update = res.removedInfo != null
12258                        && res.removedInfo.removedPackage != null;
12259                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12260                boolean doRestore = !update
12261                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12262
12263                // Set up the post-install work request bookkeeping.  This will be used
12264                // and cleaned up by the post-install event handling regardless of whether
12265                // there's a restore pass performed.  Token values are >= 1.
12266                int token;
12267                if (mNextInstallToken < 0) mNextInstallToken = 1;
12268                token = mNextInstallToken++;
12269
12270                PostInstallData data = new PostInstallData(args, res);
12271                mRunningInstalls.put(token, data);
12272                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12273
12274                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12275                    // Pass responsibility to the Backup Manager.  It will perform a
12276                    // restore if appropriate, then pass responsibility back to the
12277                    // Package Manager to run the post-install observer callbacks
12278                    // and broadcasts.
12279                    IBackupManager bm = IBackupManager.Stub.asInterface(
12280                            ServiceManager.getService(Context.BACKUP_SERVICE));
12281                    if (bm != null) {
12282                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12283                                + " to BM for possible restore");
12284                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12285                        try {
12286                            // TODO: http://b/22388012
12287                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12288                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12289                            } else {
12290                                doRestore = false;
12291                            }
12292                        } catch (RemoteException e) {
12293                            // can't happen; the backup manager is local
12294                        } catch (Exception e) {
12295                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12296                            doRestore = false;
12297                        }
12298                    } else {
12299                        Slog.e(TAG, "Backup Manager not found!");
12300                        doRestore = false;
12301                    }
12302                }
12303
12304                if (!doRestore) {
12305                    // No restore possible, or the Backup Manager was mysteriously not
12306                    // available -- just fire the post-install work request directly.
12307                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12308
12309                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12310
12311                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12312                    mHandler.sendMessage(msg);
12313                }
12314            }
12315        });
12316    }
12317
12318    /**
12319     * Callback from PackageSettings whenever an app is first transitioned out of the
12320     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12321     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12322     * here whether the app is the target of an ongoing install, and only send the
12323     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12324     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12325     * handling.
12326     */
12327    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12328        // Serialize this with the rest of the install-process message chain.  In the
12329        // restore-at-install case, this Runnable will necessarily run before the
12330        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12331        // are coherent.  In the non-restore case, the app has already completed install
12332        // and been launched through some other means, so it is not in a problematic
12333        // state for observers to see the FIRST_LAUNCH signal.
12334        mHandler.post(new Runnable() {
12335            @Override
12336            public void run() {
12337                for (int i = 0; i < mRunningInstalls.size(); i++) {
12338                    final PostInstallData data = mRunningInstalls.valueAt(i);
12339                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12340                        // right package; but is it for the right user?
12341                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12342                            if (userId == data.res.newUsers[uIndex]) {
12343                                if (DEBUG_BACKUP) {
12344                                    Slog.i(TAG, "Package " + pkgName
12345                                            + " being restored so deferring FIRST_LAUNCH");
12346                                }
12347                                return;
12348                            }
12349                        }
12350                    }
12351                }
12352                // didn't find it, so not being restored
12353                if (DEBUG_BACKUP) {
12354                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12355                }
12356                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12357            }
12358        });
12359    }
12360
12361    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12362        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12363                installerPkg, null, userIds);
12364    }
12365
12366    private abstract class HandlerParams {
12367        private static final int MAX_RETRIES = 4;
12368
12369        /**
12370         * Number of times startCopy() has been attempted and had a non-fatal
12371         * error.
12372         */
12373        private int mRetries = 0;
12374
12375        /** User handle for the user requesting the information or installation. */
12376        private final UserHandle mUser;
12377        String traceMethod;
12378        int traceCookie;
12379
12380        HandlerParams(UserHandle user) {
12381            mUser = user;
12382        }
12383
12384        UserHandle getUser() {
12385            return mUser;
12386        }
12387
12388        HandlerParams setTraceMethod(String traceMethod) {
12389            this.traceMethod = traceMethod;
12390            return this;
12391        }
12392
12393        HandlerParams setTraceCookie(int traceCookie) {
12394            this.traceCookie = traceCookie;
12395            return this;
12396        }
12397
12398        final boolean startCopy() {
12399            boolean res;
12400            try {
12401                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12402
12403                if (++mRetries > MAX_RETRIES) {
12404                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12405                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12406                    handleServiceError();
12407                    return false;
12408                } else {
12409                    handleStartCopy();
12410                    res = true;
12411                }
12412            } catch (RemoteException e) {
12413                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12414                mHandler.sendEmptyMessage(MCS_RECONNECT);
12415                res = false;
12416            }
12417            handleReturnCode();
12418            return res;
12419        }
12420
12421        final void serviceError() {
12422            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12423            handleServiceError();
12424            handleReturnCode();
12425        }
12426
12427        abstract void handleStartCopy() throws RemoteException;
12428        abstract void handleServiceError();
12429        abstract void handleReturnCode();
12430    }
12431
12432    class MeasureParams extends HandlerParams {
12433        private final PackageStats mStats;
12434        private boolean mSuccess;
12435
12436        private final IPackageStatsObserver mObserver;
12437
12438        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12439            super(new UserHandle(stats.userHandle));
12440            mObserver = observer;
12441            mStats = stats;
12442        }
12443
12444        @Override
12445        public String toString() {
12446            return "MeasureParams{"
12447                + Integer.toHexString(System.identityHashCode(this))
12448                + " " + mStats.packageName + "}";
12449        }
12450
12451        @Override
12452        void handleStartCopy() throws RemoteException {
12453            synchronized (mInstallLock) {
12454                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12455            }
12456
12457            if (mSuccess) {
12458                boolean mounted = false;
12459                try {
12460                    final String status = Environment.getExternalStorageState();
12461                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12462                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12463                } catch (Exception e) {
12464                }
12465
12466                if (mounted) {
12467                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12468
12469                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12470                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12471
12472                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12473                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12474
12475                    // Always subtract cache size, since it's a subdirectory
12476                    mStats.externalDataSize -= mStats.externalCacheSize;
12477
12478                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12479                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12480
12481                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12482                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12483                }
12484            }
12485        }
12486
12487        @Override
12488        void handleReturnCode() {
12489            if (mObserver != null) {
12490                try {
12491                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12492                } catch (RemoteException e) {
12493                    Slog.i(TAG, "Observer no longer exists.");
12494                }
12495            }
12496        }
12497
12498        @Override
12499        void handleServiceError() {
12500            Slog.e(TAG, "Could not measure application " + mStats.packageName
12501                            + " external storage");
12502        }
12503    }
12504
12505    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12506            throws RemoteException {
12507        long result = 0;
12508        for (File path : paths) {
12509            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12510        }
12511        return result;
12512    }
12513
12514    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12515        for (File path : paths) {
12516            try {
12517                mcs.clearDirectory(path.getAbsolutePath());
12518            } catch (RemoteException e) {
12519            }
12520        }
12521    }
12522
12523    static class OriginInfo {
12524        /**
12525         * Location where install is coming from, before it has been
12526         * copied/renamed into place. This could be a single monolithic APK
12527         * file, or a cluster directory. This location may be untrusted.
12528         */
12529        final File file;
12530        final String cid;
12531
12532        /**
12533         * Flag indicating that {@link #file} or {@link #cid} has already been
12534         * staged, meaning downstream users don't need to defensively copy the
12535         * contents.
12536         */
12537        final boolean staged;
12538
12539        /**
12540         * Flag indicating that {@link #file} or {@link #cid} is an already
12541         * installed app that is being moved.
12542         */
12543        final boolean existing;
12544
12545        final String resolvedPath;
12546        final File resolvedFile;
12547
12548        static OriginInfo fromNothing() {
12549            return new OriginInfo(null, null, false, false);
12550        }
12551
12552        static OriginInfo fromUntrustedFile(File file) {
12553            return new OriginInfo(file, null, false, false);
12554        }
12555
12556        static OriginInfo fromExistingFile(File file) {
12557            return new OriginInfo(file, null, false, true);
12558        }
12559
12560        static OriginInfo fromStagedFile(File file) {
12561            return new OriginInfo(file, null, true, false);
12562        }
12563
12564        static OriginInfo fromStagedContainer(String cid) {
12565            return new OriginInfo(null, cid, true, false);
12566        }
12567
12568        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12569            this.file = file;
12570            this.cid = cid;
12571            this.staged = staged;
12572            this.existing = existing;
12573
12574            if (cid != null) {
12575                resolvedPath = PackageHelper.getSdDir(cid);
12576                resolvedFile = new File(resolvedPath);
12577            } else if (file != null) {
12578                resolvedPath = file.getAbsolutePath();
12579                resolvedFile = file;
12580            } else {
12581                resolvedPath = null;
12582                resolvedFile = null;
12583            }
12584        }
12585    }
12586
12587    static class MoveInfo {
12588        final int moveId;
12589        final String fromUuid;
12590        final String toUuid;
12591        final String packageName;
12592        final String dataAppName;
12593        final int appId;
12594        final String seinfo;
12595        final int targetSdkVersion;
12596
12597        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12598                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12599            this.moveId = moveId;
12600            this.fromUuid = fromUuid;
12601            this.toUuid = toUuid;
12602            this.packageName = packageName;
12603            this.dataAppName = dataAppName;
12604            this.appId = appId;
12605            this.seinfo = seinfo;
12606            this.targetSdkVersion = targetSdkVersion;
12607        }
12608    }
12609
12610    static class VerificationInfo {
12611        /** A constant used to indicate that a uid value is not present. */
12612        public static final int NO_UID = -1;
12613
12614        /** URI referencing where the package was downloaded from. */
12615        final Uri originatingUri;
12616
12617        /** HTTP referrer URI associated with the originatingURI. */
12618        final Uri referrer;
12619
12620        /** UID of the application that the install request originated from. */
12621        final int originatingUid;
12622
12623        /** UID of application requesting the install */
12624        final int installerUid;
12625
12626        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12627            this.originatingUri = originatingUri;
12628            this.referrer = referrer;
12629            this.originatingUid = originatingUid;
12630            this.installerUid = installerUid;
12631        }
12632    }
12633
12634    class InstallParams extends HandlerParams {
12635        final OriginInfo origin;
12636        final MoveInfo move;
12637        final IPackageInstallObserver2 observer;
12638        int installFlags;
12639        final String installerPackageName;
12640        final String volumeUuid;
12641        private InstallArgs mArgs;
12642        private int mRet;
12643        final String packageAbiOverride;
12644        final String[] grantedRuntimePermissions;
12645        final VerificationInfo verificationInfo;
12646        final Certificate[][] certificates;
12647
12648        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12649                int installFlags, String installerPackageName, String volumeUuid,
12650                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12651                String[] grantedPermissions, Certificate[][] certificates) {
12652            super(user);
12653            this.origin = origin;
12654            this.move = move;
12655            this.observer = observer;
12656            this.installFlags = installFlags;
12657            this.installerPackageName = installerPackageName;
12658            this.volumeUuid = volumeUuid;
12659            this.verificationInfo = verificationInfo;
12660            this.packageAbiOverride = packageAbiOverride;
12661            this.grantedRuntimePermissions = grantedPermissions;
12662            this.certificates = certificates;
12663        }
12664
12665        @Override
12666        public String toString() {
12667            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12668                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12669        }
12670
12671        private int installLocationPolicy(PackageInfoLite pkgLite) {
12672            String packageName = pkgLite.packageName;
12673            int installLocation = pkgLite.installLocation;
12674            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12675            // reader
12676            synchronized (mPackages) {
12677                // Currently installed package which the new package is attempting to replace or
12678                // null if no such package is installed.
12679                PackageParser.Package installedPkg = mPackages.get(packageName);
12680                // Package which currently owns the data which the new package will own if installed.
12681                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12682                // will be null whereas dataOwnerPkg will contain information about the package
12683                // which was uninstalled while keeping its data.
12684                PackageParser.Package dataOwnerPkg = installedPkg;
12685                if (dataOwnerPkg  == null) {
12686                    PackageSetting ps = mSettings.mPackages.get(packageName);
12687                    if (ps != null) {
12688                        dataOwnerPkg = ps.pkg;
12689                    }
12690                }
12691
12692                if (dataOwnerPkg != null) {
12693                    // If installed, the package will get access to data left on the device by its
12694                    // predecessor. As a security measure, this is permited only if this is not a
12695                    // version downgrade or if the predecessor package is marked as debuggable and
12696                    // a downgrade is explicitly requested.
12697                    //
12698                    // On debuggable platform builds, downgrades are permitted even for
12699                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12700                    // not offer security guarantees and thus it's OK to disable some security
12701                    // mechanisms to make debugging/testing easier on those builds. However, even on
12702                    // debuggable builds downgrades of packages are permitted only if requested via
12703                    // installFlags. This is because we aim to keep the behavior of debuggable
12704                    // platform builds as close as possible to the behavior of non-debuggable
12705                    // platform builds.
12706                    final boolean downgradeRequested =
12707                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12708                    final boolean packageDebuggable =
12709                                (dataOwnerPkg.applicationInfo.flags
12710                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12711                    final boolean downgradePermitted =
12712                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12713                    if (!downgradePermitted) {
12714                        try {
12715                            checkDowngrade(dataOwnerPkg, pkgLite);
12716                        } catch (PackageManagerException e) {
12717                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12718                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12719                        }
12720                    }
12721                }
12722
12723                if (installedPkg != null) {
12724                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12725                        // Check for updated system application.
12726                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12727                            if (onSd) {
12728                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12729                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12730                            }
12731                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12732                        } else {
12733                            if (onSd) {
12734                                // Install flag overrides everything.
12735                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12736                            }
12737                            // If current upgrade specifies particular preference
12738                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12739                                // Application explicitly specified internal.
12740                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12741                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12742                                // App explictly prefers external. Let policy decide
12743                            } else {
12744                                // Prefer previous location
12745                                if (isExternal(installedPkg)) {
12746                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12747                                }
12748                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12749                            }
12750                        }
12751                    } else {
12752                        // Invalid install. Return error code
12753                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12754                    }
12755                }
12756            }
12757            // All the special cases have been taken care of.
12758            // Return result based on recommended install location.
12759            if (onSd) {
12760                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12761            }
12762            return pkgLite.recommendedInstallLocation;
12763        }
12764
12765        /*
12766         * Invoke remote method to get package information and install
12767         * location values. Override install location based on default
12768         * policy if needed and then create install arguments based
12769         * on the install location.
12770         */
12771        public void handleStartCopy() throws RemoteException {
12772            int ret = PackageManager.INSTALL_SUCCEEDED;
12773
12774            // If we're already staged, we've firmly committed to an install location
12775            if (origin.staged) {
12776                if (origin.file != null) {
12777                    installFlags |= PackageManager.INSTALL_INTERNAL;
12778                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12779                } else if (origin.cid != null) {
12780                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12781                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12782                } else {
12783                    throw new IllegalStateException("Invalid stage location");
12784                }
12785            }
12786
12787            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12788            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12789            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12790            PackageInfoLite pkgLite = null;
12791
12792            if (onInt && onSd) {
12793                // Check if both bits are set.
12794                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12795                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12796            } else if (onSd && ephemeral) {
12797                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12798                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12799            } else {
12800                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12801                        packageAbiOverride);
12802
12803                if (DEBUG_EPHEMERAL && ephemeral) {
12804                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12805                }
12806
12807                /*
12808                 * If we have too little free space, try to free cache
12809                 * before giving up.
12810                 */
12811                if (!origin.staged && pkgLite.recommendedInstallLocation
12812                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12813                    // TODO: focus freeing disk space on the target device
12814                    final StorageManager storage = StorageManager.from(mContext);
12815                    final long lowThreshold = storage.getStorageLowBytes(
12816                            Environment.getDataDirectory());
12817
12818                    final long sizeBytes = mContainerService.calculateInstalledSize(
12819                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12820
12821                    try {
12822                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12823                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12824                                installFlags, packageAbiOverride);
12825                    } catch (InstallerException e) {
12826                        Slog.w(TAG, "Failed to free cache", e);
12827                    }
12828
12829                    /*
12830                     * The cache free must have deleted the file we
12831                     * downloaded to install.
12832                     *
12833                     * TODO: fix the "freeCache" call to not delete
12834                     *       the file we care about.
12835                     */
12836                    if (pkgLite.recommendedInstallLocation
12837                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12838                        pkgLite.recommendedInstallLocation
12839                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12840                    }
12841                }
12842            }
12843
12844            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12845                int loc = pkgLite.recommendedInstallLocation;
12846                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12847                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12848                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12849                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12850                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12851                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12852                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12853                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12854                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12855                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12856                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12857                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12858                } else {
12859                    // Override with defaults if needed.
12860                    loc = installLocationPolicy(pkgLite);
12861                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12862                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12863                    } else if (!onSd && !onInt) {
12864                        // Override install location with flags
12865                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12866                            // Set the flag to install on external media.
12867                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12868                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12869                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12870                            if (DEBUG_EPHEMERAL) {
12871                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12872                            }
12873                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12874                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12875                                    |PackageManager.INSTALL_INTERNAL);
12876                        } else {
12877                            // Make sure the flag for installing on external
12878                            // media is unset
12879                            installFlags |= PackageManager.INSTALL_INTERNAL;
12880                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12881                        }
12882                    }
12883                }
12884            }
12885
12886            final InstallArgs args = createInstallArgs(this);
12887            mArgs = args;
12888
12889            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12890                // TODO: http://b/22976637
12891                // Apps installed for "all" users use the device owner to verify the app
12892                UserHandle verifierUser = getUser();
12893                if (verifierUser == UserHandle.ALL) {
12894                    verifierUser = UserHandle.SYSTEM;
12895                }
12896
12897                /*
12898                 * Determine if we have any installed package verifiers. If we
12899                 * do, then we'll defer to them to verify the packages.
12900                 */
12901                final int requiredUid = mRequiredVerifierPackage == null ? -1
12902                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12903                                verifierUser.getIdentifier());
12904                if (!origin.existing && requiredUid != -1
12905                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12906                    final Intent verification = new Intent(
12907                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12908                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12909                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12910                            PACKAGE_MIME_TYPE);
12911                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12912
12913                    // Query all live verifiers based on current user state
12914                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12915                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12916
12917                    if (DEBUG_VERIFY) {
12918                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12919                                + verification.toString() + " with " + pkgLite.verifiers.length
12920                                + " optional verifiers");
12921                    }
12922
12923                    final int verificationId = mPendingVerificationToken++;
12924
12925                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12926
12927                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12928                            installerPackageName);
12929
12930                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12931                            installFlags);
12932
12933                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12934                            pkgLite.packageName);
12935
12936                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12937                            pkgLite.versionCode);
12938
12939                    if (verificationInfo != null) {
12940                        if (verificationInfo.originatingUri != null) {
12941                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12942                                    verificationInfo.originatingUri);
12943                        }
12944                        if (verificationInfo.referrer != null) {
12945                            verification.putExtra(Intent.EXTRA_REFERRER,
12946                                    verificationInfo.referrer);
12947                        }
12948                        if (verificationInfo.originatingUid >= 0) {
12949                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12950                                    verificationInfo.originatingUid);
12951                        }
12952                        if (verificationInfo.installerUid >= 0) {
12953                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12954                                    verificationInfo.installerUid);
12955                        }
12956                    }
12957
12958                    final PackageVerificationState verificationState = new PackageVerificationState(
12959                            requiredUid, args);
12960
12961                    mPendingVerification.append(verificationId, verificationState);
12962
12963                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12964                            receivers, verificationState);
12965
12966                    /*
12967                     * If any sufficient verifiers were listed in the package
12968                     * manifest, attempt to ask them.
12969                     */
12970                    if (sufficientVerifiers != null) {
12971                        final int N = sufficientVerifiers.size();
12972                        if (N == 0) {
12973                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12974                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12975                        } else {
12976                            for (int i = 0; i < N; i++) {
12977                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12978
12979                                final Intent sufficientIntent = new Intent(verification);
12980                                sufficientIntent.setComponent(verifierComponent);
12981                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12982                            }
12983                        }
12984                    }
12985
12986                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12987                            mRequiredVerifierPackage, receivers);
12988                    if (ret == PackageManager.INSTALL_SUCCEEDED
12989                            && mRequiredVerifierPackage != null) {
12990                        Trace.asyncTraceBegin(
12991                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12992                        /*
12993                         * Send the intent to the required verification agent,
12994                         * but only start the verification timeout after the
12995                         * target BroadcastReceivers have run.
12996                         */
12997                        verification.setComponent(requiredVerifierComponent);
12998                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12999                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13000                                new BroadcastReceiver() {
13001                                    @Override
13002                                    public void onReceive(Context context, Intent intent) {
13003                                        final Message msg = mHandler
13004                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13005                                        msg.arg1 = verificationId;
13006                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13007                                    }
13008                                }, null, 0, null, null);
13009
13010                        /*
13011                         * We don't want the copy to proceed until verification
13012                         * succeeds, so null out this field.
13013                         */
13014                        mArgs = null;
13015                    }
13016                } else {
13017                    /*
13018                     * No package verification is enabled, so immediately start
13019                     * the remote call to initiate copy using temporary file.
13020                     */
13021                    ret = args.copyApk(mContainerService, true);
13022                }
13023            }
13024
13025            mRet = ret;
13026        }
13027
13028        @Override
13029        void handleReturnCode() {
13030            // If mArgs is null, then MCS couldn't be reached. When it
13031            // reconnects, it will try again to install. At that point, this
13032            // will succeed.
13033            if (mArgs != null) {
13034                processPendingInstall(mArgs, mRet);
13035            }
13036        }
13037
13038        @Override
13039        void handleServiceError() {
13040            mArgs = createInstallArgs(this);
13041            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13042        }
13043
13044        public boolean isForwardLocked() {
13045            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13046        }
13047    }
13048
13049    /**
13050     * Used during creation of InstallArgs
13051     *
13052     * @param installFlags package installation flags
13053     * @return true if should be installed on external storage
13054     */
13055    private static boolean installOnExternalAsec(int installFlags) {
13056        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13057            return false;
13058        }
13059        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13060            return true;
13061        }
13062        return false;
13063    }
13064
13065    /**
13066     * Used during creation of InstallArgs
13067     *
13068     * @param installFlags package installation flags
13069     * @return true if should be installed as forward locked
13070     */
13071    private static boolean installForwardLocked(int installFlags) {
13072        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13073    }
13074
13075    private InstallArgs createInstallArgs(InstallParams params) {
13076        if (params.move != null) {
13077            return new MoveInstallArgs(params);
13078        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13079            return new AsecInstallArgs(params);
13080        } else {
13081            return new FileInstallArgs(params);
13082        }
13083    }
13084
13085    /**
13086     * Create args that describe an existing installed package. Typically used
13087     * when cleaning up old installs, or used as a move source.
13088     */
13089    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13090            String resourcePath, String[] instructionSets) {
13091        final boolean isInAsec;
13092        if (installOnExternalAsec(installFlags)) {
13093            /* Apps on SD card are always in ASEC containers. */
13094            isInAsec = true;
13095        } else if (installForwardLocked(installFlags)
13096                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13097            /*
13098             * Forward-locked apps are only in ASEC containers if they're the
13099             * new style
13100             */
13101            isInAsec = true;
13102        } else {
13103            isInAsec = false;
13104        }
13105
13106        if (isInAsec) {
13107            return new AsecInstallArgs(codePath, instructionSets,
13108                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13109        } else {
13110            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13111        }
13112    }
13113
13114    static abstract class InstallArgs {
13115        /** @see InstallParams#origin */
13116        final OriginInfo origin;
13117        /** @see InstallParams#move */
13118        final MoveInfo move;
13119
13120        final IPackageInstallObserver2 observer;
13121        // Always refers to PackageManager flags only
13122        final int installFlags;
13123        final String installerPackageName;
13124        final String volumeUuid;
13125        final UserHandle user;
13126        final String abiOverride;
13127        final String[] installGrantPermissions;
13128        /** If non-null, drop an async trace when the install completes */
13129        final String traceMethod;
13130        final int traceCookie;
13131        final Certificate[][] certificates;
13132
13133        // The list of instruction sets supported by this app. This is currently
13134        // only used during the rmdex() phase to clean up resources. We can get rid of this
13135        // if we move dex files under the common app path.
13136        /* nullable */ String[] instructionSets;
13137
13138        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13139                int installFlags, String installerPackageName, String volumeUuid,
13140                UserHandle user, String[] instructionSets,
13141                String abiOverride, String[] installGrantPermissions,
13142                String traceMethod, int traceCookie, Certificate[][] certificates) {
13143            this.origin = origin;
13144            this.move = move;
13145            this.installFlags = installFlags;
13146            this.observer = observer;
13147            this.installerPackageName = installerPackageName;
13148            this.volumeUuid = volumeUuid;
13149            this.user = user;
13150            this.instructionSets = instructionSets;
13151            this.abiOverride = abiOverride;
13152            this.installGrantPermissions = installGrantPermissions;
13153            this.traceMethod = traceMethod;
13154            this.traceCookie = traceCookie;
13155            this.certificates = certificates;
13156        }
13157
13158        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13159        abstract int doPreInstall(int status);
13160
13161        /**
13162         * Rename package into final resting place. All paths on the given
13163         * scanned package should be updated to reflect the rename.
13164         */
13165        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13166        abstract int doPostInstall(int status, int uid);
13167
13168        /** @see PackageSettingBase#codePathString */
13169        abstract String getCodePath();
13170        /** @see PackageSettingBase#resourcePathString */
13171        abstract String getResourcePath();
13172
13173        // Need installer lock especially for dex file removal.
13174        abstract void cleanUpResourcesLI();
13175        abstract boolean doPostDeleteLI(boolean delete);
13176
13177        /**
13178         * Called before the source arguments are copied. This is used mostly
13179         * for MoveParams when it needs to read the source file to put it in the
13180         * destination.
13181         */
13182        int doPreCopy() {
13183            return PackageManager.INSTALL_SUCCEEDED;
13184        }
13185
13186        /**
13187         * Called after the source arguments are copied. This is used mostly for
13188         * MoveParams when it needs to read the source file to put it in the
13189         * destination.
13190         */
13191        int doPostCopy(int uid) {
13192            return PackageManager.INSTALL_SUCCEEDED;
13193        }
13194
13195        protected boolean isFwdLocked() {
13196            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13197        }
13198
13199        protected boolean isExternalAsec() {
13200            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13201        }
13202
13203        protected boolean isEphemeral() {
13204            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13205        }
13206
13207        UserHandle getUser() {
13208            return user;
13209        }
13210    }
13211
13212    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13213        if (!allCodePaths.isEmpty()) {
13214            if (instructionSets == null) {
13215                throw new IllegalStateException("instructionSet == null");
13216            }
13217            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13218            for (String codePath : allCodePaths) {
13219                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13220                    try {
13221                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13222                    } catch (InstallerException ignored) {
13223                    }
13224                }
13225            }
13226        }
13227    }
13228
13229    /**
13230     * Logic to handle installation of non-ASEC applications, including copying
13231     * and renaming logic.
13232     */
13233    class FileInstallArgs extends InstallArgs {
13234        private File codeFile;
13235        private File resourceFile;
13236
13237        // Example topology:
13238        // /data/app/com.example/base.apk
13239        // /data/app/com.example/split_foo.apk
13240        // /data/app/com.example/lib/arm/libfoo.so
13241        // /data/app/com.example/lib/arm64/libfoo.so
13242        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13243
13244        /** New install */
13245        FileInstallArgs(InstallParams params) {
13246            super(params.origin, params.move, params.observer, params.installFlags,
13247                    params.installerPackageName, params.volumeUuid,
13248                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13249                    params.grantedRuntimePermissions,
13250                    params.traceMethod, params.traceCookie, params.certificates);
13251            if (isFwdLocked()) {
13252                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13253            }
13254        }
13255
13256        /** Existing install */
13257        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13258            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13259                    null, null, null, 0, null /*certificates*/);
13260            this.codeFile = (codePath != null) ? new File(codePath) : null;
13261            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13262        }
13263
13264        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13265            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13266            try {
13267                return doCopyApk(imcs, temp);
13268            } finally {
13269                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13270            }
13271        }
13272
13273        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13274            if (origin.staged) {
13275                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13276                codeFile = origin.file;
13277                resourceFile = origin.file;
13278                return PackageManager.INSTALL_SUCCEEDED;
13279            }
13280
13281            try {
13282                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13283                final File tempDir =
13284                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13285                codeFile = tempDir;
13286                resourceFile = tempDir;
13287            } catch (IOException e) {
13288                Slog.w(TAG, "Failed to create copy file: " + e);
13289                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13290            }
13291
13292            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13293                @Override
13294                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13295                    if (!FileUtils.isValidExtFilename(name)) {
13296                        throw new IllegalArgumentException("Invalid filename: " + name);
13297                    }
13298                    try {
13299                        final File file = new File(codeFile, name);
13300                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13301                                O_RDWR | O_CREAT, 0644);
13302                        Os.chmod(file.getAbsolutePath(), 0644);
13303                        return new ParcelFileDescriptor(fd);
13304                    } catch (ErrnoException e) {
13305                        throw new RemoteException("Failed to open: " + e.getMessage());
13306                    }
13307                }
13308            };
13309
13310            int ret = PackageManager.INSTALL_SUCCEEDED;
13311            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13312            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13313                Slog.e(TAG, "Failed to copy package");
13314                return ret;
13315            }
13316
13317            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13318            NativeLibraryHelper.Handle handle = null;
13319            try {
13320                handle = NativeLibraryHelper.Handle.create(codeFile);
13321                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13322                        abiOverride);
13323            } catch (IOException e) {
13324                Slog.e(TAG, "Copying native libraries failed", e);
13325                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13326            } finally {
13327                IoUtils.closeQuietly(handle);
13328            }
13329
13330            return ret;
13331        }
13332
13333        int doPreInstall(int status) {
13334            if (status != PackageManager.INSTALL_SUCCEEDED) {
13335                cleanUp();
13336            }
13337            return status;
13338        }
13339
13340        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13341            if (status != PackageManager.INSTALL_SUCCEEDED) {
13342                cleanUp();
13343                return false;
13344            }
13345
13346            final File targetDir = codeFile.getParentFile();
13347            final File beforeCodeFile = codeFile;
13348            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13349
13350            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13351            try {
13352                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13353            } catch (ErrnoException e) {
13354                Slog.w(TAG, "Failed to rename", e);
13355                return false;
13356            }
13357
13358            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13359                Slog.w(TAG, "Failed to restorecon");
13360                return false;
13361            }
13362
13363            // Reflect the rename internally
13364            codeFile = afterCodeFile;
13365            resourceFile = afterCodeFile;
13366
13367            // Reflect the rename in scanned details
13368            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13369            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13370                    afterCodeFile, pkg.baseCodePath));
13371            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13372                    afterCodeFile, pkg.splitCodePaths));
13373
13374            // Reflect the rename in app info
13375            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13376            pkg.setApplicationInfoCodePath(pkg.codePath);
13377            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13378            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13379            pkg.setApplicationInfoResourcePath(pkg.codePath);
13380            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13381            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13382
13383            return true;
13384        }
13385
13386        int doPostInstall(int status, int uid) {
13387            if (status != PackageManager.INSTALL_SUCCEEDED) {
13388                cleanUp();
13389            }
13390            return status;
13391        }
13392
13393        @Override
13394        String getCodePath() {
13395            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13396        }
13397
13398        @Override
13399        String getResourcePath() {
13400            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13401        }
13402
13403        private boolean cleanUp() {
13404            if (codeFile == null || !codeFile.exists()) {
13405                return false;
13406            }
13407
13408            removeCodePathLI(codeFile);
13409
13410            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13411                resourceFile.delete();
13412            }
13413
13414            return true;
13415        }
13416
13417        void cleanUpResourcesLI() {
13418            // Try enumerating all code paths before deleting
13419            List<String> allCodePaths = Collections.EMPTY_LIST;
13420            if (codeFile != null && codeFile.exists()) {
13421                try {
13422                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13423                    allCodePaths = pkg.getAllCodePaths();
13424                } catch (PackageParserException e) {
13425                    // Ignored; we tried our best
13426                }
13427            }
13428
13429            cleanUp();
13430            removeDexFiles(allCodePaths, instructionSets);
13431        }
13432
13433        boolean doPostDeleteLI(boolean delete) {
13434            // XXX err, shouldn't we respect the delete flag?
13435            cleanUpResourcesLI();
13436            return true;
13437        }
13438    }
13439
13440    private boolean isAsecExternal(String cid) {
13441        final String asecPath = PackageHelper.getSdFilesystem(cid);
13442        return !asecPath.startsWith(mAsecInternalPath);
13443    }
13444
13445    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13446            PackageManagerException {
13447        if (copyRet < 0) {
13448            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13449                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13450                throw new PackageManagerException(copyRet, message);
13451            }
13452        }
13453    }
13454
13455    /**
13456     * Extract the MountService "container ID" from the full code path of an
13457     * .apk.
13458     */
13459    static String cidFromCodePath(String fullCodePath) {
13460        int eidx = fullCodePath.lastIndexOf("/");
13461        String subStr1 = fullCodePath.substring(0, eidx);
13462        int sidx = subStr1.lastIndexOf("/");
13463        return subStr1.substring(sidx+1, eidx);
13464    }
13465
13466    /**
13467     * Logic to handle installation of ASEC applications, including copying and
13468     * renaming logic.
13469     */
13470    class AsecInstallArgs extends InstallArgs {
13471        static final String RES_FILE_NAME = "pkg.apk";
13472        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13473
13474        String cid;
13475        String packagePath;
13476        String resourcePath;
13477
13478        /** New install */
13479        AsecInstallArgs(InstallParams params) {
13480            super(params.origin, params.move, params.observer, params.installFlags,
13481                    params.installerPackageName, params.volumeUuid,
13482                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13483                    params.grantedRuntimePermissions,
13484                    params.traceMethod, params.traceCookie, params.certificates);
13485        }
13486
13487        /** Existing install */
13488        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13489                        boolean isExternal, boolean isForwardLocked) {
13490            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13491              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13492                    instructionSets, null, null, null, 0, null /*certificates*/);
13493            // Hackily pretend we're still looking at a full code path
13494            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13495                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13496            }
13497
13498            // Extract cid from fullCodePath
13499            int eidx = fullCodePath.lastIndexOf("/");
13500            String subStr1 = fullCodePath.substring(0, eidx);
13501            int sidx = subStr1.lastIndexOf("/");
13502            cid = subStr1.substring(sidx+1, eidx);
13503            setMountPath(subStr1);
13504        }
13505
13506        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13507            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13508              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13509                    instructionSets, null, null, null, 0, null /*certificates*/);
13510            this.cid = cid;
13511            setMountPath(PackageHelper.getSdDir(cid));
13512        }
13513
13514        void createCopyFile() {
13515            cid = mInstallerService.allocateExternalStageCidLegacy();
13516        }
13517
13518        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13519            if (origin.staged && origin.cid != null) {
13520                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13521                cid = origin.cid;
13522                setMountPath(PackageHelper.getSdDir(cid));
13523                return PackageManager.INSTALL_SUCCEEDED;
13524            }
13525
13526            if (temp) {
13527                createCopyFile();
13528            } else {
13529                /*
13530                 * Pre-emptively destroy the container since it's destroyed if
13531                 * copying fails due to it existing anyway.
13532                 */
13533                PackageHelper.destroySdDir(cid);
13534            }
13535
13536            final String newMountPath = imcs.copyPackageToContainer(
13537                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13538                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13539
13540            if (newMountPath != null) {
13541                setMountPath(newMountPath);
13542                return PackageManager.INSTALL_SUCCEEDED;
13543            } else {
13544                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13545            }
13546        }
13547
13548        @Override
13549        String getCodePath() {
13550            return packagePath;
13551        }
13552
13553        @Override
13554        String getResourcePath() {
13555            return resourcePath;
13556        }
13557
13558        int doPreInstall(int status) {
13559            if (status != PackageManager.INSTALL_SUCCEEDED) {
13560                // Destroy container
13561                PackageHelper.destroySdDir(cid);
13562            } else {
13563                boolean mounted = PackageHelper.isContainerMounted(cid);
13564                if (!mounted) {
13565                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13566                            Process.SYSTEM_UID);
13567                    if (newMountPath != null) {
13568                        setMountPath(newMountPath);
13569                    } else {
13570                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13571                    }
13572                }
13573            }
13574            return status;
13575        }
13576
13577        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13578            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13579            String newMountPath = null;
13580            if (PackageHelper.isContainerMounted(cid)) {
13581                // Unmount the container
13582                if (!PackageHelper.unMountSdDir(cid)) {
13583                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13584                    return false;
13585                }
13586            }
13587            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13588                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13589                        " which might be stale. Will try to clean up.");
13590                // Clean up the stale container and proceed to recreate.
13591                if (!PackageHelper.destroySdDir(newCacheId)) {
13592                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13593                    return false;
13594                }
13595                // Successfully cleaned up stale container. Try to rename again.
13596                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13597                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13598                            + " inspite of cleaning it up.");
13599                    return false;
13600                }
13601            }
13602            if (!PackageHelper.isContainerMounted(newCacheId)) {
13603                Slog.w(TAG, "Mounting container " + newCacheId);
13604                newMountPath = PackageHelper.mountSdDir(newCacheId,
13605                        getEncryptKey(), Process.SYSTEM_UID);
13606            } else {
13607                newMountPath = PackageHelper.getSdDir(newCacheId);
13608            }
13609            if (newMountPath == null) {
13610                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13611                return false;
13612            }
13613            Log.i(TAG, "Succesfully renamed " + cid +
13614                    " to " + newCacheId +
13615                    " at new path: " + newMountPath);
13616            cid = newCacheId;
13617
13618            final File beforeCodeFile = new File(packagePath);
13619            setMountPath(newMountPath);
13620            final File afterCodeFile = new File(packagePath);
13621
13622            // Reflect the rename in scanned details
13623            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13624            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13625                    afterCodeFile, pkg.baseCodePath));
13626            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13627                    afterCodeFile, pkg.splitCodePaths));
13628
13629            // Reflect the rename in app info
13630            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13631            pkg.setApplicationInfoCodePath(pkg.codePath);
13632            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13633            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13634            pkg.setApplicationInfoResourcePath(pkg.codePath);
13635            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13636            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13637
13638            return true;
13639        }
13640
13641        private void setMountPath(String mountPath) {
13642            final File mountFile = new File(mountPath);
13643
13644            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13645            if (monolithicFile.exists()) {
13646                packagePath = monolithicFile.getAbsolutePath();
13647                if (isFwdLocked()) {
13648                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13649                } else {
13650                    resourcePath = packagePath;
13651                }
13652            } else {
13653                packagePath = mountFile.getAbsolutePath();
13654                resourcePath = packagePath;
13655            }
13656        }
13657
13658        int doPostInstall(int status, int uid) {
13659            if (status != PackageManager.INSTALL_SUCCEEDED) {
13660                cleanUp();
13661            } else {
13662                final int groupOwner;
13663                final String protectedFile;
13664                if (isFwdLocked()) {
13665                    groupOwner = UserHandle.getSharedAppGid(uid);
13666                    protectedFile = RES_FILE_NAME;
13667                } else {
13668                    groupOwner = -1;
13669                    protectedFile = null;
13670                }
13671
13672                if (uid < Process.FIRST_APPLICATION_UID
13673                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13674                    Slog.e(TAG, "Failed to finalize " + cid);
13675                    PackageHelper.destroySdDir(cid);
13676                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13677                }
13678
13679                boolean mounted = PackageHelper.isContainerMounted(cid);
13680                if (!mounted) {
13681                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13682                }
13683            }
13684            return status;
13685        }
13686
13687        private void cleanUp() {
13688            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13689
13690            // Destroy secure container
13691            PackageHelper.destroySdDir(cid);
13692        }
13693
13694        private List<String> getAllCodePaths() {
13695            final File codeFile = new File(getCodePath());
13696            if (codeFile != null && codeFile.exists()) {
13697                try {
13698                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13699                    return pkg.getAllCodePaths();
13700                } catch (PackageParserException e) {
13701                    // Ignored; we tried our best
13702                }
13703            }
13704            return Collections.EMPTY_LIST;
13705        }
13706
13707        void cleanUpResourcesLI() {
13708            // Enumerate all code paths before deleting
13709            cleanUpResourcesLI(getAllCodePaths());
13710        }
13711
13712        private void cleanUpResourcesLI(List<String> allCodePaths) {
13713            cleanUp();
13714            removeDexFiles(allCodePaths, instructionSets);
13715        }
13716
13717        String getPackageName() {
13718            return getAsecPackageName(cid);
13719        }
13720
13721        boolean doPostDeleteLI(boolean delete) {
13722            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13723            final List<String> allCodePaths = getAllCodePaths();
13724            boolean mounted = PackageHelper.isContainerMounted(cid);
13725            if (mounted) {
13726                // Unmount first
13727                if (PackageHelper.unMountSdDir(cid)) {
13728                    mounted = false;
13729                }
13730            }
13731            if (!mounted && delete) {
13732                cleanUpResourcesLI(allCodePaths);
13733            }
13734            return !mounted;
13735        }
13736
13737        @Override
13738        int doPreCopy() {
13739            if (isFwdLocked()) {
13740                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13741                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13742                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13743                }
13744            }
13745
13746            return PackageManager.INSTALL_SUCCEEDED;
13747        }
13748
13749        @Override
13750        int doPostCopy(int uid) {
13751            if (isFwdLocked()) {
13752                if (uid < Process.FIRST_APPLICATION_UID
13753                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13754                                RES_FILE_NAME)) {
13755                    Slog.e(TAG, "Failed to finalize " + cid);
13756                    PackageHelper.destroySdDir(cid);
13757                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13758                }
13759            }
13760
13761            return PackageManager.INSTALL_SUCCEEDED;
13762        }
13763    }
13764
13765    /**
13766     * Logic to handle movement of existing installed applications.
13767     */
13768    class MoveInstallArgs extends InstallArgs {
13769        private File codeFile;
13770        private File resourceFile;
13771
13772        /** New install */
13773        MoveInstallArgs(InstallParams params) {
13774            super(params.origin, params.move, params.observer, params.installFlags,
13775                    params.installerPackageName, params.volumeUuid,
13776                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13777                    params.grantedRuntimePermissions,
13778                    params.traceMethod, params.traceCookie, params.certificates);
13779        }
13780
13781        int copyApk(IMediaContainerService imcs, boolean temp) {
13782            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13783                    + move.fromUuid + " to " + move.toUuid);
13784            synchronized (mInstaller) {
13785                try {
13786                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13787                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13788                } catch (InstallerException e) {
13789                    Slog.w(TAG, "Failed to move app", e);
13790                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13791                }
13792            }
13793
13794            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13795            resourceFile = codeFile;
13796            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13797
13798            return PackageManager.INSTALL_SUCCEEDED;
13799        }
13800
13801        int doPreInstall(int status) {
13802            if (status != PackageManager.INSTALL_SUCCEEDED) {
13803                cleanUp(move.toUuid);
13804            }
13805            return status;
13806        }
13807
13808        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13809            if (status != PackageManager.INSTALL_SUCCEEDED) {
13810                cleanUp(move.toUuid);
13811                return false;
13812            }
13813
13814            // Reflect the move in app info
13815            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13816            pkg.setApplicationInfoCodePath(pkg.codePath);
13817            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13818            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13819            pkg.setApplicationInfoResourcePath(pkg.codePath);
13820            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13821            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13822
13823            return true;
13824        }
13825
13826        int doPostInstall(int status, int uid) {
13827            if (status == PackageManager.INSTALL_SUCCEEDED) {
13828                cleanUp(move.fromUuid);
13829            } else {
13830                cleanUp(move.toUuid);
13831            }
13832            return status;
13833        }
13834
13835        @Override
13836        String getCodePath() {
13837            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13838        }
13839
13840        @Override
13841        String getResourcePath() {
13842            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13843        }
13844
13845        private boolean cleanUp(String volumeUuid) {
13846            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13847                    move.dataAppName);
13848            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13849            final int[] userIds = sUserManager.getUserIds();
13850            synchronized (mInstallLock) {
13851                // Clean up both app data and code
13852                // All package moves are frozen until finished
13853                for (int userId : userIds) {
13854                    try {
13855                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13856                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13857                    } catch (InstallerException e) {
13858                        Slog.w(TAG, String.valueOf(e));
13859                    }
13860                }
13861                removeCodePathLI(codeFile);
13862            }
13863            return true;
13864        }
13865
13866        void cleanUpResourcesLI() {
13867            throw new UnsupportedOperationException();
13868        }
13869
13870        boolean doPostDeleteLI(boolean delete) {
13871            throw new UnsupportedOperationException();
13872        }
13873    }
13874
13875    static String getAsecPackageName(String packageCid) {
13876        int idx = packageCid.lastIndexOf("-");
13877        if (idx == -1) {
13878            return packageCid;
13879        }
13880        return packageCid.substring(0, idx);
13881    }
13882
13883    // Utility method used to create code paths based on package name and available index.
13884    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13885        String idxStr = "";
13886        int idx = 1;
13887        // Fall back to default value of idx=1 if prefix is not
13888        // part of oldCodePath
13889        if (oldCodePath != null) {
13890            String subStr = oldCodePath;
13891            // Drop the suffix right away
13892            if (suffix != null && subStr.endsWith(suffix)) {
13893                subStr = subStr.substring(0, subStr.length() - suffix.length());
13894            }
13895            // If oldCodePath already contains prefix find out the
13896            // ending index to either increment or decrement.
13897            int sidx = subStr.lastIndexOf(prefix);
13898            if (sidx != -1) {
13899                subStr = subStr.substring(sidx + prefix.length());
13900                if (subStr != null) {
13901                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13902                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13903                    }
13904                    try {
13905                        idx = Integer.parseInt(subStr);
13906                        if (idx <= 1) {
13907                            idx++;
13908                        } else {
13909                            idx--;
13910                        }
13911                    } catch(NumberFormatException e) {
13912                    }
13913                }
13914            }
13915        }
13916        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13917        return prefix + idxStr;
13918    }
13919
13920    private File getNextCodePath(File targetDir, String packageName) {
13921        int suffix = 1;
13922        File result;
13923        do {
13924            result = new File(targetDir, packageName + "-" + suffix);
13925            suffix++;
13926        } while (result.exists());
13927        return result;
13928    }
13929
13930    // Utility method that returns the relative package path with respect
13931    // to the installation directory. Like say for /data/data/com.test-1.apk
13932    // string com.test-1 is returned.
13933    static String deriveCodePathName(String codePath) {
13934        if (codePath == null) {
13935            return null;
13936        }
13937        final File codeFile = new File(codePath);
13938        final String name = codeFile.getName();
13939        if (codeFile.isDirectory()) {
13940            return name;
13941        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13942            final int lastDot = name.lastIndexOf('.');
13943            return name.substring(0, lastDot);
13944        } else {
13945            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13946            return null;
13947        }
13948    }
13949
13950    static class PackageInstalledInfo {
13951        String name;
13952        int uid;
13953        // The set of users that originally had this package installed.
13954        int[] origUsers;
13955        // The set of users that now have this package installed.
13956        int[] newUsers;
13957        PackageParser.Package pkg;
13958        int returnCode;
13959        String returnMsg;
13960        PackageRemovedInfo removedInfo;
13961        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13962
13963        public void setError(int code, String msg) {
13964            setReturnCode(code);
13965            setReturnMessage(msg);
13966            Slog.w(TAG, msg);
13967        }
13968
13969        public void setError(String msg, PackageParserException e) {
13970            setReturnCode(e.error);
13971            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13972            Slog.w(TAG, msg, e);
13973        }
13974
13975        public void setError(String msg, PackageManagerException e) {
13976            returnCode = e.error;
13977            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13978            Slog.w(TAG, msg, e);
13979        }
13980
13981        public void setReturnCode(int returnCode) {
13982            this.returnCode = returnCode;
13983            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13984            for (int i = 0; i < childCount; i++) {
13985                addedChildPackages.valueAt(i).returnCode = returnCode;
13986            }
13987        }
13988
13989        private void setReturnMessage(String returnMsg) {
13990            this.returnMsg = returnMsg;
13991            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13992            for (int i = 0; i < childCount; i++) {
13993                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13994            }
13995        }
13996
13997        // In some error cases we want to convey more info back to the observer
13998        String origPackage;
13999        String origPermission;
14000    }
14001
14002    /*
14003     * Install a non-existing package.
14004     */
14005    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14006            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14007            PackageInstalledInfo res) {
14008        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14009
14010        // Remember this for later, in case we need to rollback this install
14011        String pkgName = pkg.packageName;
14012
14013        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14014
14015        synchronized(mPackages) {
14016            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14017                // A package with the same name is already installed, though
14018                // it has been renamed to an older name.  The package we
14019                // are trying to install should be installed as an update to
14020                // the existing one, but that has not been requested, so bail.
14021                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14022                        + " without first uninstalling package running as "
14023                        + mSettings.mRenamedPackages.get(pkgName));
14024                return;
14025            }
14026            if (mPackages.containsKey(pkgName)) {
14027                // Don't allow installation over an existing package with the same name.
14028                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14029                        + " without first uninstalling.");
14030                return;
14031            }
14032        }
14033
14034        try {
14035            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14036                    System.currentTimeMillis(), user);
14037
14038            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14039
14040            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14041                prepareAppDataAfterInstallLIF(newPackage);
14042
14043            } else {
14044                // Remove package from internal structures, but keep around any
14045                // data that might have already existed
14046                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14047                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14048            }
14049        } catch (PackageManagerException e) {
14050            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14051        }
14052
14053        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14054    }
14055
14056    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14057        // Can't rotate keys during boot or if sharedUser.
14058        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14059                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14060            return false;
14061        }
14062        // app is using upgradeKeySets; make sure all are valid
14063        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14064        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14065        for (int i = 0; i < upgradeKeySets.length; i++) {
14066            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14067                Slog.wtf(TAG, "Package "
14068                         + (oldPs.name != null ? oldPs.name : "<null>")
14069                         + " contains upgrade-key-set reference to unknown key-set: "
14070                         + upgradeKeySets[i]
14071                         + " reverting to signatures check.");
14072                return false;
14073            }
14074        }
14075        return true;
14076    }
14077
14078    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14079        // Upgrade keysets are being used.  Determine if new package has a superset of the
14080        // required keys.
14081        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14082        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14083        for (int i = 0; i < upgradeKeySets.length; i++) {
14084            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14085            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14086                return true;
14087            }
14088        }
14089        return false;
14090    }
14091
14092    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14093        try (DigestInputStream digestStream =
14094                new DigestInputStream(new FileInputStream(file), digest)) {
14095            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14096        }
14097    }
14098
14099    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14100            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14101        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14102
14103        final PackageParser.Package oldPackage;
14104        final String pkgName = pkg.packageName;
14105        final int[] allUsers;
14106        final int[] installedUsers;
14107
14108        synchronized(mPackages) {
14109            oldPackage = mPackages.get(pkgName);
14110            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14111
14112            // don't allow upgrade to target a release SDK from a pre-release SDK
14113            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14114                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14115            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14116                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14117            if (oldTargetsPreRelease
14118                    && !newTargetsPreRelease
14119                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14120                Slog.w(TAG, "Can't install package targeting released sdk");
14121                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14122                return;
14123            }
14124
14125            // don't allow an upgrade from full to ephemeral
14126            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14127            if (isEphemeral && !oldIsEphemeral) {
14128                // can't downgrade from full to ephemeral
14129                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14130                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14131                return;
14132            }
14133
14134            // verify signatures are valid
14135            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14136            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14137                if (!checkUpgradeKeySetLP(ps, pkg)) {
14138                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14139                            "New package not signed by keys specified by upgrade-keysets: "
14140                                    + pkgName);
14141                    return;
14142                }
14143            } else {
14144                // default to original signature matching
14145                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14146                        != PackageManager.SIGNATURE_MATCH) {
14147                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14148                            "New package has a different signature: " + pkgName);
14149                    return;
14150                }
14151            }
14152
14153            // don't allow a system upgrade unless the upgrade hash matches
14154            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14155                byte[] digestBytes = null;
14156                try {
14157                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14158                    updateDigest(digest, new File(pkg.baseCodePath));
14159                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14160                        for (String path : pkg.splitCodePaths) {
14161                            updateDigest(digest, new File(path));
14162                        }
14163                    }
14164                    digestBytes = digest.digest();
14165                } catch (NoSuchAlgorithmException | IOException e) {
14166                    res.setError(INSTALL_FAILED_INVALID_APK,
14167                            "Could not compute hash: " + pkgName);
14168                    return;
14169                }
14170                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14171                    res.setError(INSTALL_FAILED_INVALID_APK,
14172                            "New package fails restrict-update check: " + pkgName);
14173                    return;
14174                }
14175                // retain upgrade restriction
14176                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14177            }
14178
14179            // Check for shared user id changes
14180            String invalidPackageName =
14181                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14182            if (invalidPackageName != null) {
14183                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14184                        "Package " + invalidPackageName + " tried to change user "
14185                                + oldPackage.mSharedUserId);
14186                return;
14187            }
14188
14189            // In case of rollback, remember per-user/profile install state
14190            allUsers = sUserManager.getUserIds();
14191            installedUsers = ps.queryInstalledUsers(allUsers, true);
14192        }
14193
14194        // Update what is removed
14195        res.removedInfo = new PackageRemovedInfo();
14196        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14197        res.removedInfo.removedPackage = oldPackage.packageName;
14198        res.removedInfo.isUpdate = true;
14199        res.removedInfo.origUsers = installedUsers;
14200        final int childCount = (oldPackage.childPackages != null)
14201                ? oldPackage.childPackages.size() : 0;
14202        for (int i = 0; i < childCount; i++) {
14203            boolean childPackageUpdated = false;
14204            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14205            if (res.addedChildPackages != null) {
14206                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14207                if (childRes != null) {
14208                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14209                    childRes.removedInfo.removedPackage = childPkg.packageName;
14210                    childRes.removedInfo.isUpdate = true;
14211                    childPackageUpdated = true;
14212                }
14213            }
14214            if (!childPackageUpdated) {
14215                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14216                childRemovedRes.removedPackage = childPkg.packageName;
14217                childRemovedRes.isUpdate = false;
14218                childRemovedRes.dataRemoved = true;
14219                synchronized (mPackages) {
14220                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14221                    if (childPs != null) {
14222                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14223                    }
14224                }
14225                if (res.removedInfo.removedChildPackages == null) {
14226                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14227                }
14228                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14229            }
14230        }
14231
14232        boolean sysPkg = (isSystemApp(oldPackage));
14233        if (sysPkg) {
14234            // Set the system/privileged flags as needed
14235            final boolean privileged =
14236                    (oldPackage.applicationInfo.privateFlags
14237                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14238            final int systemPolicyFlags = policyFlags
14239                    | PackageParser.PARSE_IS_SYSTEM
14240                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14241
14242            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14243                    user, allUsers, installerPackageName, res);
14244        } else {
14245            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14246                    user, allUsers, installerPackageName, res);
14247        }
14248    }
14249
14250    public List<String> getPreviousCodePaths(String packageName) {
14251        final PackageSetting ps = mSettings.mPackages.get(packageName);
14252        final List<String> result = new ArrayList<String>();
14253        if (ps != null && ps.oldCodePaths != null) {
14254            result.addAll(ps.oldCodePaths);
14255        }
14256        return result;
14257    }
14258
14259    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14260            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14261            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14262        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14263                + deletedPackage);
14264
14265        String pkgName = deletedPackage.packageName;
14266        boolean deletedPkg = true;
14267        boolean addedPkg = false;
14268        boolean updatedSettings = false;
14269        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14270        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14271                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14272
14273        final long origUpdateTime = (pkg.mExtras != null)
14274                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14275
14276        // First delete the existing package while retaining the data directory
14277        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14278                res.removedInfo, true, pkg)) {
14279            // If the existing package wasn't successfully deleted
14280            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14281            deletedPkg = false;
14282        } else {
14283            // Successfully deleted the old package; proceed with replace.
14284
14285            // If deleted package lived in a container, give users a chance to
14286            // relinquish resources before killing.
14287            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14288                if (DEBUG_INSTALL) {
14289                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14290                }
14291                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14292                final ArrayList<String> pkgList = new ArrayList<String>(1);
14293                pkgList.add(deletedPackage.applicationInfo.packageName);
14294                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14295            }
14296
14297            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14298                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14299            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14300
14301            try {
14302                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14303                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14304                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14305
14306                // Update the in-memory copy of the previous code paths.
14307                PackageSetting ps = mSettings.mPackages.get(pkgName);
14308                if (!killApp) {
14309                    if (ps.oldCodePaths == null) {
14310                        ps.oldCodePaths = new ArraySet<>();
14311                    }
14312                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14313                    if (deletedPackage.splitCodePaths != null) {
14314                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14315                    }
14316                } else {
14317                    ps.oldCodePaths = null;
14318                }
14319                if (ps.childPackageNames != null) {
14320                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14321                        final String childPkgName = ps.childPackageNames.get(i);
14322                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14323                        childPs.oldCodePaths = ps.oldCodePaths;
14324                    }
14325                }
14326                prepareAppDataAfterInstallLIF(newPackage);
14327                addedPkg = true;
14328            } catch (PackageManagerException e) {
14329                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14330            }
14331        }
14332
14333        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14334            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14335
14336            // Revert all internal state mutations and added folders for the failed install
14337            if (addedPkg) {
14338                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14339                        res.removedInfo, true, null);
14340            }
14341
14342            // Restore the old package
14343            if (deletedPkg) {
14344                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14345                File restoreFile = new File(deletedPackage.codePath);
14346                // Parse old package
14347                boolean oldExternal = isExternal(deletedPackage);
14348                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14349                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14350                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14351                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14352                try {
14353                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14354                            null);
14355                } catch (PackageManagerException e) {
14356                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14357                            + e.getMessage());
14358                    return;
14359                }
14360
14361                synchronized (mPackages) {
14362                    // Ensure the installer package name up to date
14363                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14364
14365                    // Update permissions for restored package
14366                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14367
14368                    mSettings.writeLPr();
14369                }
14370
14371                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14372            }
14373        } else {
14374            synchronized (mPackages) {
14375                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14376                if (ps != null) {
14377                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14378                    if (res.removedInfo.removedChildPackages != null) {
14379                        final int childCount = res.removedInfo.removedChildPackages.size();
14380                        // Iterate in reverse as we may modify the collection
14381                        for (int i = childCount - 1; i >= 0; i--) {
14382                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14383                            if (res.addedChildPackages.containsKey(childPackageName)) {
14384                                res.removedInfo.removedChildPackages.removeAt(i);
14385                            } else {
14386                                PackageRemovedInfo childInfo = res.removedInfo
14387                                        .removedChildPackages.valueAt(i);
14388                                childInfo.removedForAllUsers = mPackages.get(
14389                                        childInfo.removedPackage) == null;
14390                            }
14391                        }
14392                    }
14393                }
14394            }
14395        }
14396    }
14397
14398    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14399            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14400            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14401        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14402                + ", old=" + deletedPackage);
14403
14404        final boolean disabledSystem;
14405
14406        // Remove existing system package
14407        removePackageLI(deletedPackage, true);
14408
14409        synchronized (mPackages) {
14410            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14411        }
14412        if (!disabledSystem) {
14413            // We didn't need to disable the .apk as a current system package,
14414            // which means we are replacing another update that is already
14415            // installed.  We need to make sure to delete the older one's .apk.
14416            res.removedInfo.args = createInstallArgsForExisting(0,
14417                    deletedPackage.applicationInfo.getCodePath(),
14418                    deletedPackage.applicationInfo.getResourcePath(),
14419                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14420        } else {
14421            res.removedInfo.args = null;
14422        }
14423
14424        // Successfully disabled the old package. Now proceed with re-installation
14425        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14426                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14427        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14428
14429        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14430        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14431                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14432
14433        PackageParser.Package newPackage = null;
14434        try {
14435            // Add the package to the internal data structures
14436            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14437
14438            // Set the update and install times
14439            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14440            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14441                    System.currentTimeMillis());
14442
14443            // Update the package dynamic state if succeeded
14444            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14445                // Now that the install succeeded make sure we remove data
14446                // directories for any child package the update removed.
14447                final int deletedChildCount = (deletedPackage.childPackages != null)
14448                        ? deletedPackage.childPackages.size() : 0;
14449                final int newChildCount = (newPackage.childPackages != null)
14450                        ? newPackage.childPackages.size() : 0;
14451                for (int i = 0; i < deletedChildCount; i++) {
14452                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14453                    boolean childPackageDeleted = true;
14454                    for (int j = 0; j < newChildCount; j++) {
14455                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14456                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14457                            childPackageDeleted = false;
14458                            break;
14459                        }
14460                    }
14461                    if (childPackageDeleted) {
14462                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14463                                deletedChildPkg.packageName);
14464                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14465                            PackageRemovedInfo removedChildRes = res.removedInfo
14466                                    .removedChildPackages.get(deletedChildPkg.packageName);
14467                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14468                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14469                        }
14470                    }
14471                }
14472
14473                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14474                prepareAppDataAfterInstallLIF(newPackage);
14475            }
14476        } catch (PackageManagerException e) {
14477            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14478            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14479        }
14480
14481        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14482            // Re installation failed. Restore old information
14483            // Remove new pkg information
14484            if (newPackage != null) {
14485                removeInstalledPackageLI(newPackage, true);
14486            }
14487            // Add back the old system package
14488            try {
14489                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14490            } catch (PackageManagerException e) {
14491                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14492            }
14493
14494            synchronized (mPackages) {
14495                if (disabledSystem) {
14496                    enableSystemPackageLPw(deletedPackage);
14497                }
14498
14499                // Ensure the installer package name up to date
14500                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14501
14502                // Update permissions for restored package
14503                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14504
14505                mSettings.writeLPr();
14506            }
14507
14508            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14509                    + " after failed upgrade");
14510        }
14511    }
14512
14513    /**
14514     * Checks whether the parent or any of the child packages have a change shared
14515     * user. For a package to be a valid update the shred users of the parent and
14516     * the children should match. We may later support changing child shared users.
14517     * @param oldPkg The updated package.
14518     * @param newPkg The update package.
14519     * @return The shared user that change between the versions.
14520     */
14521    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14522            PackageParser.Package newPkg) {
14523        // Check parent shared user
14524        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14525            return newPkg.packageName;
14526        }
14527        // Check child shared users
14528        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14529        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14530        for (int i = 0; i < newChildCount; i++) {
14531            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14532            // If this child was present, did it have the same shared user?
14533            for (int j = 0; j < oldChildCount; j++) {
14534                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14535                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14536                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14537                    return newChildPkg.packageName;
14538                }
14539            }
14540        }
14541        return null;
14542    }
14543
14544    private void removeNativeBinariesLI(PackageSetting ps) {
14545        // Remove the lib path for the parent package
14546        if (ps != null) {
14547            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14548            // Remove the lib path for the child packages
14549            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14550            for (int i = 0; i < childCount; i++) {
14551                PackageSetting childPs = null;
14552                synchronized (mPackages) {
14553                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14554                }
14555                if (childPs != null) {
14556                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14557                            .legacyNativeLibraryPathString);
14558                }
14559            }
14560        }
14561    }
14562
14563    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14564        // Enable the parent package
14565        mSettings.enableSystemPackageLPw(pkg.packageName);
14566        // Enable the child packages
14567        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14568        for (int i = 0; i < childCount; i++) {
14569            PackageParser.Package childPkg = pkg.childPackages.get(i);
14570            mSettings.enableSystemPackageLPw(childPkg.packageName);
14571        }
14572    }
14573
14574    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14575            PackageParser.Package newPkg) {
14576        // Disable the parent package (parent always replaced)
14577        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14578        // Disable the child packages
14579        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14580        for (int i = 0; i < childCount; i++) {
14581            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14582            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14583            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14584        }
14585        return disabled;
14586    }
14587
14588    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14589            String installerPackageName) {
14590        // Enable the parent package
14591        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14592        // Enable the child packages
14593        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14594        for (int i = 0; i < childCount; i++) {
14595            PackageParser.Package childPkg = pkg.childPackages.get(i);
14596            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14597        }
14598    }
14599
14600    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14601        // Collect all used permissions in the UID
14602        ArraySet<String> usedPermissions = new ArraySet<>();
14603        final int packageCount = su.packages.size();
14604        for (int i = 0; i < packageCount; i++) {
14605            PackageSetting ps = su.packages.valueAt(i);
14606            if (ps.pkg == null) {
14607                continue;
14608            }
14609            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14610            for (int j = 0; j < requestedPermCount; j++) {
14611                String permission = ps.pkg.requestedPermissions.get(j);
14612                BasePermission bp = mSettings.mPermissions.get(permission);
14613                if (bp != null) {
14614                    usedPermissions.add(permission);
14615                }
14616            }
14617        }
14618
14619        PermissionsState permissionsState = su.getPermissionsState();
14620        // Prune install permissions
14621        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14622        final int installPermCount = installPermStates.size();
14623        for (int i = installPermCount - 1; i >= 0;  i--) {
14624            PermissionState permissionState = installPermStates.get(i);
14625            if (!usedPermissions.contains(permissionState.getName())) {
14626                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14627                if (bp != null) {
14628                    permissionsState.revokeInstallPermission(bp);
14629                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14630                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14631                }
14632            }
14633        }
14634
14635        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14636
14637        // Prune runtime permissions
14638        for (int userId : allUserIds) {
14639            List<PermissionState> runtimePermStates = permissionsState
14640                    .getRuntimePermissionStates(userId);
14641            final int runtimePermCount = runtimePermStates.size();
14642            for (int i = runtimePermCount - 1; i >= 0; i--) {
14643                PermissionState permissionState = runtimePermStates.get(i);
14644                if (!usedPermissions.contains(permissionState.getName())) {
14645                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14646                    if (bp != null) {
14647                        permissionsState.revokeRuntimePermission(bp, userId);
14648                        permissionsState.updatePermissionFlags(bp, userId,
14649                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14650                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14651                                runtimePermissionChangedUserIds, userId);
14652                    }
14653                }
14654            }
14655        }
14656
14657        return runtimePermissionChangedUserIds;
14658    }
14659
14660    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14661            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14662        // Update the parent package setting
14663        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14664                res, user);
14665        // Update the child packages setting
14666        final int childCount = (newPackage.childPackages != null)
14667                ? newPackage.childPackages.size() : 0;
14668        for (int i = 0; i < childCount; i++) {
14669            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14670            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14671            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14672                    childRes.origUsers, childRes, user);
14673        }
14674    }
14675
14676    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14677            String installerPackageName, int[] allUsers, int[] installedForUsers,
14678            PackageInstalledInfo res, UserHandle user) {
14679        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14680
14681        String pkgName = newPackage.packageName;
14682        synchronized (mPackages) {
14683            //write settings. the installStatus will be incomplete at this stage.
14684            //note that the new package setting would have already been
14685            //added to mPackages. It hasn't been persisted yet.
14686            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14687            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14688            mSettings.writeLPr();
14689            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14690        }
14691
14692        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14693        synchronized (mPackages) {
14694            updatePermissionsLPw(newPackage.packageName, newPackage,
14695                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14696                            ? UPDATE_PERMISSIONS_ALL : 0));
14697            // For system-bundled packages, we assume that installing an upgraded version
14698            // of the package implies that the user actually wants to run that new code,
14699            // so we enable the package.
14700            PackageSetting ps = mSettings.mPackages.get(pkgName);
14701            final int userId = user.getIdentifier();
14702            if (ps != null) {
14703                if (isSystemApp(newPackage)) {
14704                    if (DEBUG_INSTALL) {
14705                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14706                    }
14707                    // Enable system package for requested users
14708                    if (res.origUsers != null) {
14709                        for (int origUserId : res.origUsers) {
14710                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14711                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14712                                        origUserId, installerPackageName);
14713                            }
14714                        }
14715                    }
14716                    // Also convey the prior install/uninstall state
14717                    if (allUsers != null && installedForUsers != null) {
14718                        for (int currentUserId : allUsers) {
14719                            final boolean installed = ArrayUtils.contains(
14720                                    installedForUsers, currentUserId);
14721                            if (DEBUG_INSTALL) {
14722                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14723                            }
14724                            ps.setInstalled(installed, currentUserId);
14725                        }
14726                        // these install state changes will be persisted in the
14727                        // upcoming call to mSettings.writeLPr().
14728                    }
14729                }
14730                // It's implied that when a user requests installation, they want the app to be
14731                // installed and enabled.
14732                if (userId != UserHandle.USER_ALL) {
14733                    ps.setInstalled(true, userId);
14734                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14735                }
14736            }
14737            res.name = pkgName;
14738            res.uid = newPackage.applicationInfo.uid;
14739            res.pkg = newPackage;
14740            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14741            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14742            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14743            //to update install status
14744            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14745            mSettings.writeLPr();
14746            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14747        }
14748
14749        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14750    }
14751
14752    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14753        try {
14754            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14755            installPackageLI(args, res);
14756        } finally {
14757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14758        }
14759    }
14760
14761    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14762        final int installFlags = args.installFlags;
14763        final String installerPackageName = args.installerPackageName;
14764        final String volumeUuid = args.volumeUuid;
14765        final File tmpPackageFile = new File(args.getCodePath());
14766        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14767        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14768                || (args.volumeUuid != null));
14769        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14770        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14771        boolean replace = false;
14772        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14773        if (args.move != null) {
14774            // moving a complete application; perform an initial scan on the new install location
14775            scanFlags |= SCAN_INITIAL;
14776        }
14777        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14778            scanFlags |= SCAN_DONT_KILL_APP;
14779        }
14780
14781        // Result object to be returned
14782        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14783
14784        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14785
14786        // Sanity check
14787        if (ephemeral && (forwardLocked || onExternal)) {
14788            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14789                    + " external=" + onExternal);
14790            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14791            return;
14792        }
14793
14794        // Retrieve PackageSettings and parse package
14795        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14796                | PackageParser.PARSE_ENFORCE_CODE
14797                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14798                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14799                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14800                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14801        PackageParser pp = new PackageParser();
14802        pp.setSeparateProcesses(mSeparateProcesses);
14803        pp.setDisplayMetrics(mMetrics);
14804
14805        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14806        final PackageParser.Package pkg;
14807        try {
14808            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14809        } catch (PackageParserException e) {
14810            res.setError("Failed parse during installPackageLI", e);
14811            return;
14812        } finally {
14813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14814        }
14815
14816        // If we are installing a clustered package add results for the children
14817        if (pkg.childPackages != null) {
14818            synchronized (mPackages) {
14819                final int childCount = pkg.childPackages.size();
14820                for (int i = 0; i < childCount; i++) {
14821                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14822                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14823                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14824                    childRes.pkg = childPkg;
14825                    childRes.name = childPkg.packageName;
14826                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14827                    if (childPs != null) {
14828                        childRes.origUsers = childPs.queryInstalledUsers(
14829                                sUserManager.getUserIds(), true);
14830                    }
14831                    if ((mPackages.containsKey(childPkg.packageName))) {
14832                        childRes.removedInfo = new PackageRemovedInfo();
14833                        childRes.removedInfo.removedPackage = childPkg.packageName;
14834                    }
14835                    if (res.addedChildPackages == null) {
14836                        res.addedChildPackages = new ArrayMap<>();
14837                    }
14838                    res.addedChildPackages.put(childPkg.packageName, childRes);
14839                }
14840            }
14841        }
14842
14843        // If package doesn't declare API override, mark that we have an install
14844        // time CPU ABI override.
14845        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14846            pkg.cpuAbiOverride = args.abiOverride;
14847        }
14848
14849        String pkgName = res.name = pkg.packageName;
14850        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14851            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14852                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14853                return;
14854            }
14855        }
14856
14857        try {
14858            // either use what we've been given or parse directly from the APK
14859            if (args.certificates != null) {
14860                try {
14861                    PackageParser.populateCertificates(pkg, args.certificates);
14862                } catch (PackageParserException e) {
14863                    // there was something wrong with the certificates we were given;
14864                    // try to pull them from the APK
14865                    PackageParser.collectCertificates(pkg, parseFlags);
14866                }
14867            } else {
14868                PackageParser.collectCertificates(pkg, parseFlags);
14869            }
14870        } catch (PackageParserException e) {
14871            res.setError("Failed collect during installPackageLI", e);
14872            return;
14873        }
14874
14875        // Get rid of all references to package scan path via parser.
14876        pp = null;
14877        String oldCodePath = null;
14878        boolean systemApp = false;
14879        synchronized (mPackages) {
14880            // Check if installing already existing package
14881            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14882                String oldName = mSettings.mRenamedPackages.get(pkgName);
14883                if (pkg.mOriginalPackages != null
14884                        && pkg.mOriginalPackages.contains(oldName)
14885                        && mPackages.containsKey(oldName)) {
14886                    // This package is derived from an original package,
14887                    // and this device has been updating from that original
14888                    // name.  We must continue using the original name, so
14889                    // rename the new package here.
14890                    pkg.setPackageName(oldName);
14891                    pkgName = pkg.packageName;
14892                    replace = true;
14893                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14894                            + oldName + " pkgName=" + pkgName);
14895                } else if (mPackages.containsKey(pkgName)) {
14896                    // This package, under its official name, already exists
14897                    // on the device; we should replace it.
14898                    replace = true;
14899                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14900                }
14901
14902                // Child packages are installed through the parent package
14903                if (pkg.parentPackage != null) {
14904                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14905                            "Package " + pkg.packageName + " is child of package "
14906                                    + pkg.parentPackage.parentPackage + ". Child packages "
14907                                    + "can be updated only through the parent package.");
14908                    return;
14909                }
14910
14911                if (replace) {
14912                    // Prevent apps opting out from runtime permissions
14913                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14914                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14915                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14916                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14917                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14918                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14919                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14920                                        + " doesn't support runtime permissions but the old"
14921                                        + " target SDK " + oldTargetSdk + " does.");
14922                        return;
14923                    }
14924
14925                    // Prevent installing of child packages
14926                    if (oldPackage.parentPackage != null) {
14927                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14928                                "Package " + pkg.packageName + " is child of package "
14929                                        + oldPackage.parentPackage + ". Child packages "
14930                                        + "can be updated only through the parent package.");
14931                        return;
14932                    }
14933                }
14934            }
14935
14936            PackageSetting ps = mSettings.mPackages.get(pkgName);
14937            if (ps != null) {
14938                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14939
14940                // Quick sanity check that we're signed correctly if updating;
14941                // we'll check this again later when scanning, but we want to
14942                // bail early here before tripping over redefined permissions.
14943                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14944                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14945                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14946                                + pkg.packageName + " upgrade keys do not match the "
14947                                + "previously installed version");
14948                        return;
14949                    }
14950                } else {
14951                    try {
14952                        verifySignaturesLP(ps, pkg);
14953                    } catch (PackageManagerException e) {
14954                        res.setError(e.error, e.getMessage());
14955                        return;
14956                    }
14957                }
14958
14959                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14960                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14961                    systemApp = (ps.pkg.applicationInfo.flags &
14962                            ApplicationInfo.FLAG_SYSTEM) != 0;
14963                }
14964                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14965            }
14966
14967            // Check whether the newly-scanned package wants to define an already-defined perm
14968            int N = pkg.permissions.size();
14969            for (int i = N-1; i >= 0; i--) {
14970                PackageParser.Permission perm = pkg.permissions.get(i);
14971                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14972                if (bp != null) {
14973                    // If the defining package is signed with our cert, it's okay.  This
14974                    // also includes the "updating the same package" case, of course.
14975                    // "updating same package" could also involve key-rotation.
14976                    final boolean sigsOk;
14977                    if (bp.sourcePackage.equals(pkg.packageName)
14978                            && (bp.packageSetting instanceof PackageSetting)
14979                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14980                                    scanFlags))) {
14981                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14982                    } else {
14983                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14984                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14985                    }
14986                    if (!sigsOk) {
14987                        // If the owning package is the system itself, we log but allow
14988                        // install to proceed; we fail the install on all other permission
14989                        // redefinitions.
14990                        if (!bp.sourcePackage.equals("android")) {
14991                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14992                                    + pkg.packageName + " attempting to redeclare permission "
14993                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14994                            res.origPermission = perm.info.name;
14995                            res.origPackage = bp.sourcePackage;
14996                            return;
14997                        } else {
14998                            Slog.w(TAG, "Package " + pkg.packageName
14999                                    + " attempting to redeclare system permission "
15000                                    + perm.info.name + "; ignoring new declaration");
15001                            pkg.permissions.remove(i);
15002                        }
15003                    }
15004                }
15005            }
15006        }
15007
15008        if (systemApp) {
15009            if (onExternal) {
15010                // Abort update; system app can't be replaced with app on sdcard
15011                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15012                        "Cannot install updates to system apps on sdcard");
15013                return;
15014            } else if (ephemeral) {
15015                // Abort update; system app can't be replaced with an ephemeral app
15016                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15017                        "Cannot update a system app with an ephemeral app");
15018                return;
15019            }
15020        }
15021
15022        if (args.move != null) {
15023            // We did an in-place move, so dex is ready to roll
15024            scanFlags |= SCAN_NO_DEX;
15025            scanFlags |= SCAN_MOVE;
15026
15027            synchronized (mPackages) {
15028                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15029                if (ps == null) {
15030                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15031                            "Missing settings for moved package " + pkgName);
15032                }
15033
15034                // We moved the entire application as-is, so bring over the
15035                // previously derived ABI information.
15036                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15037                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15038            }
15039
15040        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15041            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15042            scanFlags |= SCAN_NO_DEX;
15043
15044            try {
15045                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15046                    args.abiOverride : pkg.cpuAbiOverride);
15047                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15048                        true /* extract libs */);
15049            } catch (PackageManagerException pme) {
15050                Slog.e(TAG, "Error deriving application ABI", pme);
15051                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15052                return;
15053            }
15054
15055            // Shared libraries for the package need to be updated.
15056            synchronized (mPackages) {
15057                try {
15058                    updateSharedLibrariesLPw(pkg, null);
15059                } catch (PackageManagerException e) {
15060                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15061                }
15062            }
15063            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15064            // Do not run PackageDexOptimizer through the local performDexOpt
15065            // method because `pkg` may not be in `mPackages` yet.
15066            //
15067            // Also, don't fail application installs if the dexopt step fails.
15068            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15069                    null /* instructionSets */, false /* checkProfiles */,
15070                    getCompilerFilterForReason(REASON_INSTALL),
15071                    getOrCreateCompilerPackageStats(pkg));
15072            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15073
15074            // Notify BackgroundDexOptService that the package has been changed.
15075            // If this is an update of a package which used to fail to compile,
15076            // BDOS will remove it from its blacklist.
15077            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15078        }
15079
15080        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15081            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15082            return;
15083        }
15084
15085        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15086
15087        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15088                "installPackageLI")) {
15089            if (replace) {
15090                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15091                        installerPackageName, res);
15092            } else {
15093                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15094                        args.user, installerPackageName, volumeUuid, res);
15095            }
15096        }
15097        synchronized (mPackages) {
15098            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15099            if (ps != null) {
15100                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15101            }
15102
15103            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15104            for (int i = 0; i < childCount; i++) {
15105                PackageParser.Package childPkg = pkg.childPackages.get(i);
15106                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15107                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15108                if (childPs != null) {
15109                    childRes.newUsers = childPs.queryInstalledUsers(
15110                            sUserManager.getUserIds(), true);
15111                }
15112            }
15113        }
15114    }
15115
15116    private void startIntentFilterVerifications(int userId, boolean replacing,
15117            PackageParser.Package pkg) {
15118        if (mIntentFilterVerifierComponent == null) {
15119            Slog.w(TAG, "No IntentFilter verification will not be done as "
15120                    + "there is no IntentFilterVerifier available!");
15121            return;
15122        }
15123
15124        final int verifierUid = getPackageUid(
15125                mIntentFilterVerifierComponent.getPackageName(),
15126                MATCH_DEBUG_TRIAGED_MISSING,
15127                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15128
15129        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15130        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15131        mHandler.sendMessage(msg);
15132
15133        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15134        for (int i = 0; i < childCount; i++) {
15135            PackageParser.Package childPkg = pkg.childPackages.get(i);
15136            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15137            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15138            mHandler.sendMessage(msg);
15139        }
15140    }
15141
15142    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15143            PackageParser.Package pkg) {
15144        int size = pkg.activities.size();
15145        if (size == 0) {
15146            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15147                    "No activity, so no need to verify any IntentFilter!");
15148            return;
15149        }
15150
15151        final boolean hasDomainURLs = hasDomainURLs(pkg);
15152        if (!hasDomainURLs) {
15153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15154                    "No domain URLs, so no need to verify any IntentFilter!");
15155            return;
15156        }
15157
15158        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15159                + " if any IntentFilter from the " + size
15160                + " Activities needs verification ...");
15161
15162        int count = 0;
15163        final String packageName = pkg.packageName;
15164
15165        synchronized (mPackages) {
15166            // If this is a new install and we see that we've already run verification for this
15167            // package, we have nothing to do: it means the state was restored from backup.
15168            if (!replacing) {
15169                IntentFilterVerificationInfo ivi =
15170                        mSettings.getIntentFilterVerificationLPr(packageName);
15171                if (ivi != null) {
15172                    if (DEBUG_DOMAIN_VERIFICATION) {
15173                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15174                                + ivi.getStatusString());
15175                    }
15176                    return;
15177                }
15178            }
15179
15180            // If any filters need to be verified, then all need to be.
15181            boolean needToVerify = false;
15182            for (PackageParser.Activity a : pkg.activities) {
15183                for (ActivityIntentInfo filter : a.intents) {
15184                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15185                        if (DEBUG_DOMAIN_VERIFICATION) {
15186                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15187                        }
15188                        needToVerify = true;
15189                        break;
15190                    }
15191                }
15192            }
15193
15194            if (needToVerify) {
15195                final int verificationId = mIntentFilterVerificationToken++;
15196                for (PackageParser.Activity a : pkg.activities) {
15197                    for (ActivityIntentInfo filter : a.intents) {
15198                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15199                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15200                                    "Verification needed for IntentFilter:" + filter.toString());
15201                            mIntentFilterVerifier.addOneIntentFilterVerification(
15202                                    verifierUid, userId, verificationId, filter, packageName);
15203                            count++;
15204                        }
15205                    }
15206                }
15207            }
15208        }
15209
15210        if (count > 0) {
15211            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15212                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15213                    +  " for userId:" + userId);
15214            mIntentFilterVerifier.startVerifications(userId);
15215        } else {
15216            if (DEBUG_DOMAIN_VERIFICATION) {
15217                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15218            }
15219        }
15220    }
15221
15222    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15223        final ComponentName cn  = filter.activity.getComponentName();
15224        final String packageName = cn.getPackageName();
15225
15226        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15227                packageName);
15228        if (ivi == null) {
15229            return true;
15230        }
15231        int status = ivi.getStatus();
15232        switch (status) {
15233            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15234            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15235                return true;
15236
15237            default:
15238                // Nothing to do
15239                return false;
15240        }
15241    }
15242
15243    private static boolean isMultiArch(ApplicationInfo info) {
15244        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15245    }
15246
15247    private static boolean isExternal(PackageParser.Package pkg) {
15248        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15249    }
15250
15251    private static boolean isExternal(PackageSetting ps) {
15252        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15253    }
15254
15255    private static boolean isEphemeral(PackageParser.Package pkg) {
15256        return pkg.applicationInfo.isEphemeralApp();
15257    }
15258
15259    private static boolean isEphemeral(PackageSetting ps) {
15260        return ps.pkg != null && isEphemeral(ps.pkg);
15261    }
15262
15263    private static boolean isSystemApp(PackageParser.Package pkg) {
15264        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15265    }
15266
15267    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15268        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15269    }
15270
15271    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15272        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15273    }
15274
15275    private static boolean isSystemApp(PackageSetting ps) {
15276        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15277    }
15278
15279    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15280        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15281    }
15282
15283    private int packageFlagsToInstallFlags(PackageSetting ps) {
15284        int installFlags = 0;
15285        if (isEphemeral(ps)) {
15286            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15287        }
15288        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15289            // This existing package was an external ASEC install when we have
15290            // the external flag without a UUID
15291            installFlags |= PackageManager.INSTALL_EXTERNAL;
15292        }
15293        if (ps.isForwardLocked()) {
15294            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15295        }
15296        return installFlags;
15297    }
15298
15299    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15300        if (isExternal(pkg)) {
15301            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15302                return StorageManager.UUID_PRIMARY_PHYSICAL;
15303            } else {
15304                return pkg.volumeUuid;
15305            }
15306        } else {
15307            return StorageManager.UUID_PRIVATE_INTERNAL;
15308        }
15309    }
15310
15311    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15312        if (isExternal(pkg)) {
15313            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15314                return mSettings.getExternalVersion();
15315            } else {
15316                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15317            }
15318        } else {
15319            return mSettings.getInternalVersion();
15320        }
15321    }
15322
15323    private void deleteTempPackageFiles() {
15324        final FilenameFilter filter = new FilenameFilter() {
15325            public boolean accept(File dir, String name) {
15326                return name.startsWith("vmdl") && name.endsWith(".tmp");
15327            }
15328        };
15329        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15330            file.delete();
15331        }
15332    }
15333
15334    @Override
15335    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15336            int flags) {
15337        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15338                flags);
15339    }
15340
15341    @Override
15342    public void deletePackage(final String packageName,
15343            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15344        mContext.enforceCallingOrSelfPermission(
15345                android.Manifest.permission.DELETE_PACKAGES, null);
15346        Preconditions.checkNotNull(packageName);
15347        Preconditions.checkNotNull(observer);
15348        final int uid = Binder.getCallingUid();
15349        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15350        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15351        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15352            mContext.enforceCallingOrSelfPermission(
15353                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15354                    "deletePackage for user " + userId);
15355        }
15356
15357        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15358            try {
15359                observer.onPackageDeleted(packageName,
15360                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15361            } catch (RemoteException re) {
15362            }
15363            return;
15364        }
15365
15366        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15367            try {
15368                observer.onPackageDeleted(packageName,
15369                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15370            } catch (RemoteException re) {
15371            }
15372            return;
15373        }
15374
15375        if (DEBUG_REMOVE) {
15376            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15377                    + " deleteAllUsers: " + deleteAllUsers );
15378        }
15379        // Queue up an async operation since the package deletion may take a little while.
15380        mHandler.post(new Runnable() {
15381            public void run() {
15382                mHandler.removeCallbacks(this);
15383                int returnCode;
15384                if (!deleteAllUsers) {
15385                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15386                } else {
15387                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15388                    // If nobody is blocking uninstall, proceed with delete for all users
15389                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15390                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15391                    } else {
15392                        // Otherwise uninstall individually for users with blockUninstalls=false
15393                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15394                        for (int userId : users) {
15395                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15396                                returnCode = deletePackageX(packageName, userId, userFlags);
15397                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15398                                    Slog.w(TAG, "Package delete failed for user " + userId
15399                                            + ", returnCode " + returnCode);
15400                                }
15401                            }
15402                        }
15403                        // The app has only been marked uninstalled for certain users.
15404                        // We still need to report that delete was blocked
15405                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15406                    }
15407                }
15408                try {
15409                    observer.onPackageDeleted(packageName, returnCode, null);
15410                } catch (RemoteException e) {
15411                    Log.i(TAG, "Observer no longer exists.");
15412                } //end catch
15413            } //end run
15414        });
15415    }
15416
15417    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15418        int[] result = EMPTY_INT_ARRAY;
15419        for (int userId : userIds) {
15420            if (getBlockUninstallForUser(packageName, userId)) {
15421                result = ArrayUtils.appendInt(result, userId);
15422            }
15423        }
15424        return result;
15425    }
15426
15427    @Override
15428    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15429        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15430    }
15431
15432    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15433        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15434                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15435        try {
15436            if (dpm != null) {
15437                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15438                        /* callingUserOnly =*/ false);
15439                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15440                        : deviceOwnerComponentName.getPackageName();
15441                // Does the package contains the device owner?
15442                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15443                // this check is probably not needed, since DO should be registered as a device
15444                // admin on some user too. (Original bug for this: b/17657954)
15445                if (packageName.equals(deviceOwnerPackageName)) {
15446                    return true;
15447                }
15448                // Does it contain a device admin for any user?
15449                int[] users;
15450                if (userId == UserHandle.USER_ALL) {
15451                    users = sUserManager.getUserIds();
15452                } else {
15453                    users = new int[]{userId};
15454                }
15455                for (int i = 0; i < users.length; ++i) {
15456                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15457                        return true;
15458                    }
15459                }
15460            }
15461        } catch (RemoteException e) {
15462        }
15463        return false;
15464    }
15465
15466    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15467        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15468    }
15469
15470    /**
15471     *  This method is an internal method that could be get invoked either
15472     *  to delete an installed package or to clean up a failed installation.
15473     *  After deleting an installed package, a broadcast is sent to notify any
15474     *  listeners that the package has been removed. For cleaning up a failed
15475     *  installation, the broadcast is not necessary since the package's
15476     *  installation wouldn't have sent the initial broadcast either
15477     *  The key steps in deleting a package are
15478     *  deleting the package information in internal structures like mPackages,
15479     *  deleting the packages base directories through installd
15480     *  updating mSettings to reflect current status
15481     *  persisting settings for later use
15482     *  sending a broadcast if necessary
15483     */
15484    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15485        final PackageRemovedInfo info = new PackageRemovedInfo();
15486        final boolean res;
15487
15488        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15489                ? UserHandle.USER_ALL : userId;
15490
15491        if (isPackageDeviceAdmin(packageName, removeUser)) {
15492            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15493            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15494        }
15495
15496        PackageSetting uninstalledPs = null;
15497
15498        // for the uninstall-updates case and restricted profiles, remember the per-
15499        // user handle installed state
15500        int[] allUsers;
15501        synchronized (mPackages) {
15502            uninstalledPs = mSettings.mPackages.get(packageName);
15503            if (uninstalledPs == null) {
15504                Slog.w(TAG, "Not removing non-existent package " + packageName);
15505                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15506            }
15507            allUsers = sUserManager.getUserIds();
15508            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15509        }
15510
15511        final int freezeUser;
15512        if (isUpdatedSystemApp(uninstalledPs)
15513                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15514            // We're downgrading a system app, which will apply to all users, so
15515            // freeze them all during the downgrade
15516            freezeUser = UserHandle.USER_ALL;
15517        } else {
15518            freezeUser = removeUser;
15519        }
15520
15521        synchronized (mInstallLock) {
15522            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15523            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15524                    deleteFlags, "deletePackageX")) {
15525                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15526                        deleteFlags | REMOVE_CHATTY, info, true, null);
15527            }
15528            synchronized (mPackages) {
15529                if (res) {
15530                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15531                }
15532            }
15533        }
15534
15535        if (res) {
15536            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15537            info.sendPackageRemovedBroadcasts(killApp);
15538            info.sendSystemPackageUpdatedBroadcasts();
15539            info.sendSystemPackageAppearedBroadcasts();
15540        }
15541        // Force a gc here.
15542        Runtime.getRuntime().gc();
15543        // Delete the resources here after sending the broadcast to let
15544        // other processes clean up before deleting resources.
15545        if (info.args != null) {
15546            synchronized (mInstallLock) {
15547                info.args.doPostDeleteLI(true);
15548            }
15549        }
15550
15551        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15552    }
15553
15554    class PackageRemovedInfo {
15555        String removedPackage;
15556        int uid = -1;
15557        int removedAppId = -1;
15558        int[] origUsers;
15559        int[] removedUsers = null;
15560        boolean isRemovedPackageSystemUpdate = false;
15561        boolean isUpdate;
15562        boolean dataRemoved;
15563        boolean removedForAllUsers;
15564        // Clean up resources deleted packages.
15565        InstallArgs args = null;
15566        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15567        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15568
15569        void sendPackageRemovedBroadcasts(boolean killApp) {
15570            sendPackageRemovedBroadcastInternal(killApp);
15571            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15572            for (int i = 0; i < childCount; i++) {
15573                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15574                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15575            }
15576        }
15577
15578        void sendSystemPackageUpdatedBroadcasts() {
15579            if (isRemovedPackageSystemUpdate) {
15580                sendSystemPackageUpdatedBroadcastsInternal();
15581                final int childCount = (removedChildPackages != null)
15582                        ? removedChildPackages.size() : 0;
15583                for (int i = 0; i < childCount; i++) {
15584                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15585                    if (childInfo.isRemovedPackageSystemUpdate) {
15586                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15587                    }
15588                }
15589            }
15590        }
15591
15592        void sendSystemPackageAppearedBroadcasts() {
15593            final int packageCount = (appearedChildPackages != null)
15594                    ? appearedChildPackages.size() : 0;
15595            for (int i = 0; i < packageCount; i++) {
15596                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15597                for (int userId : installedInfo.newUsers) {
15598                    sendPackageAddedForUser(installedInfo.name, true,
15599                            UserHandle.getAppId(installedInfo.uid), userId);
15600                }
15601            }
15602        }
15603
15604        private void sendSystemPackageUpdatedBroadcastsInternal() {
15605            Bundle extras = new Bundle(2);
15606            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15607            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15608            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15609                    extras, 0, null, null, null);
15610            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15611                    extras, 0, null, null, null);
15612            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15613                    null, 0, removedPackage, null, null);
15614        }
15615
15616        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15617            Bundle extras = new Bundle(2);
15618            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15619            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15620            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15621            if (isUpdate || isRemovedPackageSystemUpdate) {
15622                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15623            }
15624            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15625            if (removedPackage != null) {
15626                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15627                        extras, 0, null, null, removedUsers);
15628                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15629                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15630                            removedPackage, extras, 0, null, null, removedUsers);
15631                }
15632            }
15633            if (removedAppId >= 0) {
15634                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15635                        removedUsers);
15636            }
15637        }
15638    }
15639
15640    /*
15641     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15642     * flag is not set, the data directory is removed as well.
15643     * make sure this flag is set for partially installed apps. If not its meaningless to
15644     * delete a partially installed application.
15645     */
15646    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15647            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15648        String packageName = ps.name;
15649        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15650        // Retrieve object to delete permissions for shared user later on
15651        final PackageParser.Package deletedPkg;
15652        final PackageSetting deletedPs;
15653        // reader
15654        synchronized (mPackages) {
15655            deletedPkg = mPackages.get(packageName);
15656            deletedPs = mSettings.mPackages.get(packageName);
15657            if (outInfo != null) {
15658                outInfo.removedPackage = packageName;
15659                outInfo.removedUsers = deletedPs != null
15660                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15661                        : null;
15662            }
15663        }
15664
15665        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15666
15667        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15668            final PackageParser.Package resolvedPkg;
15669            if (deletedPkg != null) {
15670                resolvedPkg = deletedPkg;
15671            } else {
15672                // We don't have a parsed package when it lives on an ejected
15673                // adopted storage device, so fake something together
15674                resolvedPkg = new PackageParser.Package(ps.name);
15675                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15676            }
15677            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15678                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15679            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15680            if (outInfo != null) {
15681                outInfo.dataRemoved = true;
15682            }
15683            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15684        }
15685
15686        // writer
15687        synchronized (mPackages) {
15688            if (deletedPs != null) {
15689                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15690                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15691                    clearDefaultBrowserIfNeeded(packageName);
15692                    if (outInfo != null) {
15693                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15694                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15695                    }
15696                    updatePermissionsLPw(deletedPs.name, null, 0);
15697                    if (deletedPs.sharedUser != null) {
15698                        // Remove permissions associated with package. Since runtime
15699                        // permissions are per user we have to kill the removed package
15700                        // or packages running under the shared user of the removed
15701                        // package if revoking the permissions requested only by the removed
15702                        // package is successful and this causes a change in gids.
15703                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15704                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15705                                    userId);
15706                            if (userIdToKill == UserHandle.USER_ALL
15707                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15708                                // If gids changed for this user, kill all affected packages.
15709                                mHandler.post(new Runnable() {
15710                                    @Override
15711                                    public void run() {
15712                                        // This has to happen with no lock held.
15713                                        killApplication(deletedPs.name, deletedPs.appId,
15714                                                KILL_APP_REASON_GIDS_CHANGED);
15715                                    }
15716                                });
15717                                break;
15718                            }
15719                        }
15720                    }
15721                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15722                }
15723                // make sure to preserve per-user disabled state if this removal was just
15724                // a downgrade of a system app to the factory package
15725                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15726                    if (DEBUG_REMOVE) {
15727                        Slog.d(TAG, "Propagating install state across downgrade");
15728                    }
15729                    for (int userId : allUserHandles) {
15730                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15731                        if (DEBUG_REMOVE) {
15732                            Slog.d(TAG, "    user " + userId + " => " + installed);
15733                        }
15734                        ps.setInstalled(installed, userId);
15735                    }
15736                }
15737            }
15738            // can downgrade to reader
15739            if (writeSettings) {
15740                // Save settings now
15741                mSettings.writeLPr();
15742            }
15743        }
15744        if (outInfo != null) {
15745            // A user ID was deleted here. Go through all users and remove it
15746            // from KeyStore.
15747            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15748        }
15749    }
15750
15751    static boolean locationIsPrivileged(File path) {
15752        try {
15753            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15754                    .getCanonicalPath();
15755            return path.getCanonicalPath().startsWith(privilegedAppDir);
15756        } catch (IOException e) {
15757            Slog.e(TAG, "Unable to access code path " + path);
15758        }
15759        return false;
15760    }
15761
15762    /*
15763     * Tries to delete system package.
15764     */
15765    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15766            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15767            boolean writeSettings) {
15768        if (deletedPs.parentPackageName != null) {
15769            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15770            return false;
15771        }
15772
15773        final boolean applyUserRestrictions
15774                = (allUserHandles != null) && (outInfo.origUsers != null);
15775        final PackageSetting disabledPs;
15776        // Confirm if the system package has been updated
15777        // An updated system app can be deleted. This will also have to restore
15778        // the system pkg from system partition
15779        // reader
15780        synchronized (mPackages) {
15781            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15782        }
15783
15784        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15785                + " disabledPs=" + disabledPs);
15786
15787        if (disabledPs == null) {
15788            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15789            return false;
15790        } else if (DEBUG_REMOVE) {
15791            Slog.d(TAG, "Deleting system pkg from data partition");
15792        }
15793
15794        if (DEBUG_REMOVE) {
15795            if (applyUserRestrictions) {
15796                Slog.d(TAG, "Remembering install states:");
15797                for (int userId : allUserHandles) {
15798                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15799                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15800                }
15801            }
15802        }
15803
15804        // Delete the updated package
15805        outInfo.isRemovedPackageSystemUpdate = true;
15806        if (outInfo.removedChildPackages != null) {
15807            final int childCount = (deletedPs.childPackageNames != null)
15808                    ? deletedPs.childPackageNames.size() : 0;
15809            for (int i = 0; i < childCount; i++) {
15810                String childPackageName = deletedPs.childPackageNames.get(i);
15811                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15812                        .contains(childPackageName)) {
15813                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15814                            childPackageName);
15815                    if (childInfo != null) {
15816                        childInfo.isRemovedPackageSystemUpdate = true;
15817                    }
15818                }
15819            }
15820        }
15821
15822        if (disabledPs.versionCode < deletedPs.versionCode) {
15823            // Delete data for downgrades
15824            flags &= ~PackageManager.DELETE_KEEP_DATA;
15825        } else {
15826            // Preserve data by setting flag
15827            flags |= PackageManager.DELETE_KEEP_DATA;
15828        }
15829
15830        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15831                outInfo, writeSettings, disabledPs.pkg);
15832        if (!ret) {
15833            return false;
15834        }
15835
15836        // writer
15837        synchronized (mPackages) {
15838            // Reinstate the old system package
15839            enableSystemPackageLPw(disabledPs.pkg);
15840            // Remove any native libraries from the upgraded package.
15841            removeNativeBinariesLI(deletedPs);
15842        }
15843
15844        // Install the system package
15845        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15846        int parseFlags = mDefParseFlags
15847                | PackageParser.PARSE_MUST_BE_APK
15848                | PackageParser.PARSE_IS_SYSTEM
15849                | PackageParser.PARSE_IS_SYSTEM_DIR;
15850        if (locationIsPrivileged(disabledPs.codePath)) {
15851            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15852        }
15853
15854        final PackageParser.Package newPkg;
15855        try {
15856            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15857        } catch (PackageManagerException e) {
15858            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15859                    + e.getMessage());
15860            return false;
15861        }
15862
15863        prepareAppDataAfterInstallLIF(newPkg);
15864
15865        // writer
15866        synchronized (mPackages) {
15867            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15868
15869            // Propagate the permissions state as we do not want to drop on the floor
15870            // runtime permissions. The update permissions method below will take
15871            // care of removing obsolete permissions and grant install permissions.
15872            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15873            updatePermissionsLPw(newPkg.packageName, newPkg,
15874                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15875
15876            if (applyUserRestrictions) {
15877                if (DEBUG_REMOVE) {
15878                    Slog.d(TAG, "Propagating install state across reinstall");
15879                }
15880                for (int userId : allUserHandles) {
15881                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15882                    if (DEBUG_REMOVE) {
15883                        Slog.d(TAG, "    user " + userId + " => " + installed);
15884                    }
15885                    ps.setInstalled(installed, userId);
15886
15887                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15888                }
15889                // Regardless of writeSettings we need to ensure that this restriction
15890                // state propagation is persisted
15891                mSettings.writeAllUsersPackageRestrictionsLPr();
15892            }
15893            // can downgrade to reader here
15894            if (writeSettings) {
15895                mSettings.writeLPr();
15896            }
15897        }
15898        return true;
15899    }
15900
15901    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15902            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15903            PackageRemovedInfo outInfo, boolean writeSettings,
15904            PackageParser.Package replacingPackage) {
15905        synchronized (mPackages) {
15906            if (outInfo != null) {
15907                outInfo.uid = ps.appId;
15908            }
15909
15910            if (outInfo != null && outInfo.removedChildPackages != null) {
15911                final int childCount = (ps.childPackageNames != null)
15912                        ? ps.childPackageNames.size() : 0;
15913                for (int i = 0; i < childCount; i++) {
15914                    String childPackageName = ps.childPackageNames.get(i);
15915                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15916                    if (childPs == null) {
15917                        return false;
15918                    }
15919                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15920                            childPackageName);
15921                    if (childInfo != null) {
15922                        childInfo.uid = childPs.appId;
15923                    }
15924                }
15925            }
15926        }
15927
15928        // Delete package data from internal structures and also remove data if flag is set
15929        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15930
15931        // Delete the child packages data
15932        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15933        for (int i = 0; i < childCount; i++) {
15934            PackageSetting childPs;
15935            synchronized (mPackages) {
15936                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15937            }
15938            if (childPs != null) {
15939                PackageRemovedInfo childOutInfo = (outInfo != null
15940                        && outInfo.removedChildPackages != null)
15941                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15942                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15943                        && (replacingPackage != null
15944                        && !replacingPackage.hasChildPackage(childPs.name))
15945                        ? flags & ~DELETE_KEEP_DATA : flags;
15946                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15947                        deleteFlags, writeSettings);
15948            }
15949        }
15950
15951        // Delete application code and resources only for parent packages
15952        if (ps.parentPackageName == null) {
15953            if (deleteCodeAndResources && (outInfo != null)) {
15954                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15955                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15956                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15957            }
15958        }
15959
15960        return true;
15961    }
15962
15963    @Override
15964    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15965            int userId) {
15966        mContext.enforceCallingOrSelfPermission(
15967                android.Manifest.permission.DELETE_PACKAGES, null);
15968        synchronized (mPackages) {
15969            PackageSetting ps = mSettings.mPackages.get(packageName);
15970            if (ps == null) {
15971                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15972                return false;
15973            }
15974            if (!ps.getInstalled(userId)) {
15975                // Can't block uninstall for an app that is not installed or enabled.
15976                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15977                return false;
15978            }
15979            ps.setBlockUninstall(blockUninstall, userId);
15980            mSettings.writePackageRestrictionsLPr(userId);
15981        }
15982        return true;
15983    }
15984
15985    @Override
15986    public boolean getBlockUninstallForUser(String packageName, int userId) {
15987        synchronized (mPackages) {
15988            PackageSetting ps = mSettings.mPackages.get(packageName);
15989            if (ps == null) {
15990                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15991                return false;
15992            }
15993            return ps.getBlockUninstall(userId);
15994        }
15995    }
15996
15997    @Override
15998    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15999        int callingUid = Binder.getCallingUid();
16000        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16001            throw new SecurityException(
16002                    "setRequiredForSystemUser can only be run by the system or root");
16003        }
16004        synchronized (mPackages) {
16005            PackageSetting ps = mSettings.mPackages.get(packageName);
16006            if (ps == null) {
16007                Log.w(TAG, "Package doesn't exist: " + packageName);
16008                return false;
16009            }
16010            if (systemUserApp) {
16011                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16012            } else {
16013                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16014            }
16015            mSettings.writeLPr();
16016        }
16017        return true;
16018    }
16019
16020    /*
16021     * This method handles package deletion in general
16022     */
16023    private boolean deletePackageLIF(String packageName, UserHandle user,
16024            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16025            PackageRemovedInfo outInfo, boolean writeSettings,
16026            PackageParser.Package replacingPackage) {
16027        if (packageName == null) {
16028            Slog.w(TAG, "Attempt to delete null packageName.");
16029            return false;
16030        }
16031
16032        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16033
16034        PackageSetting ps;
16035
16036        synchronized (mPackages) {
16037            ps = mSettings.mPackages.get(packageName);
16038            if (ps == null) {
16039                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16040                return false;
16041            }
16042
16043            if (ps.parentPackageName != null && (!isSystemApp(ps)
16044                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16045                if (DEBUG_REMOVE) {
16046                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16047                            + ((user == null) ? UserHandle.USER_ALL : user));
16048                }
16049                final int removedUserId = (user != null) ? user.getIdentifier()
16050                        : UserHandle.USER_ALL;
16051                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16052                    return false;
16053                }
16054                markPackageUninstalledForUserLPw(ps, user);
16055                scheduleWritePackageRestrictionsLocked(user);
16056                return true;
16057            }
16058        }
16059
16060        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16061                && user.getIdentifier() != UserHandle.USER_ALL)) {
16062            // The caller is asking that the package only be deleted for a single
16063            // user.  To do this, we just mark its uninstalled state and delete
16064            // its data. If this is a system app, we only allow this to happen if
16065            // they have set the special DELETE_SYSTEM_APP which requests different
16066            // semantics than normal for uninstalling system apps.
16067            markPackageUninstalledForUserLPw(ps, user);
16068
16069            if (!isSystemApp(ps)) {
16070                // Do not uninstall the APK if an app should be cached
16071                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16072                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16073                    // Other user still have this package installed, so all
16074                    // we need to do is clear this user's data and save that
16075                    // it is uninstalled.
16076                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16077                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16078                        return false;
16079                    }
16080                    scheduleWritePackageRestrictionsLocked(user);
16081                    return true;
16082                } else {
16083                    // We need to set it back to 'installed' so the uninstall
16084                    // broadcasts will be sent correctly.
16085                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16086                    ps.setInstalled(true, user.getIdentifier());
16087                }
16088            } else {
16089                // This is a system app, so we assume that the
16090                // other users still have this package installed, so all
16091                // we need to do is clear this user's data and save that
16092                // it is uninstalled.
16093                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16094                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16095                    return false;
16096                }
16097                scheduleWritePackageRestrictionsLocked(user);
16098                return true;
16099            }
16100        }
16101
16102        // If we are deleting a composite package for all users, keep track
16103        // of result for each child.
16104        if (ps.childPackageNames != null && outInfo != null) {
16105            synchronized (mPackages) {
16106                final int childCount = ps.childPackageNames.size();
16107                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16108                for (int i = 0; i < childCount; i++) {
16109                    String childPackageName = ps.childPackageNames.get(i);
16110                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16111                    childInfo.removedPackage = childPackageName;
16112                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16113                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16114                    if (childPs != null) {
16115                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16116                    }
16117                }
16118            }
16119        }
16120
16121        boolean ret = false;
16122        if (isSystemApp(ps)) {
16123            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16124            // When an updated system application is deleted we delete the existing resources
16125            // as well and fall back to existing code in system partition
16126            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16127        } else {
16128            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16129            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16130                    outInfo, writeSettings, replacingPackage);
16131        }
16132
16133        // Take a note whether we deleted the package for all users
16134        if (outInfo != null) {
16135            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16136            if (outInfo.removedChildPackages != null) {
16137                synchronized (mPackages) {
16138                    final int childCount = outInfo.removedChildPackages.size();
16139                    for (int i = 0; i < childCount; i++) {
16140                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16141                        if (childInfo != null) {
16142                            childInfo.removedForAllUsers = mPackages.get(
16143                                    childInfo.removedPackage) == null;
16144                        }
16145                    }
16146                }
16147            }
16148            // If we uninstalled an update to a system app there may be some
16149            // child packages that appeared as they are declared in the system
16150            // app but were not declared in the update.
16151            if (isSystemApp(ps)) {
16152                synchronized (mPackages) {
16153                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16154                    final int childCount = (updatedPs.childPackageNames != null)
16155                            ? updatedPs.childPackageNames.size() : 0;
16156                    for (int i = 0; i < childCount; i++) {
16157                        String childPackageName = updatedPs.childPackageNames.get(i);
16158                        if (outInfo.removedChildPackages == null
16159                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16160                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16161                            if (childPs == null) {
16162                                continue;
16163                            }
16164                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16165                            installRes.name = childPackageName;
16166                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16167                            installRes.pkg = mPackages.get(childPackageName);
16168                            installRes.uid = childPs.pkg.applicationInfo.uid;
16169                            if (outInfo.appearedChildPackages == null) {
16170                                outInfo.appearedChildPackages = new ArrayMap<>();
16171                            }
16172                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16173                        }
16174                    }
16175                }
16176            }
16177        }
16178
16179        return ret;
16180    }
16181
16182    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16183        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16184                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16185        for (int nextUserId : userIds) {
16186            if (DEBUG_REMOVE) {
16187                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16188            }
16189            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16190                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16191                    false /*hidden*/, false /*suspended*/, null, null, null,
16192                    false /*blockUninstall*/,
16193                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16194        }
16195    }
16196
16197    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16198            PackageRemovedInfo outInfo) {
16199        final PackageParser.Package pkg;
16200        synchronized (mPackages) {
16201            pkg = mPackages.get(ps.name);
16202        }
16203
16204        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16205                : new int[] {userId};
16206        for (int nextUserId : userIds) {
16207            if (DEBUG_REMOVE) {
16208                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16209                        + nextUserId);
16210            }
16211
16212            destroyAppDataLIF(pkg, userId,
16213                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16214            destroyAppProfilesLIF(pkg, userId);
16215            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16216            schedulePackageCleaning(ps.name, nextUserId, false);
16217            synchronized (mPackages) {
16218                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16219                    scheduleWritePackageRestrictionsLocked(nextUserId);
16220                }
16221                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16222            }
16223        }
16224
16225        if (outInfo != null) {
16226            outInfo.removedPackage = ps.name;
16227            outInfo.removedAppId = ps.appId;
16228            outInfo.removedUsers = userIds;
16229        }
16230
16231        return true;
16232    }
16233
16234    private final class ClearStorageConnection implements ServiceConnection {
16235        IMediaContainerService mContainerService;
16236
16237        @Override
16238        public void onServiceConnected(ComponentName name, IBinder service) {
16239            synchronized (this) {
16240                mContainerService = IMediaContainerService.Stub.asInterface(service);
16241                notifyAll();
16242            }
16243        }
16244
16245        @Override
16246        public void onServiceDisconnected(ComponentName name) {
16247        }
16248    }
16249
16250    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16251        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16252
16253        final boolean mounted;
16254        if (Environment.isExternalStorageEmulated()) {
16255            mounted = true;
16256        } else {
16257            final String status = Environment.getExternalStorageState();
16258
16259            mounted = status.equals(Environment.MEDIA_MOUNTED)
16260                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16261        }
16262
16263        if (!mounted) {
16264            return;
16265        }
16266
16267        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16268        int[] users;
16269        if (userId == UserHandle.USER_ALL) {
16270            users = sUserManager.getUserIds();
16271        } else {
16272            users = new int[] { userId };
16273        }
16274        final ClearStorageConnection conn = new ClearStorageConnection();
16275        if (mContext.bindServiceAsUser(
16276                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16277            try {
16278                for (int curUser : users) {
16279                    long timeout = SystemClock.uptimeMillis() + 5000;
16280                    synchronized (conn) {
16281                        long now;
16282                        while (conn.mContainerService == null &&
16283                                (now = SystemClock.uptimeMillis()) < timeout) {
16284                            try {
16285                                conn.wait(timeout - now);
16286                            } catch (InterruptedException e) {
16287                            }
16288                        }
16289                    }
16290                    if (conn.mContainerService == null) {
16291                        return;
16292                    }
16293
16294                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16295                    clearDirectory(conn.mContainerService,
16296                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16297                    if (allData) {
16298                        clearDirectory(conn.mContainerService,
16299                                userEnv.buildExternalStorageAppDataDirs(packageName));
16300                        clearDirectory(conn.mContainerService,
16301                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16302                    }
16303                }
16304            } finally {
16305                mContext.unbindService(conn);
16306            }
16307        }
16308    }
16309
16310    @Override
16311    public void clearApplicationProfileData(String packageName) {
16312        enforceSystemOrRoot("Only the system can clear all profile data");
16313
16314        final PackageParser.Package pkg;
16315        synchronized (mPackages) {
16316            pkg = mPackages.get(packageName);
16317        }
16318
16319        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16320            synchronized (mInstallLock) {
16321                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16322                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16323                        true /* removeBaseMarker */);
16324            }
16325        }
16326    }
16327
16328    @Override
16329    public void clearApplicationUserData(final String packageName,
16330            final IPackageDataObserver observer, final int userId) {
16331        mContext.enforceCallingOrSelfPermission(
16332                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16333
16334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16335                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16336
16337        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16338            throw new SecurityException("Cannot clear data for a protected package: "
16339                    + packageName);
16340        }
16341        // Queue up an async operation since the package deletion may take a little while.
16342        mHandler.post(new Runnable() {
16343            public void run() {
16344                mHandler.removeCallbacks(this);
16345                final boolean succeeded;
16346                try (PackageFreezer freezer = freezePackage(packageName,
16347                        "clearApplicationUserData")) {
16348                    synchronized (mInstallLock) {
16349                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16350                    }
16351                    clearExternalStorageDataSync(packageName, userId, true);
16352                }
16353                if (succeeded) {
16354                    // invoke DeviceStorageMonitor's update method to clear any notifications
16355                    DeviceStorageMonitorInternal dsm = LocalServices
16356                            .getService(DeviceStorageMonitorInternal.class);
16357                    if (dsm != null) {
16358                        dsm.checkMemory();
16359                    }
16360                }
16361                if(observer != null) {
16362                    try {
16363                        observer.onRemoveCompleted(packageName, succeeded);
16364                    } catch (RemoteException e) {
16365                        Log.i(TAG, "Observer no longer exists.");
16366                    }
16367                } //end if observer
16368            } //end run
16369        });
16370    }
16371
16372    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16373        if (packageName == null) {
16374            Slog.w(TAG, "Attempt to delete null packageName.");
16375            return false;
16376        }
16377
16378        // Try finding details about the requested package
16379        PackageParser.Package pkg;
16380        synchronized (mPackages) {
16381            pkg = mPackages.get(packageName);
16382            if (pkg == null) {
16383                final PackageSetting ps = mSettings.mPackages.get(packageName);
16384                if (ps != null) {
16385                    pkg = ps.pkg;
16386                }
16387            }
16388
16389            if (pkg == null) {
16390                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16391                return false;
16392            }
16393
16394            PackageSetting ps = (PackageSetting) pkg.mExtras;
16395            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16396        }
16397
16398        clearAppDataLIF(pkg, userId,
16399                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16400
16401        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16402        removeKeystoreDataIfNeeded(userId, appId);
16403
16404        UserManagerInternal umInternal = getUserManagerInternal();
16405        final int flags;
16406        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16407            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16408        } else if (umInternal.isUserRunning(userId)) {
16409            flags = StorageManager.FLAG_STORAGE_DE;
16410        } else {
16411            flags = 0;
16412        }
16413        prepareAppDataContentsLIF(pkg, userId, flags);
16414
16415        return true;
16416    }
16417
16418    /**
16419     * Reverts user permission state changes (permissions and flags) in
16420     * all packages for a given user.
16421     *
16422     * @param userId The device user for which to do a reset.
16423     */
16424    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16425        final int packageCount = mPackages.size();
16426        for (int i = 0; i < packageCount; i++) {
16427            PackageParser.Package pkg = mPackages.valueAt(i);
16428            PackageSetting ps = (PackageSetting) pkg.mExtras;
16429            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16430        }
16431    }
16432
16433    private void resetNetworkPolicies(int userId) {
16434        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16435    }
16436
16437    /**
16438     * Reverts user permission state changes (permissions and flags).
16439     *
16440     * @param ps The package for which to reset.
16441     * @param userId The device user for which to do a reset.
16442     */
16443    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16444            final PackageSetting ps, final int userId) {
16445        if (ps.pkg == null) {
16446            return;
16447        }
16448
16449        // These are flags that can change base on user actions.
16450        final int userSettableMask = FLAG_PERMISSION_USER_SET
16451                | FLAG_PERMISSION_USER_FIXED
16452                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16453                | FLAG_PERMISSION_REVIEW_REQUIRED;
16454
16455        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16456                | FLAG_PERMISSION_POLICY_FIXED;
16457
16458        boolean writeInstallPermissions = false;
16459        boolean writeRuntimePermissions = false;
16460
16461        final int permissionCount = ps.pkg.requestedPermissions.size();
16462        for (int i = 0; i < permissionCount; i++) {
16463            String permission = ps.pkg.requestedPermissions.get(i);
16464
16465            BasePermission bp = mSettings.mPermissions.get(permission);
16466            if (bp == null) {
16467                continue;
16468            }
16469
16470            // If shared user we just reset the state to which only this app contributed.
16471            if (ps.sharedUser != null) {
16472                boolean used = false;
16473                final int packageCount = ps.sharedUser.packages.size();
16474                for (int j = 0; j < packageCount; j++) {
16475                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16476                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16477                            && pkg.pkg.requestedPermissions.contains(permission)) {
16478                        used = true;
16479                        break;
16480                    }
16481                }
16482                if (used) {
16483                    continue;
16484                }
16485            }
16486
16487            PermissionsState permissionsState = ps.getPermissionsState();
16488
16489            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16490
16491            // Always clear the user settable flags.
16492            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16493                    bp.name) != null;
16494            // If permission review is enabled and this is a legacy app, mark the
16495            // permission as requiring a review as this is the initial state.
16496            int flags = 0;
16497            if (Build.PERMISSIONS_REVIEW_REQUIRED
16498                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16499                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16500            }
16501            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16502                if (hasInstallState) {
16503                    writeInstallPermissions = true;
16504                } else {
16505                    writeRuntimePermissions = true;
16506                }
16507            }
16508
16509            // Below is only runtime permission handling.
16510            if (!bp.isRuntime()) {
16511                continue;
16512            }
16513
16514            // Never clobber system or policy.
16515            if ((oldFlags & policyOrSystemFlags) != 0) {
16516                continue;
16517            }
16518
16519            // If this permission was granted by default, make sure it is.
16520            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16521                if (permissionsState.grantRuntimePermission(bp, userId)
16522                        != PERMISSION_OPERATION_FAILURE) {
16523                    writeRuntimePermissions = true;
16524                }
16525            // If permission review is enabled the permissions for a legacy apps
16526            // are represented as constantly granted runtime ones, so don't revoke.
16527            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16528                // Otherwise, reset the permission.
16529                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16530                switch (revokeResult) {
16531                    case PERMISSION_OPERATION_SUCCESS:
16532                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16533                        writeRuntimePermissions = true;
16534                        final int appId = ps.appId;
16535                        mHandler.post(new Runnable() {
16536                            @Override
16537                            public void run() {
16538                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16539                            }
16540                        });
16541                    } break;
16542                }
16543            }
16544        }
16545
16546        // Synchronously write as we are taking permissions away.
16547        if (writeRuntimePermissions) {
16548            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16549        }
16550
16551        // Synchronously write as we are taking permissions away.
16552        if (writeInstallPermissions) {
16553            mSettings.writeLPr();
16554        }
16555    }
16556
16557    /**
16558     * Remove entries from the keystore daemon. Will only remove it if the
16559     * {@code appId} is valid.
16560     */
16561    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16562        if (appId < 0) {
16563            return;
16564        }
16565
16566        final KeyStore keyStore = KeyStore.getInstance();
16567        if (keyStore != null) {
16568            if (userId == UserHandle.USER_ALL) {
16569                for (final int individual : sUserManager.getUserIds()) {
16570                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16571                }
16572            } else {
16573                keyStore.clearUid(UserHandle.getUid(userId, appId));
16574            }
16575        } else {
16576            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16577        }
16578    }
16579
16580    @Override
16581    public void deleteApplicationCacheFiles(final String packageName,
16582            final IPackageDataObserver observer) {
16583        final int userId = UserHandle.getCallingUserId();
16584        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16585    }
16586
16587    @Override
16588    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16589            final IPackageDataObserver observer) {
16590        mContext.enforceCallingOrSelfPermission(
16591                android.Manifest.permission.DELETE_CACHE_FILES, null);
16592        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16593                /* requireFullPermission= */ true, /* checkShell= */ false,
16594                "delete application cache files");
16595
16596        final PackageParser.Package pkg;
16597        synchronized (mPackages) {
16598            pkg = mPackages.get(packageName);
16599        }
16600
16601        // Queue up an async operation since the package deletion may take a little while.
16602        mHandler.post(new Runnable() {
16603            public void run() {
16604                synchronized (mInstallLock) {
16605                    final int flags = StorageManager.FLAG_STORAGE_DE
16606                            | StorageManager.FLAG_STORAGE_CE;
16607                    // We're only clearing cache files, so we don't care if the
16608                    // app is unfrozen and still able to run
16609                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16610                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16611                }
16612                clearExternalStorageDataSync(packageName, userId, false);
16613                if (observer != null) {
16614                    try {
16615                        observer.onRemoveCompleted(packageName, true);
16616                    } catch (RemoteException e) {
16617                        Log.i(TAG, "Observer no longer exists.");
16618                    }
16619                }
16620            }
16621        });
16622    }
16623
16624    @Override
16625    public void getPackageSizeInfo(final String packageName, int userHandle,
16626            final IPackageStatsObserver observer) {
16627        mContext.enforceCallingOrSelfPermission(
16628                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16629        if (packageName == null) {
16630            throw new IllegalArgumentException("Attempt to get size of null packageName");
16631        }
16632
16633        PackageStats stats = new PackageStats(packageName, userHandle);
16634
16635        /*
16636         * Queue up an async operation since the package measurement may take a
16637         * little while.
16638         */
16639        Message msg = mHandler.obtainMessage(INIT_COPY);
16640        msg.obj = new MeasureParams(stats, observer);
16641        mHandler.sendMessage(msg);
16642    }
16643
16644    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16645        final PackageSetting ps;
16646        synchronized (mPackages) {
16647            ps = mSettings.mPackages.get(packageName);
16648            if (ps == null) {
16649                Slog.w(TAG, "Failed to find settings for " + packageName);
16650                return false;
16651            }
16652        }
16653        try {
16654            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16655                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16656                    ps.getCeDataInode(userId), ps.codePathString, stats);
16657        } catch (InstallerException e) {
16658            Slog.w(TAG, String.valueOf(e));
16659            return false;
16660        }
16661
16662        // For now, ignore code size of packages on system partition
16663        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16664            stats.codeSize = 0;
16665        }
16666
16667        return true;
16668    }
16669
16670    private int getUidTargetSdkVersionLockedLPr(int uid) {
16671        Object obj = mSettings.getUserIdLPr(uid);
16672        if (obj instanceof SharedUserSetting) {
16673            final SharedUserSetting sus = (SharedUserSetting) obj;
16674            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16675            final Iterator<PackageSetting> it = sus.packages.iterator();
16676            while (it.hasNext()) {
16677                final PackageSetting ps = it.next();
16678                if (ps.pkg != null) {
16679                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16680                    if (v < vers) vers = v;
16681                }
16682            }
16683            return vers;
16684        } else if (obj instanceof PackageSetting) {
16685            final PackageSetting ps = (PackageSetting) obj;
16686            if (ps.pkg != null) {
16687                return ps.pkg.applicationInfo.targetSdkVersion;
16688            }
16689        }
16690        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16691    }
16692
16693    @Override
16694    public void addPreferredActivity(IntentFilter filter, int match,
16695            ComponentName[] set, ComponentName activity, int userId) {
16696        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16697                "Adding preferred");
16698    }
16699
16700    private void addPreferredActivityInternal(IntentFilter filter, int match,
16701            ComponentName[] set, ComponentName activity, boolean always, int userId,
16702            String opname) {
16703        // writer
16704        int callingUid = Binder.getCallingUid();
16705        enforceCrossUserPermission(callingUid, userId,
16706                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16707        if (filter.countActions() == 0) {
16708            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16709            return;
16710        }
16711        synchronized (mPackages) {
16712            if (mContext.checkCallingOrSelfPermission(
16713                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16714                    != PackageManager.PERMISSION_GRANTED) {
16715                if (getUidTargetSdkVersionLockedLPr(callingUid)
16716                        < Build.VERSION_CODES.FROYO) {
16717                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16718                            + callingUid);
16719                    return;
16720                }
16721                mContext.enforceCallingOrSelfPermission(
16722                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16723            }
16724
16725            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16726            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16727                    + userId + ":");
16728            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16729            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16730            scheduleWritePackageRestrictionsLocked(userId);
16731            postPreferredActivityChangedBroadcast(userId);
16732        }
16733    }
16734
16735    private void postPreferredActivityChangedBroadcast(int userId) {
16736        mHandler.post(() -> {
16737            final IActivityManager am = ActivityManagerNative.getDefault();
16738            if (am == null) {
16739                return;
16740            }
16741
16742            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16743            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16744            try {
16745                am.broadcastIntent(null, intent, null, null,
16746                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16747                        null, false, false, userId);
16748            } catch (RemoteException e) {
16749            }
16750        });
16751    }
16752
16753    @Override
16754    public void replacePreferredActivity(IntentFilter filter, int match,
16755            ComponentName[] set, ComponentName activity, int userId) {
16756        if (filter.countActions() != 1) {
16757            throw new IllegalArgumentException(
16758                    "replacePreferredActivity expects filter to have only 1 action.");
16759        }
16760        if (filter.countDataAuthorities() != 0
16761                || filter.countDataPaths() != 0
16762                || filter.countDataSchemes() > 1
16763                || filter.countDataTypes() != 0) {
16764            throw new IllegalArgumentException(
16765                    "replacePreferredActivity expects filter to have no data authorities, " +
16766                    "paths, or types; and at most one scheme.");
16767        }
16768
16769        final int callingUid = Binder.getCallingUid();
16770        enforceCrossUserPermission(callingUid, userId,
16771                true /* requireFullPermission */, false /* checkShell */,
16772                "replace preferred activity");
16773        synchronized (mPackages) {
16774            if (mContext.checkCallingOrSelfPermission(
16775                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16776                    != PackageManager.PERMISSION_GRANTED) {
16777                if (getUidTargetSdkVersionLockedLPr(callingUid)
16778                        < Build.VERSION_CODES.FROYO) {
16779                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16780                            + Binder.getCallingUid());
16781                    return;
16782                }
16783                mContext.enforceCallingOrSelfPermission(
16784                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16785            }
16786
16787            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16788            if (pir != null) {
16789                // Get all of the existing entries that exactly match this filter.
16790                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16791                if (existing != null && existing.size() == 1) {
16792                    PreferredActivity cur = existing.get(0);
16793                    if (DEBUG_PREFERRED) {
16794                        Slog.i(TAG, "Checking replace of preferred:");
16795                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16796                        if (!cur.mPref.mAlways) {
16797                            Slog.i(TAG, "  -- CUR; not mAlways!");
16798                        } else {
16799                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16800                            Slog.i(TAG, "  -- CUR: mSet="
16801                                    + Arrays.toString(cur.mPref.mSetComponents));
16802                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16803                            Slog.i(TAG, "  -- NEW: mMatch="
16804                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16805                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16806                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16807                        }
16808                    }
16809                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16810                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16811                            && cur.mPref.sameSet(set)) {
16812                        // Setting the preferred activity to what it happens to be already
16813                        if (DEBUG_PREFERRED) {
16814                            Slog.i(TAG, "Replacing with same preferred activity "
16815                                    + cur.mPref.mShortComponent + " for user "
16816                                    + userId + ":");
16817                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16818                        }
16819                        return;
16820                    }
16821                }
16822
16823                if (existing != null) {
16824                    if (DEBUG_PREFERRED) {
16825                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16826                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16827                    }
16828                    for (int i = 0; i < existing.size(); i++) {
16829                        PreferredActivity pa = existing.get(i);
16830                        if (DEBUG_PREFERRED) {
16831                            Slog.i(TAG, "Removing existing preferred activity "
16832                                    + pa.mPref.mComponent + ":");
16833                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16834                        }
16835                        pir.removeFilter(pa);
16836                    }
16837                }
16838            }
16839            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16840                    "Replacing preferred");
16841        }
16842    }
16843
16844    @Override
16845    public void clearPackagePreferredActivities(String packageName) {
16846        final int uid = Binder.getCallingUid();
16847        // writer
16848        synchronized (mPackages) {
16849            PackageParser.Package pkg = mPackages.get(packageName);
16850            if (pkg == null || pkg.applicationInfo.uid != uid) {
16851                if (mContext.checkCallingOrSelfPermission(
16852                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16853                        != PackageManager.PERMISSION_GRANTED) {
16854                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16855                            < Build.VERSION_CODES.FROYO) {
16856                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16857                                + Binder.getCallingUid());
16858                        return;
16859                    }
16860                    mContext.enforceCallingOrSelfPermission(
16861                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16862                }
16863            }
16864
16865            int user = UserHandle.getCallingUserId();
16866            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16867                scheduleWritePackageRestrictionsLocked(user);
16868            }
16869        }
16870    }
16871
16872    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16873    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16874        ArrayList<PreferredActivity> removed = null;
16875        boolean changed = false;
16876        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16877            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16878            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16879            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16880                continue;
16881            }
16882            Iterator<PreferredActivity> it = pir.filterIterator();
16883            while (it.hasNext()) {
16884                PreferredActivity pa = it.next();
16885                // Mark entry for removal only if it matches the package name
16886                // and the entry is of type "always".
16887                if (packageName == null ||
16888                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16889                                && pa.mPref.mAlways)) {
16890                    if (removed == null) {
16891                        removed = new ArrayList<PreferredActivity>();
16892                    }
16893                    removed.add(pa);
16894                }
16895            }
16896            if (removed != null) {
16897                for (int j=0; j<removed.size(); j++) {
16898                    PreferredActivity pa = removed.get(j);
16899                    pir.removeFilter(pa);
16900                }
16901                changed = true;
16902            }
16903        }
16904        if (changed) {
16905            postPreferredActivityChangedBroadcast(userId);
16906        }
16907        return changed;
16908    }
16909
16910    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16911    private void clearIntentFilterVerificationsLPw(int userId) {
16912        final int packageCount = mPackages.size();
16913        for (int i = 0; i < packageCount; i++) {
16914            PackageParser.Package pkg = mPackages.valueAt(i);
16915            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16916        }
16917    }
16918
16919    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16920    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16921        if (userId == UserHandle.USER_ALL) {
16922            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16923                    sUserManager.getUserIds())) {
16924                for (int oneUserId : sUserManager.getUserIds()) {
16925                    scheduleWritePackageRestrictionsLocked(oneUserId);
16926                }
16927            }
16928        } else {
16929            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16930                scheduleWritePackageRestrictionsLocked(userId);
16931            }
16932        }
16933    }
16934
16935    void clearDefaultBrowserIfNeeded(String packageName) {
16936        for (int oneUserId : sUserManager.getUserIds()) {
16937            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16938            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16939            if (packageName.equals(defaultBrowserPackageName)) {
16940                setDefaultBrowserPackageName(null, oneUserId);
16941            }
16942        }
16943    }
16944
16945    @Override
16946    public void resetApplicationPreferences(int userId) {
16947        mContext.enforceCallingOrSelfPermission(
16948                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16949        final long identity = Binder.clearCallingIdentity();
16950        // writer
16951        try {
16952            synchronized (mPackages) {
16953                clearPackagePreferredActivitiesLPw(null, userId);
16954                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16955                // TODO: We have to reset the default SMS and Phone. This requires
16956                // significant refactoring to keep all default apps in the package
16957                // manager (cleaner but more work) or have the services provide
16958                // callbacks to the package manager to request a default app reset.
16959                applyFactoryDefaultBrowserLPw(userId);
16960                clearIntentFilterVerificationsLPw(userId);
16961                primeDomainVerificationsLPw(userId);
16962                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16963                scheduleWritePackageRestrictionsLocked(userId);
16964            }
16965            resetNetworkPolicies(userId);
16966        } finally {
16967            Binder.restoreCallingIdentity(identity);
16968        }
16969    }
16970
16971    @Override
16972    public int getPreferredActivities(List<IntentFilter> outFilters,
16973            List<ComponentName> outActivities, String packageName) {
16974
16975        int num = 0;
16976        final int userId = UserHandle.getCallingUserId();
16977        // reader
16978        synchronized (mPackages) {
16979            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16980            if (pir != null) {
16981                final Iterator<PreferredActivity> it = pir.filterIterator();
16982                while (it.hasNext()) {
16983                    final PreferredActivity pa = it.next();
16984                    if (packageName == null
16985                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16986                                    && pa.mPref.mAlways)) {
16987                        if (outFilters != null) {
16988                            outFilters.add(new IntentFilter(pa));
16989                        }
16990                        if (outActivities != null) {
16991                            outActivities.add(pa.mPref.mComponent);
16992                        }
16993                    }
16994                }
16995            }
16996        }
16997
16998        return num;
16999    }
17000
17001    @Override
17002    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17003            int userId) {
17004        int callingUid = Binder.getCallingUid();
17005        if (callingUid != Process.SYSTEM_UID) {
17006            throw new SecurityException(
17007                    "addPersistentPreferredActivity can only be run by the system");
17008        }
17009        if (filter.countActions() == 0) {
17010            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17011            return;
17012        }
17013        synchronized (mPackages) {
17014            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17015                    ":");
17016            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17017            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17018                    new PersistentPreferredActivity(filter, activity));
17019            scheduleWritePackageRestrictionsLocked(userId);
17020            postPreferredActivityChangedBroadcast(userId);
17021        }
17022    }
17023
17024    @Override
17025    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17026        int callingUid = Binder.getCallingUid();
17027        if (callingUid != Process.SYSTEM_UID) {
17028            throw new SecurityException(
17029                    "clearPackagePersistentPreferredActivities can only be run by the system");
17030        }
17031        ArrayList<PersistentPreferredActivity> removed = null;
17032        boolean changed = false;
17033        synchronized (mPackages) {
17034            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17035                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17036                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17037                        .valueAt(i);
17038                if (userId != thisUserId) {
17039                    continue;
17040                }
17041                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17042                while (it.hasNext()) {
17043                    PersistentPreferredActivity ppa = it.next();
17044                    // Mark entry for removal only if it matches the package name.
17045                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17046                        if (removed == null) {
17047                            removed = new ArrayList<PersistentPreferredActivity>();
17048                        }
17049                        removed.add(ppa);
17050                    }
17051                }
17052                if (removed != null) {
17053                    for (int j=0; j<removed.size(); j++) {
17054                        PersistentPreferredActivity ppa = removed.get(j);
17055                        ppir.removeFilter(ppa);
17056                    }
17057                    changed = true;
17058                }
17059            }
17060
17061            if (changed) {
17062                scheduleWritePackageRestrictionsLocked(userId);
17063                postPreferredActivityChangedBroadcast(userId);
17064            }
17065        }
17066    }
17067
17068    /**
17069     * Common machinery for picking apart a restored XML blob and passing
17070     * it to a caller-supplied functor to be applied to the running system.
17071     */
17072    private void restoreFromXml(XmlPullParser parser, int userId,
17073            String expectedStartTag, BlobXmlRestorer functor)
17074            throws IOException, XmlPullParserException {
17075        int type;
17076        while ((type = parser.next()) != XmlPullParser.START_TAG
17077                && type != XmlPullParser.END_DOCUMENT) {
17078        }
17079        if (type != XmlPullParser.START_TAG) {
17080            // oops didn't find a start tag?!
17081            if (DEBUG_BACKUP) {
17082                Slog.e(TAG, "Didn't find start tag during restore");
17083            }
17084            return;
17085        }
17086Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17087        // this is supposed to be TAG_PREFERRED_BACKUP
17088        if (!expectedStartTag.equals(parser.getName())) {
17089            if (DEBUG_BACKUP) {
17090                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17091            }
17092            return;
17093        }
17094
17095        // skip interfering stuff, then we're aligned with the backing implementation
17096        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17097Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17098        functor.apply(parser, userId);
17099    }
17100
17101    private interface BlobXmlRestorer {
17102        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17103    }
17104
17105    /**
17106     * Non-Binder method, support for the backup/restore mechanism: write the
17107     * full set of preferred activities in its canonical XML format.  Returns the
17108     * XML output as a byte array, or null if there is none.
17109     */
17110    @Override
17111    public byte[] getPreferredActivityBackup(int userId) {
17112        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17113            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17114        }
17115
17116        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17117        try {
17118            final XmlSerializer serializer = new FastXmlSerializer();
17119            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17120            serializer.startDocument(null, true);
17121            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17122
17123            synchronized (mPackages) {
17124                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17125            }
17126
17127            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17128            serializer.endDocument();
17129            serializer.flush();
17130        } catch (Exception e) {
17131            if (DEBUG_BACKUP) {
17132                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17133            }
17134            return null;
17135        }
17136
17137        return dataStream.toByteArray();
17138    }
17139
17140    @Override
17141    public void restorePreferredActivities(byte[] backup, int userId) {
17142        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17143            throw new SecurityException("Only the system may call restorePreferredActivities()");
17144        }
17145
17146        try {
17147            final XmlPullParser parser = Xml.newPullParser();
17148            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17149            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17150                    new BlobXmlRestorer() {
17151                        @Override
17152                        public void apply(XmlPullParser parser, int userId)
17153                                throws XmlPullParserException, IOException {
17154                            synchronized (mPackages) {
17155                                mSettings.readPreferredActivitiesLPw(parser, userId);
17156                            }
17157                        }
17158                    } );
17159        } catch (Exception e) {
17160            if (DEBUG_BACKUP) {
17161                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17162            }
17163        }
17164    }
17165
17166    /**
17167     * Non-Binder method, support for the backup/restore mechanism: write the
17168     * default browser (etc) settings in its canonical XML format.  Returns the default
17169     * browser XML representation as a byte array, or null if there is none.
17170     */
17171    @Override
17172    public byte[] getDefaultAppsBackup(int userId) {
17173        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17174            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17175        }
17176
17177        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17178        try {
17179            final XmlSerializer serializer = new FastXmlSerializer();
17180            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17181            serializer.startDocument(null, true);
17182            serializer.startTag(null, TAG_DEFAULT_APPS);
17183
17184            synchronized (mPackages) {
17185                mSettings.writeDefaultAppsLPr(serializer, userId);
17186            }
17187
17188            serializer.endTag(null, TAG_DEFAULT_APPS);
17189            serializer.endDocument();
17190            serializer.flush();
17191        } catch (Exception e) {
17192            if (DEBUG_BACKUP) {
17193                Slog.e(TAG, "Unable to write default apps for backup", e);
17194            }
17195            return null;
17196        }
17197
17198        return dataStream.toByteArray();
17199    }
17200
17201    @Override
17202    public void restoreDefaultApps(byte[] backup, int userId) {
17203        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17204            throw new SecurityException("Only the system may call restoreDefaultApps()");
17205        }
17206
17207        try {
17208            final XmlPullParser parser = Xml.newPullParser();
17209            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17210            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17211                    new BlobXmlRestorer() {
17212                        @Override
17213                        public void apply(XmlPullParser parser, int userId)
17214                                throws XmlPullParserException, IOException {
17215                            synchronized (mPackages) {
17216                                mSettings.readDefaultAppsLPw(parser, userId);
17217                            }
17218                        }
17219                    } );
17220        } catch (Exception e) {
17221            if (DEBUG_BACKUP) {
17222                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17223            }
17224        }
17225    }
17226
17227    @Override
17228    public byte[] getIntentFilterVerificationBackup(int userId) {
17229        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17230            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17231        }
17232
17233        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17234        try {
17235            final XmlSerializer serializer = new FastXmlSerializer();
17236            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17237            serializer.startDocument(null, true);
17238            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17239
17240            synchronized (mPackages) {
17241                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17242            }
17243
17244            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17245            serializer.endDocument();
17246            serializer.flush();
17247        } catch (Exception e) {
17248            if (DEBUG_BACKUP) {
17249                Slog.e(TAG, "Unable to write default apps for backup", e);
17250            }
17251            return null;
17252        }
17253
17254        return dataStream.toByteArray();
17255    }
17256
17257    @Override
17258    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17259        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17260            throw new SecurityException("Only the system may call restorePreferredActivities()");
17261        }
17262
17263        try {
17264            final XmlPullParser parser = Xml.newPullParser();
17265            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17266            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17267                    new BlobXmlRestorer() {
17268                        @Override
17269                        public void apply(XmlPullParser parser, int userId)
17270                                throws XmlPullParserException, IOException {
17271                            synchronized (mPackages) {
17272                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17273                                mSettings.writeLPr();
17274                            }
17275                        }
17276                    } );
17277        } catch (Exception e) {
17278            if (DEBUG_BACKUP) {
17279                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17280            }
17281        }
17282    }
17283
17284    @Override
17285    public byte[] getPermissionGrantBackup(int userId) {
17286        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17287            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17288        }
17289
17290        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17291        try {
17292            final XmlSerializer serializer = new FastXmlSerializer();
17293            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17294            serializer.startDocument(null, true);
17295            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17296
17297            synchronized (mPackages) {
17298                serializeRuntimePermissionGrantsLPr(serializer, userId);
17299            }
17300
17301            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17302            serializer.endDocument();
17303            serializer.flush();
17304        } catch (Exception e) {
17305            if (DEBUG_BACKUP) {
17306                Slog.e(TAG, "Unable to write default apps for backup", e);
17307            }
17308            return null;
17309        }
17310
17311        return dataStream.toByteArray();
17312    }
17313
17314    @Override
17315    public void restorePermissionGrants(byte[] backup, int userId) {
17316        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17317            throw new SecurityException("Only the system may call restorePermissionGrants()");
17318        }
17319
17320        try {
17321            final XmlPullParser parser = Xml.newPullParser();
17322            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17323            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17324                    new BlobXmlRestorer() {
17325                        @Override
17326                        public void apply(XmlPullParser parser, int userId)
17327                                throws XmlPullParserException, IOException {
17328                            synchronized (mPackages) {
17329                                processRestoredPermissionGrantsLPr(parser, userId);
17330                            }
17331                        }
17332                    } );
17333        } catch (Exception e) {
17334            if (DEBUG_BACKUP) {
17335                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17336            }
17337        }
17338    }
17339
17340    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17341            throws IOException {
17342        serializer.startTag(null, TAG_ALL_GRANTS);
17343
17344        final int N = mSettings.mPackages.size();
17345        for (int i = 0; i < N; i++) {
17346            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17347            boolean pkgGrantsKnown = false;
17348
17349            PermissionsState packagePerms = ps.getPermissionsState();
17350
17351            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17352                final int grantFlags = state.getFlags();
17353                // only look at grants that are not system/policy fixed
17354                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17355                    final boolean isGranted = state.isGranted();
17356                    // And only back up the user-twiddled state bits
17357                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17358                        final String packageName = mSettings.mPackages.keyAt(i);
17359                        if (!pkgGrantsKnown) {
17360                            serializer.startTag(null, TAG_GRANT);
17361                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17362                            pkgGrantsKnown = true;
17363                        }
17364
17365                        final boolean userSet =
17366                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17367                        final boolean userFixed =
17368                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17369                        final boolean revoke =
17370                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17371
17372                        serializer.startTag(null, TAG_PERMISSION);
17373                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17374                        if (isGranted) {
17375                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17376                        }
17377                        if (userSet) {
17378                            serializer.attribute(null, ATTR_USER_SET, "true");
17379                        }
17380                        if (userFixed) {
17381                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17382                        }
17383                        if (revoke) {
17384                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17385                        }
17386                        serializer.endTag(null, TAG_PERMISSION);
17387                    }
17388                }
17389            }
17390
17391            if (pkgGrantsKnown) {
17392                serializer.endTag(null, TAG_GRANT);
17393            }
17394        }
17395
17396        serializer.endTag(null, TAG_ALL_GRANTS);
17397    }
17398
17399    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17400            throws XmlPullParserException, IOException {
17401        String pkgName = null;
17402        int outerDepth = parser.getDepth();
17403        int type;
17404        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17405                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17406            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17407                continue;
17408            }
17409
17410            final String tagName = parser.getName();
17411            if (tagName.equals(TAG_GRANT)) {
17412                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17413                if (DEBUG_BACKUP) {
17414                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17415                }
17416            } else if (tagName.equals(TAG_PERMISSION)) {
17417
17418                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17419                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17420
17421                int newFlagSet = 0;
17422                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17423                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17424                }
17425                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17426                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17427                }
17428                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17429                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17430                }
17431                if (DEBUG_BACKUP) {
17432                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17433                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17434                }
17435                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17436                if (ps != null) {
17437                    // Already installed so we apply the grant immediately
17438                    if (DEBUG_BACKUP) {
17439                        Slog.v(TAG, "        + already installed; applying");
17440                    }
17441                    PermissionsState perms = ps.getPermissionsState();
17442                    BasePermission bp = mSettings.mPermissions.get(permName);
17443                    if (bp != null) {
17444                        if (isGranted) {
17445                            perms.grantRuntimePermission(bp, userId);
17446                        }
17447                        if (newFlagSet != 0) {
17448                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17449                        }
17450                    }
17451                } else {
17452                    // Need to wait for post-restore install to apply the grant
17453                    if (DEBUG_BACKUP) {
17454                        Slog.v(TAG, "        - not yet installed; saving for later");
17455                    }
17456                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17457                            isGranted, newFlagSet, userId);
17458                }
17459            } else {
17460                PackageManagerService.reportSettingsProblem(Log.WARN,
17461                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17462                XmlUtils.skipCurrentTag(parser);
17463            }
17464        }
17465
17466        scheduleWriteSettingsLocked();
17467        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17468    }
17469
17470    @Override
17471    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17472            int sourceUserId, int targetUserId, int flags) {
17473        mContext.enforceCallingOrSelfPermission(
17474                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17475        int callingUid = Binder.getCallingUid();
17476        enforceOwnerRights(ownerPackage, callingUid);
17477        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17478        if (intentFilter.countActions() == 0) {
17479            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17480            return;
17481        }
17482        synchronized (mPackages) {
17483            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17484                    ownerPackage, targetUserId, flags);
17485            CrossProfileIntentResolver resolver =
17486                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17487            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17488            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17489            if (existing != null) {
17490                int size = existing.size();
17491                for (int i = 0; i < size; i++) {
17492                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17493                        return;
17494                    }
17495                }
17496            }
17497            resolver.addFilter(newFilter);
17498            scheduleWritePackageRestrictionsLocked(sourceUserId);
17499        }
17500    }
17501
17502    @Override
17503    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17504        mContext.enforceCallingOrSelfPermission(
17505                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17506        int callingUid = Binder.getCallingUid();
17507        enforceOwnerRights(ownerPackage, callingUid);
17508        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17509        synchronized (mPackages) {
17510            CrossProfileIntentResolver resolver =
17511                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17512            ArraySet<CrossProfileIntentFilter> set =
17513                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17514            for (CrossProfileIntentFilter filter : set) {
17515                if (filter.getOwnerPackage().equals(ownerPackage)) {
17516                    resolver.removeFilter(filter);
17517                }
17518            }
17519            scheduleWritePackageRestrictionsLocked(sourceUserId);
17520        }
17521    }
17522
17523    // Enforcing that callingUid is owning pkg on userId
17524    private void enforceOwnerRights(String pkg, int callingUid) {
17525        // The system owns everything.
17526        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17527            return;
17528        }
17529        int callingUserId = UserHandle.getUserId(callingUid);
17530        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17531        if (pi == null) {
17532            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17533                    + callingUserId);
17534        }
17535        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17536            throw new SecurityException("Calling uid " + callingUid
17537                    + " does not own package " + pkg);
17538        }
17539    }
17540
17541    @Override
17542    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17543        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17544    }
17545
17546    private Intent getHomeIntent() {
17547        Intent intent = new Intent(Intent.ACTION_MAIN);
17548        intent.addCategory(Intent.CATEGORY_HOME);
17549        intent.addCategory(Intent.CATEGORY_DEFAULT);
17550        return intent;
17551    }
17552
17553    private IntentFilter getHomeFilter() {
17554        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17555        filter.addCategory(Intent.CATEGORY_HOME);
17556        filter.addCategory(Intent.CATEGORY_DEFAULT);
17557        return filter;
17558    }
17559
17560    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17561            int userId) {
17562        Intent intent  = getHomeIntent();
17563        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17564                PackageManager.GET_META_DATA, userId);
17565        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17566                true, false, false, userId);
17567
17568        allHomeCandidates.clear();
17569        if (list != null) {
17570            for (ResolveInfo ri : list) {
17571                allHomeCandidates.add(ri);
17572            }
17573        }
17574        return (preferred == null || preferred.activityInfo == null)
17575                ? null
17576                : new ComponentName(preferred.activityInfo.packageName,
17577                        preferred.activityInfo.name);
17578    }
17579
17580    @Override
17581    public void setHomeActivity(ComponentName comp, int userId) {
17582        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17583        getHomeActivitiesAsUser(homeActivities, userId);
17584
17585        boolean found = false;
17586
17587        final int size = homeActivities.size();
17588        final ComponentName[] set = new ComponentName[size];
17589        for (int i = 0; i < size; i++) {
17590            final ResolveInfo candidate = homeActivities.get(i);
17591            final ActivityInfo info = candidate.activityInfo;
17592            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17593            set[i] = activityName;
17594            if (!found && activityName.equals(comp)) {
17595                found = true;
17596            }
17597        }
17598        if (!found) {
17599            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17600                    + userId);
17601        }
17602        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17603                set, comp, userId);
17604    }
17605
17606    private @Nullable String getSetupWizardPackageName() {
17607        final Intent intent = new Intent(Intent.ACTION_MAIN);
17608        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17609
17610        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17611                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17612                        | MATCH_DISABLED_COMPONENTS,
17613                UserHandle.myUserId());
17614        if (matches.size() == 1) {
17615            return matches.get(0).getComponentInfo().packageName;
17616        } else {
17617            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17618                    + ": matches=" + matches);
17619            return null;
17620        }
17621    }
17622
17623    @Override
17624    public void setApplicationEnabledSetting(String appPackageName,
17625            int newState, int flags, int userId, String callingPackage) {
17626        if (!sUserManager.exists(userId)) return;
17627        if (callingPackage == null) {
17628            callingPackage = Integer.toString(Binder.getCallingUid());
17629        }
17630        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17631    }
17632
17633    @Override
17634    public void setComponentEnabledSetting(ComponentName componentName,
17635            int newState, int flags, int userId) {
17636        if (!sUserManager.exists(userId)) return;
17637        setEnabledSetting(componentName.getPackageName(),
17638                componentName.getClassName(), newState, flags, userId, null);
17639    }
17640
17641    private void setEnabledSetting(final String packageName, String className, int newState,
17642            final int flags, int userId, String callingPackage) {
17643        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17644              || newState == COMPONENT_ENABLED_STATE_ENABLED
17645              || newState == COMPONENT_ENABLED_STATE_DISABLED
17646              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17647              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17648            throw new IllegalArgumentException("Invalid new component state: "
17649                    + newState);
17650        }
17651        PackageSetting pkgSetting;
17652        final int uid = Binder.getCallingUid();
17653        final int permission;
17654        if (uid == Process.SYSTEM_UID) {
17655            permission = PackageManager.PERMISSION_GRANTED;
17656        } else {
17657            permission = mContext.checkCallingOrSelfPermission(
17658                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17659        }
17660        enforceCrossUserPermission(uid, userId,
17661                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17662        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17663        boolean sendNow = false;
17664        boolean isApp = (className == null);
17665        String componentName = isApp ? packageName : className;
17666        int packageUid = -1;
17667        ArrayList<String> components;
17668
17669        // writer
17670        synchronized (mPackages) {
17671            pkgSetting = mSettings.mPackages.get(packageName);
17672            if (pkgSetting == null) {
17673                if (className == null) {
17674                    throw new IllegalArgumentException("Unknown package: " + packageName);
17675                }
17676                throw new IllegalArgumentException(
17677                        "Unknown component: " + packageName + "/" + className);
17678            }
17679        }
17680
17681        // Limit who can change which apps
17682        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17683            // Don't allow apps that don't have permission to modify other apps
17684            if (!allowedByPermission) {
17685                throw new SecurityException(
17686                        "Permission Denial: attempt to change component state from pid="
17687                        + Binder.getCallingPid()
17688                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17689            }
17690            // Don't allow changing protected packages.
17691            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17692                throw new SecurityException("Cannot disable a protected package: " + packageName);
17693            }
17694        }
17695
17696        synchronized (mPackages) {
17697            if (uid == Process.SHELL_UID) {
17698                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17699                int oldState = pkgSetting.getEnabled(userId);
17700                if (className == null
17701                    &&
17702                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17703                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17704                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17705                    &&
17706                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17707                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17708                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17709                    // ok
17710                } else {
17711                    throw new SecurityException(
17712                            "Shell cannot change component state for " + packageName + "/"
17713                            + className + " to " + newState);
17714                }
17715            }
17716            if (className == null) {
17717                // We're dealing with an application/package level state change
17718                if (pkgSetting.getEnabled(userId) == newState) {
17719                    // Nothing to do
17720                    return;
17721                }
17722                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17723                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17724                    // Don't care about who enables an app.
17725                    callingPackage = null;
17726                }
17727                pkgSetting.setEnabled(newState, userId, callingPackage);
17728                // pkgSetting.pkg.mSetEnabled = newState;
17729            } else {
17730                // We're dealing with a component level state change
17731                // First, verify that this is a valid class name.
17732                PackageParser.Package pkg = pkgSetting.pkg;
17733                if (pkg == null || !pkg.hasComponentClassName(className)) {
17734                    if (pkg != null &&
17735                            pkg.applicationInfo.targetSdkVersion >=
17736                                    Build.VERSION_CODES.JELLY_BEAN) {
17737                        throw new IllegalArgumentException("Component class " + className
17738                                + " does not exist in " + packageName);
17739                    } else {
17740                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17741                                + className + " does not exist in " + packageName);
17742                    }
17743                }
17744                switch (newState) {
17745                case COMPONENT_ENABLED_STATE_ENABLED:
17746                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17747                        return;
17748                    }
17749                    break;
17750                case COMPONENT_ENABLED_STATE_DISABLED:
17751                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17752                        return;
17753                    }
17754                    break;
17755                case COMPONENT_ENABLED_STATE_DEFAULT:
17756                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17757                        return;
17758                    }
17759                    break;
17760                default:
17761                    Slog.e(TAG, "Invalid new component state: " + newState);
17762                    return;
17763                }
17764            }
17765            scheduleWritePackageRestrictionsLocked(userId);
17766            components = mPendingBroadcasts.get(userId, packageName);
17767            final boolean newPackage = components == null;
17768            if (newPackage) {
17769                components = new ArrayList<String>();
17770            }
17771            if (!components.contains(componentName)) {
17772                components.add(componentName);
17773            }
17774            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17775                sendNow = true;
17776                // Purge entry from pending broadcast list if another one exists already
17777                // since we are sending one right away.
17778                mPendingBroadcasts.remove(userId, packageName);
17779            } else {
17780                if (newPackage) {
17781                    mPendingBroadcasts.put(userId, packageName, components);
17782                }
17783                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17784                    // Schedule a message
17785                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17786                }
17787            }
17788        }
17789
17790        long callingId = Binder.clearCallingIdentity();
17791        try {
17792            if (sendNow) {
17793                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17794                sendPackageChangedBroadcast(packageName,
17795                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17796            }
17797        } finally {
17798            Binder.restoreCallingIdentity(callingId);
17799        }
17800    }
17801
17802    @Override
17803    public void flushPackageRestrictionsAsUser(int userId) {
17804        if (!sUserManager.exists(userId)) {
17805            return;
17806        }
17807        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17808                false /* checkShell */, "flushPackageRestrictions");
17809        synchronized (mPackages) {
17810            mSettings.writePackageRestrictionsLPr(userId);
17811            mDirtyUsers.remove(userId);
17812            if (mDirtyUsers.isEmpty()) {
17813                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17814            }
17815        }
17816    }
17817
17818    private void sendPackageChangedBroadcast(String packageName,
17819            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17820        if (DEBUG_INSTALL)
17821            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17822                    + componentNames);
17823        Bundle extras = new Bundle(4);
17824        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17825        String nameList[] = new String[componentNames.size()];
17826        componentNames.toArray(nameList);
17827        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17828        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17829        extras.putInt(Intent.EXTRA_UID, packageUid);
17830        // If this is not reporting a change of the overall package, then only send it
17831        // to registered receivers.  We don't want to launch a swath of apps for every
17832        // little component state change.
17833        final int flags = !componentNames.contains(packageName)
17834                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17835        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17836                new int[] {UserHandle.getUserId(packageUid)});
17837    }
17838
17839    @Override
17840    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17841        if (!sUserManager.exists(userId)) return;
17842        final int uid = Binder.getCallingUid();
17843        final int permission = mContext.checkCallingOrSelfPermission(
17844                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17845        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17846        enforceCrossUserPermission(uid, userId,
17847                true /* requireFullPermission */, true /* checkShell */, "stop package");
17848        // writer
17849        synchronized (mPackages) {
17850            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17851                    allowedByPermission, uid, userId)) {
17852                scheduleWritePackageRestrictionsLocked(userId);
17853            }
17854        }
17855    }
17856
17857    @Override
17858    public String getInstallerPackageName(String packageName) {
17859        // reader
17860        synchronized (mPackages) {
17861            return mSettings.getInstallerPackageNameLPr(packageName);
17862        }
17863    }
17864
17865    public boolean isOrphaned(String packageName) {
17866        // reader
17867        synchronized (mPackages) {
17868            return mSettings.isOrphaned(packageName);
17869        }
17870    }
17871
17872    @Override
17873    public int getApplicationEnabledSetting(String packageName, int userId) {
17874        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17875        int uid = Binder.getCallingUid();
17876        enforceCrossUserPermission(uid, userId,
17877                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17878        // reader
17879        synchronized (mPackages) {
17880            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17881        }
17882    }
17883
17884    @Override
17885    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17886        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17887        int uid = Binder.getCallingUid();
17888        enforceCrossUserPermission(uid, userId,
17889                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17890        // reader
17891        synchronized (mPackages) {
17892            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17893        }
17894    }
17895
17896    @Override
17897    public void enterSafeMode() {
17898        enforceSystemOrRoot("Only the system can request entering safe mode");
17899
17900        if (!mSystemReady) {
17901            mSafeMode = true;
17902        }
17903    }
17904
17905    @Override
17906    public void systemReady() {
17907        mSystemReady = true;
17908
17909        // Read the compatibilty setting when the system is ready.
17910        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17911                mContext.getContentResolver(),
17912                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17913        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17914        if (DEBUG_SETTINGS) {
17915            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17916        }
17917
17918        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17919
17920        synchronized (mPackages) {
17921            // Verify that all of the preferred activity components actually
17922            // exist.  It is possible for applications to be updated and at
17923            // that point remove a previously declared activity component that
17924            // had been set as a preferred activity.  We try to clean this up
17925            // the next time we encounter that preferred activity, but it is
17926            // possible for the user flow to never be able to return to that
17927            // situation so here we do a sanity check to make sure we haven't
17928            // left any junk around.
17929            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17930            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17931                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17932                removed.clear();
17933                for (PreferredActivity pa : pir.filterSet()) {
17934                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17935                        removed.add(pa);
17936                    }
17937                }
17938                if (removed.size() > 0) {
17939                    for (int r=0; r<removed.size(); r++) {
17940                        PreferredActivity pa = removed.get(r);
17941                        Slog.w(TAG, "Removing dangling preferred activity: "
17942                                + pa.mPref.mComponent);
17943                        pir.removeFilter(pa);
17944                    }
17945                    mSettings.writePackageRestrictionsLPr(
17946                            mSettings.mPreferredActivities.keyAt(i));
17947                }
17948            }
17949
17950            for (int userId : UserManagerService.getInstance().getUserIds()) {
17951                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17952                    grantPermissionsUserIds = ArrayUtils.appendInt(
17953                            grantPermissionsUserIds, userId);
17954                }
17955            }
17956        }
17957        sUserManager.systemReady();
17958
17959        // If we upgraded grant all default permissions before kicking off.
17960        for (int userId : grantPermissionsUserIds) {
17961            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17962        }
17963
17964        // Kick off any messages waiting for system ready
17965        if (mPostSystemReadyMessages != null) {
17966            for (Message msg : mPostSystemReadyMessages) {
17967                msg.sendToTarget();
17968            }
17969            mPostSystemReadyMessages = null;
17970        }
17971
17972        // Watch for external volumes that come and go over time
17973        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17974        storage.registerListener(mStorageListener);
17975
17976        mInstallerService.systemReady();
17977        mPackageDexOptimizer.systemReady();
17978
17979        MountServiceInternal mountServiceInternal = LocalServices.getService(
17980                MountServiceInternal.class);
17981        mountServiceInternal.addExternalStoragePolicy(
17982                new MountServiceInternal.ExternalStorageMountPolicy() {
17983            @Override
17984            public int getMountMode(int uid, String packageName) {
17985                if (Process.isIsolated(uid)) {
17986                    return Zygote.MOUNT_EXTERNAL_NONE;
17987                }
17988                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17989                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17990                }
17991                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17992                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17993                }
17994                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17995                    return Zygote.MOUNT_EXTERNAL_READ;
17996                }
17997                return Zygote.MOUNT_EXTERNAL_WRITE;
17998            }
17999
18000            @Override
18001            public boolean hasExternalStorage(int uid, String packageName) {
18002                return true;
18003            }
18004        });
18005
18006        // Now that we're mostly running, clean up stale users and apps
18007        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18008        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18009    }
18010
18011    @Override
18012    public boolean isSafeMode() {
18013        return mSafeMode;
18014    }
18015
18016    @Override
18017    public boolean hasSystemUidErrors() {
18018        return mHasSystemUidErrors;
18019    }
18020
18021    static String arrayToString(int[] array) {
18022        StringBuffer buf = new StringBuffer(128);
18023        buf.append('[');
18024        if (array != null) {
18025            for (int i=0; i<array.length; i++) {
18026                if (i > 0) buf.append(", ");
18027                buf.append(array[i]);
18028            }
18029        }
18030        buf.append(']');
18031        return buf.toString();
18032    }
18033
18034    static class DumpState {
18035        public static final int DUMP_LIBS = 1 << 0;
18036        public static final int DUMP_FEATURES = 1 << 1;
18037        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18038        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18039        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18040        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18041        public static final int DUMP_PERMISSIONS = 1 << 6;
18042        public static final int DUMP_PACKAGES = 1 << 7;
18043        public static final int DUMP_SHARED_USERS = 1 << 8;
18044        public static final int DUMP_MESSAGES = 1 << 9;
18045        public static final int DUMP_PROVIDERS = 1 << 10;
18046        public static final int DUMP_VERIFIERS = 1 << 11;
18047        public static final int DUMP_PREFERRED = 1 << 12;
18048        public static final int DUMP_PREFERRED_XML = 1 << 13;
18049        public static final int DUMP_KEYSETS = 1 << 14;
18050        public static final int DUMP_VERSION = 1 << 15;
18051        public static final int DUMP_INSTALLS = 1 << 16;
18052        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18053        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18054        public static final int DUMP_FROZEN = 1 << 19;
18055        public static final int DUMP_DEXOPT = 1 << 20;
18056        public static final int DUMP_COMPILER_STATS = 1 << 21;
18057
18058        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18059
18060        private int mTypes;
18061
18062        private int mOptions;
18063
18064        private boolean mTitlePrinted;
18065
18066        private SharedUserSetting mSharedUser;
18067
18068        public boolean isDumping(int type) {
18069            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18070                return true;
18071            }
18072
18073            return (mTypes & type) != 0;
18074        }
18075
18076        public void setDump(int type) {
18077            mTypes |= type;
18078        }
18079
18080        public boolean isOptionEnabled(int option) {
18081            return (mOptions & option) != 0;
18082        }
18083
18084        public void setOptionEnabled(int option) {
18085            mOptions |= option;
18086        }
18087
18088        public boolean onTitlePrinted() {
18089            final boolean printed = mTitlePrinted;
18090            mTitlePrinted = true;
18091            return printed;
18092        }
18093
18094        public boolean getTitlePrinted() {
18095            return mTitlePrinted;
18096        }
18097
18098        public void setTitlePrinted(boolean enabled) {
18099            mTitlePrinted = enabled;
18100        }
18101
18102        public SharedUserSetting getSharedUser() {
18103            return mSharedUser;
18104        }
18105
18106        public void setSharedUser(SharedUserSetting user) {
18107            mSharedUser = user;
18108        }
18109    }
18110
18111    @Override
18112    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18113            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18114        (new PackageManagerShellCommand(this)).exec(
18115                this, in, out, err, args, resultReceiver);
18116    }
18117
18118    @Override
18119    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18120        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18121                != PackageManager.PERMISSION_GRANTED) {
18122            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18123                    + Binder.getCallingPid()
18124                    + ", uid=" + Binder.getCallingUid()
18125                    + " without permission "
18126                    + android.Manifest.permission.DUMP);
18127            return;
18128        }
18129
18130        DumpState dumpState = new DumpState();
18131        boolean fullPreferred = false;
18132        boolean checkin = false;
18133
18134        String packageName = null;
18135        ArraySet<String> permissionNames = null;
18136
18137        int opti = 0;
18138        while (opti < args.length) {
18139            String opt = args[opti];
18140            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18141                break;
18142            }
18143            opti++;
18144
18145            if ("-a".equals(opt)) {
18146                // Right now we only know how to print all.
18147            } else if ("-h".equals(opt)) {
18148                pw.println("Package manager dump options:");
18149                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18150                pw.println("    --checkin: dump for a checkin");
18151                pw.println("    -f: print details of intent filters");
18152                pw.println("    -h: print this help");
18153                pw.println("  cmd may be one of:");
18154                pw.println("    l[ibraries]: list known shared libraries");
18155                pw.println("    f[eatures]: list device features");
18156                pw.println("    k[eysets]: print known keysets");
18157                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18158                pw.println("    perm[issions]: dump permissions");
18159                pw.println("    permission [name ...]: dump declaration and use of given permission");
18160                pw.println("    pref[erred]: print preferred package settings");
18161                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18162                pw.println("    prov[iders]: dump content providers");
18163                pw.println("    p[ackages]: dump installed packages");
18164                pw.println("    s[hared-users]: dump shared user IDs");
18165                pw.println("    m[essages]: print collected runtime messages");
18166                pw.println("    v[erifiers]: print package verifier info");
18167                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18168                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18169                pw.println("    version: print database version info");
18170                pw.println("    write: write current settings now");
18171                pw.println("    installs: details about install sessions");
18172                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18173                pw.println("    dexopt: dump dexopt state");
18174                pw.println("    compiler-stats: dump compiler statistics");
18175                pw.println("    <package.name>: info about given package");
18176                return;
18177            } else if ("--checkin".equals(opt)) {
18178                checkin = true;
18179            } else if ("-f".equals(opt)) {
18180                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18181            } else {
18182                pw.println("Unknown argument: " + opt + "; use -h for help");
18183            }
18184        }
18185
18186        // Is the caller requesting to dump a particular piece of data?
18187        if (opti < args.length) {
18188            String cmd = args[opti];
18189            opti++;
18190            // Is this a package name?
18191            if ("android".equals(cmd) || cmd.contains(".")) {
18192                packageName = cmd;
18193                // When dumping a single package, we always dump all of its
18194                // filter information since the amount of data will be reasonable.
18195                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18196            } else if ("check-permission".equals(cmd)) {
18197                if (opti >= args.length) {
18198                    pw.println("Error: check-permission missing permission argument");
18199                    return;
18200                }
18201                String perm = args[opti];
18202                opti++;
18203                if (opti >= args.length) {
18204                    pw.println("Error: check-permission missing package argument");
18205                    return;
18206                }
18207                String pkg = args[opti];
18208                opti++;
18209                int user = UserHandle.getUserId(Binder.getCallingUid());
18210                if (opti < args.length) {
18211                    try {
18212                        user = Integer.parseInt(args[opti]);
18213                    } catch (NumberFormatException e) {
18214                        pw.println("Error: check-permission user argument is not a number: "
18215                                + args[opti]);
18216                        return;
18217                    }
18218                }
18219                pw.println(checkPermission(perm, pkg, user));
18220                return;
18221            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18222                dumpState.setDump(DumpState.DUMP_LIBS);
18223            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18224                dumpState.setDump(DumpState.DUMP_FEATURES);
18225            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18226                if (opti >= args.length) {
18227                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18228                            | DumpState.DUMP_SERVICE_RESOLVERS
18229                            | DumpState.DUMP_RECEIVER_RESOLVERS
18230                            | DumpState.DUMP_CONTENT_RESOLVERS);
18231                } else {
18232                    while (opti < args.length) {
18233                        String name = args[opti];
18234                        if ("a".equals(name) || "activity".equals(name)) {
18235                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18236                        } else if ("s".equals(name) || "service".equals(name)) {
18237                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18238                        } else if ("r".equals(name) || "receiver".equals(name)) {
18239                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18240                        } else if ("c".equals(name) || "content".equals(name)) {
18241                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18242                        } else {
18243                            pw.println("Error: unknown resolver table type: " + name);
18244                            return;
18245                        }
18246                        opti++;
18247                    }
18248                }
18249            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18250                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18251            } else if ("permission".equals(cmd)) {
18252                if (opti >= args.length) {
18253                    pw.println("Error: permission requires permission name");
18254                    return;
18255                }
18256                permissionNames = new ArraySet<>();
18257                while (opti < args.length) {
18258                    permissionNames.add(args[opti]);
18259                    opti++;
18260                }
18261                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18262                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18263            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18264                dumpState.setDump(DumpState.DUMP_PREFERRED);
18265            } else if ("preferred-xml".equals(cmd)) {
18266                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18267                if (opti < args.length && "--full".equals(args[opti])) {
18268                    fullPreferred = true;
18269                    opti++;
18270                }
18271            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18272                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18273            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18274                dumpState.setDump(DumpState.DUMP_PACKAGES);
18275            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18276                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18277            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18278                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18279            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18280                dumpState.setDump(DumpState.DUMP_MESSAGES);
18281            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18282                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18283            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18284                    || "intent-filter-verifiers".equals(cmd)) {
18285                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18286            } else if ("version".equals(cmd)) {
18287                dumpState.setDump(DumpState.DUMP_VERSION);
18288            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18289                dumpState.setDump(DumpState.DUMP_KEYSETS);
18290            } else if ("installs".equals(cmd)) {
18291                dumpState.setDump(DumpState.DUMP_INSTALLS);
18292            } else if ("frozen".equals(cmd)) {
18293                dumpState.setDump(DumpState.DUMP_FROZEN);
18294            } else if ("dexopt".equals(cmd)) {
18295                dumpState.setDump(DumpState.DUMP_DEXOPT);
18296            } else if ("compiler-stats".equals(cmd)) {
18297                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18298            } else if ("write".equals(cmd)) {
18299                synchronized (mPackages) {
18300                    mSettings.writeLPr();
18301                    pw.println("Settings written.");
18302                    return;
18303                }
18304            }
18305        }
18306
18307        if (checkin) {
18308            pw.println("vers,1");
18309        }
18310
18311        // reader
18312        synchronized (mPackages) {
18313            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18314                if (!checkin) {
18315                    if (dumpState.onTitlePrinted())
18316                        pw.println();
18317                    pw.println("Database versions:");
18318                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18319                }
18320            }
18321
18322            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18323                if (!checkin) {
18324                    if (dumpState.onTitlePrinted())
18325                        pw.println();
18326                    pw.println("Verifiers:");
18327                    pw.print("  Required: ");
18328                    pw.print(mRequiredVerifierPackage);
18329                    pw.print(" (uid=");
18330                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18331                            UserHandle.USER_SYSTEM));
18332                    pw.println(")");
18333                } else if (mRequiredVerifierPackage != null) {
18334                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18335                    pw.print(",");
18336                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18337                            UserHandle.USER_SYSTEM));
18338                }
18339            }
18340
18341            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18342                    packageName == null) {
18343                if (mIntentFilterVerifierComponent != null) {
18344                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18345                    if (!checkin) {
18346                        if (dumpState.onTitlePrinted())
18347                            pw.println();
18348                        pw.println("Intent Filter Verifier:");
18349                        pw.print("  Using: ");
18350                        pw.print(verifierPackageName);
18351                        pw.print(" (uid=");
18352                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18353                                UserHandle.USER_SYSTEM));
18354                        pw.println(")");
18355                    } else if (verifierPackageName != null) {
18356                        pw.print("ifv,"); pw.print(verifierPackageName);
18357                        pw.print(",");
18358                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18359                                UserHandle.USER_SYSTEM));
18360                    }
18361                } else {
18362                    pw.println();
18363                    pw.println("No Intent Filter Verifier available!");
18364                }
18365            }
18366
18367            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18368                boolean printedHeader = false;
18369                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18370                while (it.hasNext()) {
18371                    String name = it.next();
18372                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18373                    if (!checkin) {
18374                        if (!printedHeader) {
18375                            if (dumpState.onTitlePrinted())
18376                                pw.println();
18377                            pw.println("Libraries:");
18378                            printedHeader = true;
18379                        }
18380                        pw.print("  ");
18381                    } else {
18382                        pw.print("lib,");
18383                    }
18384                    pw.print(name);
18385                    if (!checkin) {
18386                        pw.print(" -> ");
18387                    }
18388                    if (ent.path != null) {
18389                        if (!checkin) {
18390                            pw.print("(jar) ");
18391                            pw.print(ent.path);
18392                        } else {
18393                            pw.print(",jar,");
18394                            pw.print(ent.path);
18395                        }
18396                    } else {
18397                        if (!checkin) {
18398                            pw.print("(apk) ");
18399                            pw.print(ent.apk);
18400                        } else {
18401                            pw.print(",apk,");
18402                            pw.print(ent.apk);
18403                        }
18404                    }
18405                    pw.println();
18406                }
18407            }
18408
18409            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18410                if (dumpState.onTitlePrinted())
18411                    pw.println();
18412                if (!checkin) {
18413                    pw.println("Features:");
18414                }
18415
18416                for (FeatureInfo feat : mAvailableFeatures.values()) {
18417                    if (checkin) {
18418                        pw.print("feat,");
18419                        pw.print(feat.name);
18420                        pw.print(",");
18421                        pw.println(feat.version);
18422                    } else {
18423                        pw.print("  ");
18424                        pw.print(feat.name);
18425                        if (feat.version > 0) {
18426                            pw.print(" version=");
18427                            pw.print(feat.version);
18428                        }
18429                        pw.println();
18430                    }
18431                }
18432            }
18433
18434            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18435                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18436                        : "Activity Resolver Table:", "  ", packageName,
18437                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18438                    dumpState.setTitlePrinted(true);
18439                }
18440            }
18441            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18442                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18443                        : "Receiver Resolver Table:", "  ", packageName,
18444                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18445                    dumpState.setTitlePrinted(true);
18446                }
18447            }
18448            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18449                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18450                        : "Service Resolver Table:", "  ", packageName,
18451                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18452                    dumpState.setTitlePrinted(true);
18453                }
18454            }
18455            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18456                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18457                        : "Provider Resolver Table:", "  ", packageName,
18458                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18459                    dumpState.setTitlePrinted(true);
18460                }
18461            }
18462
18463            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18464                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18465                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18466                    int user = mSettings.mPreferredActivities.keyAt(i);
18467                    if (pir.dump(pw,
18468                            dumpState.getTitlePrinted()
18469                                ? "\nPreferred Activities User " + user + ":"
18470                                : "Preferred Activities User " + user + ":", "  ",
18471                            packageName, true, false)) {
18472                        dumpState.setTitlePrinted(true);
18473                    }
18474                }
18475            }
18476
18477            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18478                pw.flush();
18479                FileOutputStream fout = new FileOutputStream(fd);
18480                BufferedOutputStream str = new BufferedOutputStream(fout);
18481                XmlSerializer serializer = new FastXmlSerializer();
18482                try {
18483                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18484                    serializer.startDocument(null, true);
18485                    serializer.setFeature(
18486                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18487                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18488                    serializer.endDocument();
18489                    serializer.flush();
18490                } catch (IllegalArgumentException e) {
18491                    pw.println("Failed writing: " + e);
18492                } catch (IllegalStateException e) {
18493                    pw.println("Failed writing: " + e);
18494                } catch (IOException e) {
18495                    pw.println("Failed writing: " + e);
18496                }
18497            }
18498
18499            if (!checkin
18500                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18501                    && packageName == null) {
18502                pw.println();
18503                int count = mSettings.mPackages.size();
18504                if (count == 0) {
18505                    pw.println("No applications!");
18506                    pw.println();
18507                } else {
18508                    final String prefix = "  ";
18509                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18510                    if (allPackageSettings.size() == 0) {
18511                        pw.println("No domain preferred apps!");
18512                        pw.println();
18513                    } else {
18514                        pw.println("App verification status:");
18515                        pw.println();
18516                        count = 0;
18517                        for (PackageSetting ps : allPackageSettings) {
18518                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18519                            if (ivi == null || ivi.getPackageName() == null) continue;
18520                            pw.println(prefix + "Package: " + ivi.getPackageName());
18521                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18522                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18523                            pw.println();
18524                            count++;
18525                        }
18526                        if (count == 0) {
18527                            pw.println(prefix + "No app verification established.");
18528                            pw.println();
18529                        }
18530                        for (int userId : sUserManager.getUserIds()) {
18531                            pw.println("App linkages for user " + userId + ":");
18532                            pw.println();
18533                            count = 0;
18534                            for (PackageSetting ps : allPackageSettings) {
18535                                final long status = ps.getDomainVerificationStatusForUser(userId);
18536                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18537                                    continue;
18538                                }
18539                                pw.println(prefix + "Package: " + ps.name);
18540                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18541                                String statusStr = IntentFilterVerificationInfo.
18542                                        getStatusStringFromValue(status);
18543                                pw.println(prefix + "Status:  " + statusStr);
18544                                pw.println();
18545                                count++;
18546                            }
18547                            if (count == 0) {
18548                                pw.println(prefix + "No configured app linkages.");
18549                                pw.println();
18550                            }
18551                        }
18552                    }
18553                }
18554            }
18555
18556            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18557                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18558                if (packageName == null && permissionNames == null) {
18559                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18560                        if (iperm == 0) {
18561                            if (dumpState.onTitlePrinted())
18562                                pw.println();
18563                            pw.println("AppOp Permissions:");
18564                        }
18565                        pw.print("  AppOp Permission ");
18566                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18567                        pw.println(":");
18568                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18569                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18570                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18571                        }
18572                    }
18573                }
18574            }
18575
18576            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18577                boolean printedSomething = false;
18578                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18579                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18580                        continue;
18581                    }
18582                    if (!printedSomething) {
18583                        if (dumpState.onTitlePrinted())
18584                            pw.println();
18585                        pw.println("Registered ContentProviders:");
18586                        printedSomething = true;
18587                    }
18588                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18589                    pw.print("    "); pw.println(p.toString());
18590                }
18591                printedSomething = false;
18592                for (Map.Entry<String, PackageParser.Provider> entry :
18593                        mProvidersByAuthority.entrySet()) {
18594                    PackageParser.Provider p = entry.getValue();
18595                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18596                        continue;
18597                    }
18598                    if (!printedSomething) {
18599                        if (dumpState.onTitlePrinted())
18600                            pw.println();
18601                        pw.println("ContentProvider Authorities:");
18602                        printedSomething = true;
18603                    }
18604                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18605                    pw.print("    "); pw.println(p.toString());
18606                    if (p.info != null && p.info.applicationInfo != null) {
18607                        final String appInfo = p.info.applicationInfo.toString();
18608                        pw.print("      applicationInfo="); pw.println(appInfo);
18609                    }
18610                }
18611            }
18612
18613            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18614                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18615            }
18616
18617            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18618                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18619            }
18620
18621            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18622                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18623            }
18624
18625            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18626                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18627            }
18628
18629            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18630                // XXX should handle packageName != null by dumping only install data that
18631                // the given package is involved with.
18632                if (dumpState.onTitlePrinted()) pw.println();
18633                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18634            }
18635
18636            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18637                // XXX should handle packageName != null by dumping only install data that
18638                // the given package is involved with.
18639                if (dumpState.onTitlePrinted()) pw.println();
18640
18641                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18642                ipw.println();
18643                ipw.println("Frozen packages:");
18644                ipw.increaseIndent();
18645                if (mFrozenPackages.size() == 0) {
18646                    ipw.println("(none)");
18647                } else {
18648                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18649                        ipw.println(mFrozenPackages.valueAt(i));
18650                    }
18651                }
18652                ipw.decreaseIndent();
18653            }
18654
18655            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18656                if (dumpState.onTitlePrinted()) pw.println();
18657                dumpDexoptStateLPr(pw, packageName);
18658            }
18659
18660            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18661                if (dumpState.onTitlePrinted()) pw.println();
18662                dumpCompilerStatsLPr(pw, packageName);
18663            }
18664
18665            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18666                if (dumpState.onTitlePrinted()) pw.println();
18667                mSettings.dumpReadMessagesLPr(pw, dumpState);
18668
18669                pw.println();
18670                pw.println("Package warning messages:");
18671                BufferedReader in = null;
18672                String line = null;
18673                try {
18674                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18675                    while ((line = in.readLine()) != null) {
18676                        if (line.contains("ignored: updated version")) continue;
18677                        pw.println(line);
18678                    }
18679                } catch (IOException ignored) {
18680                } finally {
18681                    IoUtils.closeQuietly(in);
18682                }
18683            }
18684
18685            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18686                BufferedReader in = null;
18687                String line = null;
18688                try {
18689                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18690                    while ((line = in.readLine()) != null) {
18691                        if (line.contains("ignored: updated version")) continue;
18692                        pw.print("msg,");
18693                        pw.println(line);
18694                    }
18695                } catch (IOException ignored) {
18696                } finally {
18697                    IoUtils.closeQuietly(in);
18698                }
18699            }
18700        }
18701    }
18702
18703    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18704        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18705        ipw.println();
18706        ipw.println("Dexopt state:");
18707        ipw.increaseIndent();
18708        Collection<PackageParser.Package> packages = null;
18709        if (packageName != null) {
18710            PackageParser.Package targetPackage = mPackages.get(packageName);
18711            if (targetPackage != null) {
18712                packages = Collections.singletonList(targetPackage);
18713            } else {
18714                ipw.println("Unable to find package: " + packageName);
18715                return;
18716            }
18717        } else {
18718            packages = mPackages.values();
18719        }
18720
18721        for (PackageParser.Package pkg : packages) {
18722            ipw.println("[" + pkg.packageName + "]");
18723            ipw.increaseIndent();
18724            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18725            ipw.decreaseIndent();
18726        }
18727    }
18728
18729    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18730        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18731        ipw.println();
18732        ipw.println("Compiler stats:");
18733        ipw.increaseIndent();
18734        Collection<PackageParser.Package> packages = null;
18735        if (packageName != null) {
18736            PackageParser.Package targetPackage = mPackages.get(packageName);
18737            if (targetPackage != null) {
18738                packages = Collections.singletonList(targetPackage);
18739            } else {
18740                ipw.println("Unable to find package: " + packageName);
18741                return;
18742            }
18743        } else {
18744            packages = mPackages.values();
18745        }
18746
18747        for (PackageParser.Package pkg : packages) {
18748            ipw.println("[" + pkg.packageName + "]");
18749            ipw.increaseIndent();
18750
18751            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18752            if (stats == null) {
18753                ipw.println("(No recorded stats)");
18754            } else {
18755                stats.dump(ipw);
18756            }
18757            ipw.decreaseIndent();
18758        }
18759    }
18760
18761    private String dumpDomainString(String packageName) {
18762        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18763                .getList();
18764        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18765
18766        ArraySet<String> result = new ArraySet<>();
18767        if (iviList.size() > 0) {
18768            for (IntentFilterVerificationInfo ivi : iviList) {
18769                for (String host : ivi.getDomains()) {
18770                    result.add(host);
18771                }
18772            }
18773        }
18774        if (filters != null && filters.size() > 0) {
18775            for (IntentFilter filter : filters) {
18776                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18777                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18778                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18779                    result.addAll(filter.getHostsList());
18780                }
18781            }
18782        }
18783
18784        StringBuilder sb = new StringBuilder(result.size() * 16);
18785        for (String domain : result) {
18786            if (sb.length() > 0) sb.append(" ");
18787            sb.append(domain);
18788        }
18789        return sb.toString();
18790    }
18791
18792    // ------- apps on sdcard specific code -------
18793    static final boolean DEBUG_SD_INSTALL = false;
18794
18795    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18796
18797    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18798
18799    private boolean mMediaMounted = false;
18800
18801    static String getEncryptKey() {
18802        try {
18803            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18804                    SD_ENCRYPTION_KEYSTORE_NAME);
18805            if (sdEncKey == null) {
18806                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18807                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18808                if (sdEncKey == null) {
18809                    Slog.e(TAG, "Failed to create encryption keys");
18810                    return null;
18811                }
18812            }
18813            return sdEncKey;
18814        } catch (NoSuchAlgorithmException nsae) {
18815            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18816            return null;
18817        } catch (IOException ioe) {
18818            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18819            return null;
18820        }
18821    }
18822
18823    /*
18824     * Update media status on PackageManager.
18825     */
18826    @Override
18827    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18828        int callingUid = Binder.getCallingUid();
18829        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18830            throw new SecurityException("Media status can only be updated by the system");
18831        }
18832        // reader; this apparently protects mMediaMounted, but should probably
18833        // be a different lock in that case.
18834        synchronized (mPackages) {
18835            Log.i(TAG, "Updating external media status from "
18836                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18837                    + (mediaStatus ? "mounted" : "unmounted"));
18838            if (DEBUG_SD_INSTALL)
18839                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18840                        + ", mMediaMounted=" + mMediaMounted);
18841            if (mediaStatus == mMediaMounted) {
18842                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18843                        : 0, -1);
18844                mHandler.sendMessage(msg);
18845                return;
18846            }
18847            mMediaMounted = mediaStatus;
18848        }
18849        // Queue up an async operation since the package installation may take a
18850        // little while.
18851        mHandler.post(new Runnable() {
18852            public void run() {
18853                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18854            }
18855        });
18856    }
18857
18858    /**
18859     * Called by MountService when the initial ASECs to scan are available.
18860     * Should block until all the ASEC containers are finished being scanned.
18861     */
18862    public void scanAvailableAsecs() {
18863        updateExternalMediaStatusInner(true, false, false);
18864    }
18865
18866    /*
18867     * Collect information of applications on external media, map them against
18868     * existing containers and update information based on current mount status.
18869     * Please note that we always have to report status if reportStatus has been
18870     * set to true especially when unloading packages.
18871     */
18872    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18873            boolean externalStorage) {
18874        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18875        int[] uidArr = EmptyArray.INT;
18876
18877        final String[] list = PackageHelper.getSecureContainerList();
18878        if (ArrayUtils.isEmpty(list)) {
18879            Log.i(TAG, "No secure containers found");
18880        } else {
18881            // Process list of secure containers and categorize them
18882            // as active or stale based on their package internal state.
18883
18884            // reader
18885            synchronized (mPackages) {
18886                for (String cid : list) {
18887                    // Leave stages untouched for now; installer service owns them
18888                    if (PackageInstallerService.isStageName(cid)) continue;
18889
18890                    if (DEBUG_SD_INSTALL)
18891                        Log.i(TAG, "Processing container " + cid);
18892                    String pkgName = getAsecPackageName(cid);
18893                    if (pkgName == null) {
18894                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18895                        continue;
18896                    }
18897                    if (DEBUG_SD_INSTALL)
18898                        Log.i(TAG, "Looking for pkg : " + pkgName);
18899
18900                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18901                    if (ps == null) {
18902                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18903                        continue;
18904                    }
18905
18906                    /*
18907                     * Skip packages that are not external if we're unmounting
18908                     * external storage.
18909                     */
18910                    if (externalStorage && !isMounted && !isExternal(ps)) {
18911                        continue;
18912                    }
18913
18914                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18915                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18916                    // The package status is changed only if the code path
18917                    // matches between settings and the container id.
18918                    if (ps.codePathString != null
18919                            && ps.codePathString.startsWith(args.getCodePath())) {
18920                        if (DEBUG_SD_INSTALL) {
18921                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18922                                    + " at code path: " + ps.codePathString);
18923                        }
18924
18925                        // We do have a valid package installed on sdcard
18926                        processCids.put(args, ps.codePathString);
18927                        final int uid = ps.appId;
18928                        if (uid != -1) {
18929                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18930                        }
18931                    } else {
18932                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18933                                + ps.codePathString);
18934                    }
18935                }
18936            }
18937
18938            Arrays.sort(uidArr);
18939        }
18940
18941        // Process packages with valid entries.
18942        if (isMounted) {
18943            if (DEBUG_SD_INSTALL)
18944                Log.i(TAG, "Loading packages");
18945            loadMediaPackages(processCids, uidArr, externalStorage);
18946            startCleaningPackages();
18947            mInstallerService.onSecureContainersAvailable();
18948        } else {
18949            if (DEBUG_SD_INSTALL)
18950                Log.i(TAG, "Unloading packages");
18951            unloadMediaPackages(processCids, uidArr, reportStatus);
18952        }
18953    }
18954
18955    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18956            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18957        final int size = infos.size();
18958        final String[] packageNames = new String[size];
18959        final int[] packageUids = new int[size];
18960        for (int i = 0; i < size; i++) {
18961            final ApplicationInfo info = infos.get(i);
18962            packageNames[i] = info.packageName;
18963            packageUids[i] = info.uid;
18964        }
18965        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18966                finishedReceiver);
18967    }
18968
18969    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18970            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18971        sendResourcesChangedBroadcast(mediaStatus, replacing,
18972                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18973    }
18974
18975    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18976            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18977        int size = pkgList.length;
18978        if (size > 0) {
18979            // Send broadcasts here
18980            Bundle extras = new Bundle();
18981            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18982            if (uidArr != null) {
18983                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18984            }
18985            if (replacing) {
18986                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18987            }
18988            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18989                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18990            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18991        }
18992    }
18993
18994   /*
18995     * Look at potentially valid container ids from processCids If package
18996     * information doesn't match the one on record or package scanning fails,
18997     * the cid is added to list of removeCids. We currently don't delete stale
18998     * containers.
18999     */
19000    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19001            boolean externalStorage) {
19002        ArrayList<String> pkgList = new ArrayList<String>();
19003        Set<AsecInstallArgs> keys = processCids.keySet();
19004
19005        for (AsecInstallArgs args : keys) {
19006            String codePath = processCids.get(args);
19007            if (DEBUG_SD_INSTALL)
19008                Log.i(TAG, "Loading container : " + args.cid);
19009            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19010            try {
19011                // Make sure there are no container errors first.
19012                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19013                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19014                            + " when installing from sdcard");
19015                    continue;
19016                }
19017                // Check code path here.
19018                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19019                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19020                            + " does not match one in settings " + codePath);
19021                    continue;
19022                }
19023                // Parse package
19024                int parseFlags = mDefParseFlags;
19025                if (args.isExternalAsec()) {
19026                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19027                }
19028                if (args.isFwdLocked()) {
19029                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19030                }
19031
19032                synchronized (mInstallLock) {
19033                    PackageParser.Package pkg = null;
19034                    try {
19035                        // Sadly we don't know the package name yet to freeze it
19036                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19037                                SCAN_IGNORE_FROZEN, 0, null);
19038                    } catch (PackageManagerException e) {
19039                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19040                    }
19041                    // Scan the package
19042                    if (pkg != null) {
19043                        /*
19044                         * TODO why is the lock being held? doPostInstall is
19045                         * called in other places without the lock. This needs
19046                         * to be straightened out.
19047                         */
19048                        // writer
19049                        synchronized (mPackages) {
19050                            retCode = PackageManager.INSTALL_SUCCEEDED;
19051                            pkgList.add(pkg.packageName);
19052                            // Post process args
19053                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19054                                    pkg.applicationInfo.uid);
19055                        }
19056                    } else {
19057                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19058                    }
19059                }
19060
19061            } finally {
19062                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19063                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19064                }
19065            }
19066        }
19067        // writer
19068        synchronized (mPackages) {
19069            // If the platform SDK has changed since the last time we booted,
19070            // we need to re-grant app permission to catch any new ones that
19071            // appear. This is really a hack, and means that apps can in some
19072            // cases get permissions that the user didn't initially explicitly
19073            // allow... it would be nice to have some better way to handle
19074            // this situation.
19075            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19076                    : mSettings.getInternalVersion();
19077            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19078                    : StorageManager.UUID_PRIVATE_INTERNAL;
19079
19080            int updateFlags = UPDATE_PERMISSIONS_ALL;
19081            if (ver.sdkVersion != mSdkVersion) {
19082                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19083                        + mSdkVersion + "; regranting permissions for external");
19084                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19085            }
19086            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19087
19088            // Yay, everything is now upgraded
19089            ver.forceCurrent();
19090
19091            // can downgrade to reader
19092            // Persist settings
19093            mSettings.writeLPr();
19094        }
19095        // Send a broadcast to let everyone know we are done processing
19096        if (pkgList.size() > 0) {
19097            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19098        }
19099    }
19100
19101   /*
19102     * Utility method to unload a list of specified containers
19103     */
19104    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19105        // Just unmount all valid containers.
19106        for (AsecInstallArgs arg : cidArgs) {
19107            synchronized (mInstallLock) {
19108                arg.doPostDeleteLI(false);
19109           }
19110       }
19111   }
19112
19113    /*
19114     * Unload packages mounted on external media. This involves deleting package
19115     * data from internal structures, sending broadcasts about disabled packages,
19116     * gc'ing to free up references, unmounting all secure containers
19117     * corresponding to packages on external media, and posting a
19118     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19119     * that we always have to post this message if status has been requested no
19120     * matter what.
19121     */
19122    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19123            final boolean reportStatus) {
19124        if (DEBUG_SD_INSTALL)
19125            Log.i(TAG, "unloading media packages");
19126        ArrayList<String> pkgList = new ArrayList<String>();
19127        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19128        final Set<AsecInstallArgs> keys = processCids.keySet();
19129        for (AsecInstallArgs args : keys) {
19130            String pkgName = args.getPackageName();
19131            if (DEBUG_SD_INSTALL)
19132                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19133            // Delete package internally
19134            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19135            synchronized (mInstallLock) {
19136                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19137                final boolean res;
19138                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19139                        "unloadMediaPackages")) {
19140                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19141                            null);
19142                }
19143                if (res) {
19144                    pkgList.add(pkgName);
19145                } else {
19146                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19147                    failedList.add(args);
19148                }
19149            }
19150        }
19151
19152        // reader
19153        synchronized (mPackages) {
19154            // We didn't update the settings after removing each package;
19155            // write them now for all packages.
19156            mSettings.writeLPr();
19157        }
19158
19159        // We have to absolutely send UPDATED_MEDIA_STATUS only
19160        // after confirming that all the receivers processed the ordered
19161        // broadcast when packages get disabled, force a gc to clean things up.
19162        // and unload all the containers.
19163        if (pkgList.size() > 0) {
19164            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19165                    new IIntentReceiver.Stub() {
19166                public void performReceive(Intent intent, int resultCode, String data,
19167                        Bundle extras, boolean ordered, boolean sticky,
19168                        int sendingUser) throws RemoteException {
19169                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19170                            reportStatus ? 1 : 0, 1, keys);
19171                    mHandler.sendMessage(msg);
19172                }
19173            });
19174        } else {
19175            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19176                    keys);
19177            mHandler.sendMessage(msg);
19178        }
19179    }
19180
19181    private void loadPrivatePackages(final VolumeInfo vol) {
19182        mHandler.post(new Runnable() {
19183            @Override
19184            public void run() {
19185                loadPrivatePackagesInner(vol);
19186            }
19187        });
19188    }
19189
19190    private void loadPrivatePackagesInner(VolumeInfo vol) {
19191        final String volumeUuid = vol.fsUuid;
19192        if (TextUtils.isEmpty(volumeUuid)) {
19193            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19194            return;
19195        }
19196
19197        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19198        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19199        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19200
19201        final VersionInfo ver;
19202        final List<PackageSetting> packages;
19203        synchronized (mPackages) {
19204            ver = mSettings.findOrCreateVersion(volumeUuid);
19205            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19206        }
19207
19208        for (PackageSetting ps : packages) {
19209            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19210            synchronized (mInstallLock) {
19211                final PackageParser.Package pkg;
19212                try {
19213                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19214                    loaded.add(pkg.applicationInfo);
19215
19216                } catch (PackageManagerException e) {
19217                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19218                }
19219
19220                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19221                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19222                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19223                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19224                }
19225            }
19226        }
19227
19228        // Reconcile app data for all started/unlocked users
19229        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19230        final UserManager um = mContext.getSystemService(UserManager.class);
19231        UserManagerInternal umInternal = getUserManagerInternal();
19232        for (UserInfo user : um.getUsers()) {
19233            final int flags;
19234            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19235                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19236            } else if (umInternal.isUserRunning(user.id)) {
19237                flags = StorageManager.FLAG_STORAGE_DE;
19238            } else {
19239                continue;
19240            }
19241
19242            try {
19243                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19244                synchronized (mInstallLock) {
19245                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19246                }
19247            } catch (IllegalStateException e) {
19248                // Device was probably ejected, and we'll process that event momentarily
19249                Slog.w(TAG, "Failed to prepare storage: " + e);
19250            }
19251        }
19252
19253        synchronized (mPackages) {
19254            int updateFlags = UPDATE_PERMISSIONS_ALL;
19255            if (ver.sdkVersion != mSdkVersion) {
19256                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19257                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19258                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19259            }
19260            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19261
19262            // Yay, everything is now upgraded
19263            ver.forceCurrent();
19264
19265            mSettings.writeLPr();
19266        }
19267
19268        for (PackageFreezer freezer : freezers) {
19269            freezer.close();
19270        }
19271
19272        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19273        sendResourcesChangedBroadcast(true, false, loaded, null);
19274    }
19275
19276    private void unloadPrivatePackages(final VolumeInfo vol) {
19277        mHandler.post(new Runnable() {
19278            @Override
19279            public void run() {
19280                unloadPrivatePackagesInner(vol);
19281            }
19282        });
19283    }
19284
19285    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19286        final String volumeUuid = vol.fsUuid;
19287        if (TextUtils.isEmpty(volumeUuid)) {
19288            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19289            return;
19290        }
19291
19292        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19293        synchronized (mInstallLock) {
19294        synchronized (mPackages) {
19295            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19296            for (PackageSetting ps : packages) {
19297                if (ps.pkg == null) continue;
19298
19299                final ApplicationInfo info = ps.pkg.applicationInfo;
19300                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19301                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19302
19303                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19304                        "unloadPrivatePackagesInner")) {
19305                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19306                            false, null)) {
19307                        unloaded.add(info);
19308                    } else {
19309                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19310                    }
19311                }
19312
19313                // Try very hard to release any references to this package
19314                // so we don't risk the system server being killed due to
19315                // open FDs
19316                AttributeCache.instance().removePackage(ps.name);
19317            }
19318
19319            mSettings.writeLPr();
19320        }
19321        }
19322
19323        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19324        sendResourcesChangedBroadcast(false, false, unloaded, null);
19325
19326        // Try very hard to release any references to this path so we don't risk
19327        // the system server being killed due to open FDs
19328        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19329
19330        for (int i = 0; i < 3; i++) {
19331            System.gc();
19332            System.runFinalization();
19333        }
19334    }
19335
19336    /**
19337     * Prepare storage areas for given user on all mounted devices.
19338     */
19339    void prepareUserData(int userId, int userSerial, int flags) {
19340        synchronized (mInstallLock) {
19341            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19342            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19343                final String volumeUuid = vol.getFsUuid();
19344                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19345            }
19346        }
19347    }
19348
19349    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19350            boolean allowRecover) {
19351        // Prepare storage and verify that serial numbers are consistent; if
19352        // there's a mismatch we need to destroy to avoid leaking data
19353        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19354        try {
19355            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19356
19357            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19358                UserManagerService.enforceSerialNumber(
19359                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19360                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19361                    UserManagerService.enforceSerialNumber(
19362                            Environment.getDataSystemDeDirectory(userId), userSerial);
19363                }
19364            }
19365            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19366                UserManagerService.enforceSerialNumber(
19367                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19368                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19369                    UserManagerService.enforceSerialNumber(
19370                            Environment.getDataSystemCeDirectory(userId), userSerial);
19371                }
19372            }
19373
19374            synchronized (mInstallLock) {
19375                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19376            }
19377        } catch (Exception e) {
19378            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19379                    + " because we failed to prepare: " + e);
19380            destroyUserDataLI(volumeUuid, userId,
19381                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19382
19383            if (allowRecover) {
19384                // Try one last time; if we fail again we're really in trouble
19385                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19386            }
19387        }
19388    }
19389
19390    /**
19391     * Destroy storage areas for given user on all mounted devices.
19392     */
19393    void destroyUserData(int userId, int flags) {
19394        synchronized (mInstallLock) {
19395            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19396            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19397                final String volumeUuid = vol.getFsUuid();
19398                destroyUserDataLI(volumeUuid, userId, flags);
19399            }
19400        }
19401    }
19402
19403    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19404        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19405        try {
19406            // Clean up app data, profile data, and media data
19407            mInstaller.destroyUserData(volumeUuid, userId, flags);
19408
19409            // Clean up system data
19410            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19411                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19412                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19413                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19414                }
19415                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19416                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19417                }
19418            }
19419
19420            // Data with special labels is now gone, so finish the job
19421            storage.destroyUserStorage(volumeUuid, userId, flags);
19422
19423        } catch (Exception e) {
19424            logCriticalInfo(Log.WARN,
19425                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19426        }
19427    }
19428
19429    /**
19430     * Examine all users present on given mounted volume, and destroy data
19431     * belonging to users that are no longer valid, or whose user ID has been
19432     * recycled.
19433     */
19434    private void reconcileUsers(String volumeUuid) {
19435        final List<File> files = new ArrayList<>();
19436        Collections.addAll(files, FileUtils
19437                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19438        Collections.addAll(files, FileUtils
19439                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19440        Collections.addAll(files, FileUtils
19441                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19442        Collections.addAll(files, FileUtils
19443                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19444        for (File file : files) {
19445            if (!file.isDirectory()) continue;
19446
19447            final int userId;
19448            final UserInfo info;
19449            try {
19450                userId = Integer.parseInt(file.getName());
19451                info = sUserManager.getUserInfo(userId);
19452            } catch (NumberFormatException e) {
19453                Slog.w(TAG, "Invalid user directory " + file);
19454                continue;
19455            }
19456
19457            boolean destroyUser = false;
19458            if (info == null) {
19459                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19460                        + " because no matching user was found");
19461                destroyUser = true;
19462            } else if (!mOnlyCore) {
19463                try {
19464                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19465                } catch (IOException e) {
19466                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19467                            + " because we failed to enforce serial number: " + e);
19468                    destroyUser = true;
19469                }
19470            }
19471
19472            if (destroyUser) {
19473                synchronized (mInstallLock) {
19474                    destroyUserDataLI(volumeUuid, userId,
19475                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19476                }
19477            }
19478        }
19479    }
19480
19481    private void assertPackageKnown(String volumeUuid, String packageName)
19482            throws PackageManagerException {
19483        synchronized (mPackages) {
19484            final PackageSetting ps = mSettings.mPackages.get(packageName);
19485            if (ps == null) {
19486                throw new PackageManagerException("Package " + packageName + " is unknown");
19487            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19488                throw new PackageManagerException(
19489                        "Package " + packageName + " found on unknown volume " + volumeUuid
19490                                + "; expected volume " + ps.volumeUuid);
19491            }
19492        }
19493    }
19494
19495    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19496            throws PackageManagerException {
19497        synchronized (mPackages) {
19498            final PackageSetting ps = mSettings.mPackages.get(packageName);
19499            if (ps == null) {
19500                throw new PackageManagerException("Package " + packageName + " is unknown");
19501            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19502                throw new PackageManagerException(
19503                        "Package " + packageName + " found on unknown volume " + volumeUuid
19504                                + "; expected volume " + ps.volumeUuid);
19505            } else if (!ps.getInstalled(userId)) {
19506                throw new PackageManagerException(
19507                        "Package " + packageName + " not installed for user " + userId);
19508            }
19509        }
19510    }
19511
19512    /**
19513     * Examine all apps present on given mounted volume, and destroy apps that
19514     * aren't expected, either due to uninstallation or reinstallation on
19515     * another volume.
19516     */
19517    private void reconcileApps(String volumeUuid) {
19518        final File[] files = FileUtils
19519                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19520        for (File file : files) {
19521            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19522                    && !PackageInstallerService.isStageName(file.getName());
19523            if (!isPackage) {
19524                // Ignore entries which are not packages
19525                continue;
19526            }
19527
19528            try {
19529                final PackageLite pkg = PackageParser.parsePackageLite(file,
19530                        PackageParser.PARSE_MUST_BE_APK);
19531                assertPackageKnown(volumeUuid, pkg.packageName);
19532
19533            } catch (PackageParserException | PackageManagerException e) {
19534                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19535                synchronized (mInstallLock) {
19536                    removeCodePathLI(file);
19537                }
19538            }
19539        }
19540    }
19541
19542    /**
19543     * Reconcile all app data for the given user.
19544     * <p>
19545     * Verifies that directories exist and that ownership and labeling is
19546     * correct for all installed apps on all mounted volumes.
19547     */
19548    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19549        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19550        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19551            final String volumeUuid = vol.getFsUuid();
19552            synchronized (mInstallLock) {
19553                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19554            }
19555        }
19556    }
19557
19558    /**
19559     * Reconcile all app data on given mounted volume.
19560     * <p>
19561     * Destroys app data that isn't expected, either due to uninstallation or
19562     * reinstallation on another volume.
19563     * <p>
19564     * Verifies that directories exist and that ownership and labeling is
19565     * correct for all installed apps.
19566     */
19567    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19568            boolean migrateAppData) {
19569        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19570                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19571
19572        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19573        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19574
19575        boolean restoreconNeeded = false;
19576
19577        // First look for stale data that doesn't belong, and check if things
19578        // have changed since we did our last restorecon
19579        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19580            if (StorageManager.isFileEncryptedNativeOrEmulated()
19581                    && !StorageManager.isUserKeyUnlocked(userId)) {
19582                throw new RuntimeException(
19583                        "Yikes, someone asked us to reconcile CE storage while " + userId
19584                                + " was still locked; this would have caused massive data loss!");
19585            }
19586
19587            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19588
19589            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19590            for (File file : files) {
19591                final String packageName = file.getName();
19592                try {
19593                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19594                } catch (PackageManagerException e) {
19595                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19596                    try {
19597                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19598                                StorageManager.FLAG_STORAGE_CE, 0);
19599                    } catch (InstallerException e2) {
19600                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19601                    }
19602                }
19603            }
19604        }
19605        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19606            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19607
19608            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19609            for (File file : files) {
19610                final String packageName = file.getName();
19611                try {
19612                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19613                } catch (PackageManagerException e) {
19614                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19615                    try {
19616                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19617                                StorageManager.FLAG_STORAGE_DE, 0);
19618                    } catch (InstallerException e2) {
19619                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19620                    }
19621                }
19622            }
19623        }
19624
19625        // Ensure that data directories are ready to roll for all packages
19626        // installed for this volume and user
19627        final List<PackageSetting> packages;
19628        synchronized (mPackages) {
19629            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19630        }
19631        int preparedCount = 0;
19632        for (PackageSetting ps : packages) {
19633            final String packageName = ps.name;
19634            if (ps.pkg == null) {
19635                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19636                // TODO: might be due to legacy ASEC apps; we should circle back
19637                // and reconcile again once they're scanned
19638                continue;
19639            }
19640
19641            if (ps.getInstalled(userId)) {
19642                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19643
19644                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
19645                    // We may have just shuffled around app data directories, so
19646                    // prepare them one more time
19647                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19648                }
19649
19650                preparedCount++;
19651            }
19652        }
19653
19654        if (restoreconNeeded) {
19655            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19656                SELinuxMMAC.setRestoreconDone(ceDir);
19657            }
19658            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19659                SELinuxMMAC.setRestoreconDone(deDir);
19660            }
19661        }
19662
19663        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19664                + " packages; restoreconNeeded was " + restoreconNeeded);
19665    }
19666
19667    /**
19668     * Prepare app data for the given app just after it was installed or
19669     * upgraded. This method carefully only touches users that it's installed
19670     * for, and it forces a restorecon to handle any seinfo changes.
19671     * <p>
19672     * Verifies that directories exist and that ownership and labeling is
19673     * correct for all installed apps. If there is an ownership mismatch, it
19674     * will try recovering system apps by wiping data; third-party app data is
19675     * left intact.
19676     * <p>
19677     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19678     */
19679    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19680        final PackageSetting ps;
19681        synchronized (mPackages) {
19682            ps = mSettings.mPackages.get(pkg.packageName);
19683            mSettings.writeKernelMappingLPr(ps);
19684        }
19685
19686        final UserManager um = mContext.getSystemService(UserManager.class);
19687        UserManagerInternal umInternal = getUserManagerInternal();
19688        for (UserInfo user : um.getUsers()) {
19689            final int flags;
19690            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19691                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19692            } else if (umInternal.isUserRunning(user.id)) {
19693                flags = StorageManager.FLAG_STORAGE_DE;
19694            } else {
19695                continue;
19696            }
19697
19698            if (ps.getInstalled(user.id)) {
19699                // Whenever an app changes, force a restorecon of its data
19700                // TODO: when user data is locked, mark that we're still dirty
19701                prepareAppDataLIF(pkg, user.id, flags, true);
19702            }
19703        }
19704    }
19705
19706    /**
19707     * Prepare app data for the given app.
19708     * <p>
19709     * Verifies that directories exist and that ownership and labeling is
19710     * correct for all installed apps. If there is an ownership mismatch, this
19711     * will try recovering system apps by wiping data; third-party app data is
19712     * left intact.
19713     */
19714    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19715            boolean restoreconNeeded) {
19716        if (pkg == null) {
19717            Slog.wtf(TAG, "Package was null!", new Throwable());
19718            return;
19719        }
19720        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19721        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19722        for (int i = 0; i < childCount; i++) {
19723            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19724        }
19725    }
19726
19727    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19728            boolean restoreconNeeded) {
19729        if (DEBUG_APP_DATA) {
19730            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19731                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19732        }
19733
19734        final String volumeUuid = pkg.volumeUuid;
19735        final String packageName = pkg.packageName;
19736        final ApplicationInfo app = pkg.applicationInfo;
19737        final int appId = UserHandle.getAppId(app.uid);
19738
19739        Preconditions.checkNotNull(app.seinfo);
19740
19741        try {
19742            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19743                    appId, app.seinfo, app.targetSdkVersion);
19744        } catch (InstallerException e) {
19745            if (app.isSystemApp()) {
19746                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19747                        + ", but trying to recover: " + e);
19748                destroyAppDataLeafLIF(pkg, userId, flags);
19749                try {
19750                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19751                            appId, app.seinfo, app.targetSdkVersion);
19752                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19753                } catch (InstallerException e2) {
19754                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19755                }
19756            } else {
19757                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19758            }
19759        }
19760
19761        if (restoreconNeeded) {
19762            try {
19763                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19764                        app.seinfo);
19765            } catch (InstallerException e) {
19766                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19767            }
19768        }
19769
19770        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19771            try {
19772                // CE storage is unlocked right now, so read out the inode and
19773                // remember for use later when it's locked
19774                // TODO: mark this structure as dirty so we persist it!
19775                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19776                        StorageManager.FLAG_STORAGE_CE);
19777                synchronized (mPackages) {
19778                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19779                    if (ps != null) {
19780                        ps.setCeDataInode(ceDataInode, userId);
19781                    }
19782                }
19783            } catch (InstallerException e) {
19784                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19785            }
19786        }
19787
19788        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19789    }
19790
19791    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19792        if (pkg == null) {
19793            Slog.wtf(TAG, "Package was null!", new Throwable());
19794            return;
19795        }
19796        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19797        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19798        for (int i = 0; i < childCount; i++) {
19799            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19800        }
19801    }
19802
19803    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19804        final String volumeUuid = pkg.volumeUuid;
19805        final String packageName = pkg.packageName;
19806        final ApplicationInfo app = pkg.applicationInfo;
19807
19808        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19809            // Create a native library symlink only if we have native libraries
19810            // and if the native libraries are 32 bit libraries. We do not provide
19811            // this symlink for 64 bit libraries.
19812            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19813                final String nativeLibPath = app.nativeLibraryDir;
19814                try {
19815                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19816                            nativeLibPath, userId);
19817                } catch (InstallerException e) {
19818                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19819                }
19820            }
19821        }
19822    }
19823
19824    /**
19825     * For system apps on non-FBE devices, this method migrates any existing
19826     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19827     * requested by the app.
19828     */
19829    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19830        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19831                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19832            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19833                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19834            try {
19835                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19836                        storageTarget);
19837            } catch (InstallerException e) {
19838                logCriticalInfo(Log.WARN,
19839                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19840            }
19841            return true;
19842        } else {
19843            return false;
19844        }
19845    }
19846
19847    public PackageFreezer freezePackage(String packageName, String killReason) {
19848        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19849    }
19850
19851    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19852        return new PackageFreezer(packageName, userId, killReason);
19853    }
19854
19855    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19856            String killReason) {
19857        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19858    }
19859
19860    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19861            String killReason) {
19862        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19863            return new PackageFreezer();
19864        } else {
19865            return freezePackage(packageName, userId, killReason);
19866        }
19867    }
19868
19869    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19870            String killReason) {
19871        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19872    }
19873
19874    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19875            String killReason) {
19876        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19877            return new PackageFreezer();
19878        } else {
19879            return freezePackage(packageName, userId, killReason);
19880        }
19881    }
19882
19883    /**
19884     * Class that freezes and kills the given package upon creation, and
19885     * unfreezes it upon closing. This is typically used when doing surgery on
19886     * app code/data to prevent the app from running while you're working.
19887     */
19888    private class PackageFreezer implements AutoCloseable {
19889        private final String mPackageName;
19890        private final PackageFreezer[] mChildren;
19891
19892        private final boolean mWeFroze;
19893
19894        private final AtomicBoolean mClosed = new AtomicBoolean();
19895        private final CloseGuard mCloseGuard = CloseGuard.get();
19896
19897        /**
19898         * Create and return a stub freezer that doesn't actually do anything,
19899         * typically used when someone requested
19900         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19901         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19902         */
19903        public PackageFreezer() {
19904            mPackageName = null;
19905            mChildren = null;
19906            mWeFroze = false;
19907            mCloseGuard.open("close");
19908        }
19909
19910        public PackageFreezer(String packageName, int userId, String killReason) {
19911            synchronized (mPackages) {
19912                mPackageName = packageName;
19913                mWeFroze = mFrozenPackages.add(mPackageName);
19914
19915                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19916                if (ps != null) {
19917                    killApplication(ps.name, ps.appId, userId, killReason);
19918                }
19919
19920                final PackageParser.Package p = mPackages.get(packageName);
19921                if (p != null && p.childPackages != null) {
19922                    final int N = p.childPackages.size();
19923                    mChildren = new PackageFreezer[N];
19924                    for (int i = 0; i < N; i++) {
19925                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19926                                userId, killReason);
19927                    }
19928                } else {
19929                    mChildren = null;
19930                }
19931            }
19932            mCloseGuard.open("close");
19933        }
19934
19935        @Override
19936        protected void finalize() throws Throwable {
19937            try {
19938                mCloseGuard.warnIfOpen();
19939                close();
19940            } finally {
19941                super.finalize();
19942            }
19943        }
19944
19945        @Override
19946        public void close() {
19947            mCloseGuard.close();
19948            if (mClosed.compareAndSet(false, true)) {
19949                synchronized (mPackages) {
19950                    if (mWeFroze) {
19951                        mFrozenPackages.remove(mPackageName);
19952                    }
19953
19954                    if (mChildren != null) {
19955                        for (PackageFreezer freezer : mChildren) {
19956                            freezer.close();
19957                        }
19958                    }
19959                }
19960            }
19961        }
19962    }
19963
19964    /**
19965     * Verify that given package is currently frozen.
19966     */
19967    private void checkPackageFrozen(String packageName) {
19968        synchronized (mPackages) {
19969            if (!mFrozenPackages.contains(packageName)) {
19970                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19971            }
19972        }
19973    }
19974
19975    @Override
19976    public int movePackage(final String packageName, final String volumeUuid) {
19977        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19978
19979        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19980        final int moveId = mNextMoveId.getAndIncrement();
19981        mHandler.post(new Runnable() {
19982            @Override
19983            public void run() {
19984                try {
19985                    movePackageInternal(packageName, volumeUuid, moveId, user);
19986                } catch (PackageManagerException e) {
19987                    Slog.w(TAG, "Failed to move " + packageName, e);
19988                    mMoveCallbacks.notifyStatusChanged(moveId,
19989                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19990                }
19991            }
19992        });
19993        return moveId;
19994    }
19995
19996    private void movePackageInternal(final String packageName, final String volumeUuid,
19997            final int moveId, UserHandle user) throws PackageManagerException {
19998        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19999        final PackageManager pm = mContext.getPackageManager();
20000
20001        final boolean currentAsec;
20002        final String currentVolumeUuid;
20003        final File codeFile;
20004        final String installerPackageName;
20005        final String packageAbiOverride;
20006        final int appId;
20007        final String seinfo;
20008        final String label;
20009        final int targetSdkVersion;
20010        final PackageFreezer freezer;
20011        final int[] installedUserIds;
20012
20013        // reader
20014        synchronized (mPackages) {
20015            final PackageParser.Package pkg = mPackages.get(packageName);
20016            final PackageSetting ps = mSettings.mPackages.get(packageName);
20017            if (pkg == null || ps == null) {
20018                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20019            }
20020
20021            if (pkg.applicationInfo.isSystemApp()) {
20022                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20023                        "Cannot move system application");
20024            }
20025
20026            if (pkg.applicationInfo.isExternalAsec()) {
20027                currentAsec = true;
20028                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20029            } else if (pkg.applicationInfo.isForwardLocked()) {
20030                currentAsec = true;
20031                currentVolumeUuid = "forward_locked";
20032            } else {
20033                currentAsec = false;
20034                currentVolumeUuid = ps.volumeUuid;
20035
20036                final File probe = new File(pkg.codePath);
20037                final File probeOat = new File(probe, "oat");
20038                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20039                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20040                            "Move only supported for modern cluster style installs");
20041                }
20042            }
20043
20044            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20045                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20046                        "Package already moved to " + volumeUuid);
20047            }
20048            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20049                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20050                        "Device admin cannot be moved");
20051            }
20052
20053            if (mFrozenPackages.contains(packageName)) {
20054                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20055                        "Failed to move already frozen package");
20056            }
20057
20058            codeFile = new File(pkg.codePath);
20059            installerPackageName = ps.installerPackageName;
20060            packageAbiOverride = ps.cpuAbiOverrideString;
20061            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20062            seinfo = pkg.applicationInfo.seinfo;
20063            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20064            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20065            freezer = freezePackage(packageName, "movePackageInternal");
20066            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20067        }
20068
20069        final Bundle extras = new Bundle();
20070        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20071        extras.putString(Intent.EXTRA_TITLE, label);
20072        mMoveCallbacks.notifyCreated(moveId, extras);
20073
20074        int installFlags;
20075        final boolean moveCompleteApp;
20076        final File measurePath;
20077
20078        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20079            installFlags = INSTALL_INTERNAL;
20080            moveCompleteApp = !currentAsec;
20081            measurePath = Environment.getDataAppDirectory(volumeUuid);
20082        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20083            installFlags = INSTALL_EXTERNAL;
20084            moveCompleteApp = false;
20085            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20086        } else {
20087            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20088            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20089                    || !volume.isMountedWritable()) {
20090                freezer.close();
20091                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20092                        "Move location not mounted private volume");
20093            }
20094
20095            Preconditions.checkState(!currentAsec);
20096
20097            installFlags = INSTALL_INTERNAL;
20098            moveCompleteApp = true;
20099            measurePath = Environment.getDataAppDirectory(volumeUuid);
20100        }
20101
20102        final PackageStats stats = new PackageStats(null, -1);
20103        synchronized (mInstaller) {
20104            for (int userId : installedUserIds) {
20105                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20106                    freezer.close();
20107                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20108                            "Failed to measure package size");
20109                }
20110            }
20111        }
20112
20113        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20114                + stats.dataSize);
20115
20116        final long startFreeBytes = measurePath.getFreeSpace();
20117        final long sizeBytes;
20118        if (moveCompleteApp) {
20119            sizeBytes = stats.codeSize + stats.dataSize;
20120        } else {
20121            sizeBytes = stats.codeSize;
20122        }
20123
20124        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20125            freezer.close();
20126            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20127                    "Not enough free space to move");
20128        }
20129
20130        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20131
20132        final CountDownLatch installedLatch = new CountDownLatch(1);
20133        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20134            @Override
20135            public void onUserActionRequired(Intent intent) throws RemoteException {
20136                throw new IllegalStateException();
20137            }
20138
20139            @Override
20140            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20141                    Bundle extras) throws RemoteException {
20142                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20143                        + PackageManager.installStatusToString(returnCode, msg));
20144
20145                installedLatch.countDown();
20146                freezer.close();
20147
20148                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20149                switch (status) {
20150                    case PackageInstaller.STATUS_SUCCESS:
20151                        mMoveCallbacks.notifyStatusChanged(moveId,
20152                                PackageManager.MOVE_SUCCEEDED);
20153                        break;
20154                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20155                        mMoveCallbacks.notifyStatusChanged(moveId,
20156                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20157                        break;
20158                    default:
20159                        mMoveCallbacks.notifyStatusChanged(moveId,
20160                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20161                        break;
20162                }
20163            }
20164        };
20165
20166        final MoveInfo move;
20167        if (moveCompleteApp) {
20168            // Kick off a thread to report progress estimates
20169            new Thread() {
20170                @Override
20171                public void run() {
20172                    while (true) {
20173                        try {
20174                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20175                                break;
20176                            }
20177                        } catch (InterruptedException ignored) {
20178                        }
20179
20180                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20181                        final int progress = 10 + (int) MathUtils.constrain(
20182                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20183                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20184                    }
20185                }
20186            }.start();
20187
20188            final String dataAppName = codeFile.getName();
20189            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20190                    dataAppName, appId, seinfo, targetSdkVersion);
20191        } else {
20192            move = null;
20193        }
20194
20195        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20196
20197        final Message msg = mHandler.obtainMessage(INIT_COPY);
20198        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20199        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20200                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20201                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20202        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20203        msg.obj = params;
20204
20205        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20206                System.identityHashCode(msg.obj));
20207        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20208                System.identityHashCode(msg.obj));
20209
20210        mHandler.sendMessage(msg);
20211    }
20212
20213    @Override
20214    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20215        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20216
20217        final int realMoveId = mNextMoveId.getAndIncrement();
20218        final Bundle extras = new Bundle();
20219        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20220        mMoveCallbacks.notifyCreated(realMoveId, extras);
20221
20222        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20223            @Override
20224            public void onCreated(int moveId, Bundle extras) {
20225                // Ignored
20226            }
20227
20228            @Override
20229            public void onStatusChanged(int moveId, int status, long estMillis) {
20230                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20231            }
20232        };
20233
20234        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20235        storage.setPrimaryStorageUuid(volumeUuid, callback);
20236        return realMoveId;
20237    }
20238
20239    @Override
20240    public int getMoveStatus(int moveId) {
20241        mContext.enforceCallingOrSelfPermission(
20242                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20243        return mMoveCallbacks.mLastStatus.get(moveId);
20244    }
20245
20246    @Override
20247    public void registerMoveCallback(IPackageMoveObserver callback) {
20248        mContext.enforceCallingOrSelfPermission(
20249                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20250        mMoveCallbacks.register(callback);
20251    }
20252
20253    @Override
20254    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20255        mContext.enforceCallingOrSelfPermission(
20256                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20257        mMoveCallbacks.unregister(callback);
20258    }
20259
20260    @Override
20261    public boolean setInstallLocation(int loc) {
20262        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20263                null);
20264        if (getInstallLocation() == loc) {
20265            return true;
20266        }
20267        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20268                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20269            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20270                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20271            return true;
20272        }
20273        return false;
20274   }
20275
20276    @Override
20277    public int getInstallLocation() {
20278        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20279                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20280                PackageHelper.APP_INSTALL_AUTO);
20281    }
20282
20283    /** Called by UserManagerService */
20284    void cleanUpUser(UserManagerService userManager, int userHandle) {
20285        synchronized (mPackages) {
20286            mDirtyUsers.remove(userHandle);
20287            mUserNeedsBadging.delete(userHandle);
20288            mSettings.removeUserLPw(userHandle);
20289            mPendingBroadcasts.remove(userHandle);
20290            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20291            removeUnusedPackagesLPw(userManager, userHandle);
20292        }
20293    }
20294
20295    /**
20296     * We're removing userHandle and would like to remove any downloaded packages
20297     * that are no longer in use by any other user.
20298     * @param userHandle the user being removed
20299     */
20300    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20301        final boolean DEBUG_CLEAN_APKS = false;
20302        int [] users = userManager.getUserIds();
20303        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20304        while (psit.hasNext()) {
20305            PackageSetting ps = psit.next();
20306            if (ps.pkg == null) {
20307                continue;
20308            }
20309            final String packageName = ps.pkg.packageName;
20310            // Skip over if system app
20311            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20312                continue;
20313            }
20314            if (DEBUG_CLEAN_APKS) {
20315                Slog.i(TAG, "Checking package " + packageName);
20316            }
20317            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20318            if (keep) {
20319                if (DEBUG_CLEAN_APKS) {
20320                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20321                }
20322            } else {
20323                for (int i = 0; i < users.length; i++) {
20324                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20325                        keep = true;
20326                        if (DEBUG_CLEAN_APKS) {
20327                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20328                                    + users[i]);
20329                        }
20330                        break;
20331                    }
20332                }
20333            }
20334            if (!keep) {
20335                if (DEBUG_CLEAN_APKS) {
20336                    Slog.i(TAG, "  Removing package " + packageName);
20337                }
20338                mHandler.post(new Runnable() {
20339                    public void run() {
20340                        deletePackageX(packageName, userHandle, 0);
20341                    } //end run
20342                });
20343            }
20344        }
20345    }
20346
20347    /** Called by UserManagerService */
20348    void createNewUser(int userId) {
20349        synchronized (mInstallLock) {
20350            mSettings.createNewUserLI(this, mInstaller, userId);
20351        }
20352        synchronized (mPackages) {
20353            scheduleWritePackageRestrictionsLocked(userId);
20354            scheduleWritePackageListLocked(userId);
20355            applyFactoryDefaultBrowserLPw(userId);
20356            primeDomainVerificationsLPw(userId);
20357        }
20358    }
20359
20360    void onNewUserCreated(final int userId) {
20361        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20362        // If permission review for legacy apps is required, we represent
20363        // dagerous permissions for such apps as always granted runtime
20364        // permissions to keep per user flag state whether review is needed.
20365        // Hence, if a new user is added we have to propagate dangerous
20366        // permission grants for these legacy apps.
20367        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20368            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20369                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20370        }
20371    }
20372
20373    @Override
20374    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20375        mContext.enforceCallingOrSelfPermission(
20376                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20377                "Only package verification agents can read the verifier device identity");
20378
20379        synchronized (mPackages) {
20380            return mSettings.getVerifierDeviceIdentityLPw();
20381        }
20382    }
20383
20384    @Override
20385    public void setPermissionEnforced(String permission, boolean enforced) {
20386        // TODO: Now that we no longer change GID for storage, this should to away.
20387        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20388                "setPermissionEnforced");
20389        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20390            synchronized (mPackages) {
20391                if (mSettings.mReadExternalStorageEnforced == null
20392                        || mSettings.mReadExternalStorageEnforced != enforced) {
20393                    mSettings.mReadExternalStorageEnforced = enforced;
20394                    mSettings.writeLPr();
20395                }
20396            }
20397            // kill any non-foreground processes so we restart them and
20398            // grant/revoke the GID.
20399            final IActivityManager am = ActivityManagerNative.getDefault();
20400            if (am != null) {
20401                final long token = Binder.clearCallingIdentity();
20402                try {
20403                    am.killProcessesBelowForeground("setPermissionEnforcement");
20404                } catch (RemoteException e) {
20405                } finally {
20406                    Binder.restoreCallingIdentity(token);
20407                }
20408            }
20409        } else {
20410            throw new IllegalArgumentException("No selective enforcement for " + permission);
20411        }
20412    }
20413
20414    @Override
20415    @Deprecated
20416    public boolean isPermissionEnforced(String permission) {
20417        return true;
20418    }
20419
20420    @Override
20421    public boolean isStorageLow() {
20422        final long token = Binder.clearCallingIdentity();
20423        try {
20424            final DeviceStorageMonitorInternal
20425                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20426            if (dsm != null) {
20427                return dsm.isMemoryLow();
20428            } else {
20429                return false;
20430            }
20431        } finally {
20432            Binder.restoreCallingIdentity(token);
20433        }
20434    }
20435
20436    @Override
20437    public IPackageInstaller getPackageInstaller() {
20438        return mInstallerService;
20439    }
20440
20441    private boolean userNeedsBadging(int userId) {
20442        int index = mUserNeedsBadging.indexOfKey(userId);
20443        if (index < 0) {
20444            final UserInfo userInfo;
20445            final long token = Binder.clearCallingIdentity();
20446            try {
20447                userInfo = sUserManager.getUserInfo(userId);
20448            } finally {
20449                Binder.restoreCallingIdentity(token);
20450            }
20451            final boolean b;
20452            if (userInfo != null && userInfo.isManagedProfile()) {
20453                b = true;
20454            } else {
20455                b = false;
20456            }
20457            mUserNeedsBadging.put(userId, b);
20458            return b;
20459        }
20460        return mUserNeedsBadging.valueAt(index);
20461    }
20462
20463    @Override
20464    public KeySet getKeySetByAlias(String packageName, String alias) {
20465        if (packageName == null || alias == null) {
20466            return null;
20467        }
20468        synchronized(mPackages) {
20469            final PackageParser.Package pkg = mPackages.get(packageName);
20470            if (pkg == null) {
20471                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20472                throw new IllegalArgumentException("Unknown package: " + packageName);
20473            }
20474            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20475            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20476        }
20477    }
20478
20479    @Override
20480    public KeySet getSigningKeySet(String packageName) {
20481        if (packageName == null) {
20482            return null;
20483        }
20484        synchronized(mPackages) {
20485            final PackageParser.Package pkg = mPackages.get(packageName);
20486            if (pkg == null) {
20487                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20488                throw new IllegalArgumentException("Unknown package: " + packageName);
20489            }
20490            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20491                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20492                throw new SecurityException("May not access signing KeySet of other apps.");
20493            }
20494            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20495            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20496        }
20497    }
20498
20499    @Override
20500    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20501        if (packageName == null || ks == null) {
20502            return false;
20503        }
20504        synchronized(mPackages) {
20505            final PackageParser.Package pkg = mPackages.get(packageName);
20506            if (pkg == null) {
20507                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20508                throw new IllegalArgumentException("Unknown package: " + packageName);
20509            }
20510            IBinder ksh = ks.getToken();
20511            if (ksh instanceof KeySetHandle) {
20512                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20513                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20514            }
20515            return false;
20516        }
20517    }
20518
20519    @Override
20520    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20521        if (packageName == null || ks == null) {
20522            return false;
20523        }
20524        synchronized(mPackages) {
20525            final PackageParser.Package pkg = mPackages.get(packageName);
20526            if (pkg == null) {
20527                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20528                throw new IllegalArgumentException("Unknown package: " + packageName);
20529            }
20530            IBinder ksh = ks.getToken();
20531            if (ksh instanceof KeySetHandle) {
20532                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20533                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20534            }
20535            return false;
20536        }
20537    }
20538
20539    private void deletePackageIfUnusedLPr(final String packageName) {
20540        PackageSetting ps = mSettings.mPackages.get(packageName);
20541        if (ps == null) {
20542            return;
20543        }
20544        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20545            // TODO Implement atomic delete if package is unused
20546            // It is currently possible that the package will be deleted even if it is installed
20547            // after this method returns.
20548            mHandler.post(new Runnable() {
20549                public void run() {
20550                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20551                }
20552            });
20553        }
20554    }
20555
20556    /**
20557     * Check and throw if the given before/after packages would be considered a
20558     * downgrade.
20559     */
20560    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20561            throws PackageManagerException {
20562        if (after.versionCode < before.mVersionCode) {
20563            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20564                    "Update version code " + after.versionCode + " is older than current "
20565                    + before.mVersionCode);
20566        } else if (after.versionCode == before.mVersionCode) {
20567            if (after.baseRevisionCode < before.baseRevisionCode) {
20568                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20569                        "Update base revision code " + after.baseRevisionCode
20570                        + " is older than current " + before.baseRevisionCode);
20571            }
20572
20573            if (!ArrayUtils.isEmpty(after.splitNames)) {
20574                for (int i = 0; i < after.splitNames.length; i++) {
20575                    final String splitName = after.splitNames[i];
20576                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20577                    if (j != -1) {
20578                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20579                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20580                                    "Update split " + splitName + " revision code "
20581                                    + after.splitRevisionCodes[i] + " is older than current "
20582                                    + before.splitRevisionCodes[j]);
20583                        }
20584                    }
20585                }
20586            }
20587        }
20588    }
20589
20590    private static class MoveCallbacks extends Handler {
20591        private static final int MSG_CREATED = 1;
20592        private static final int MSG_STATUS_CHANGED = 2;
20593
20594        private final RemoteCallbackList<IPackageMoveObserver>
20595                mCallbacks = new RemoteCallbackList<>();
20596
20597        private final SparseIntArray mLastStatus = new SparseIntArray();
20598
20599        public MoveCallbacks(Looper looper) {
20600            super(looper);
20601        }
20602
20603        public void register(IPackageMoveObserver callback) {
20604            mCallbacks.register(callback);
20605        }
20606
20607        public void unregister(IPackageMoveObserver callback) {
20608            mCallbacks.unregister(callback);
20609        }
20610
20611        @Override
20612        public void handleMessage(Message msg) {
20613            final SomeArgs args = (SomeArgs) msg.obj;
20614            final int n = mCallbacks.beginBroadcast();
20615            for (int i = 0; i < n; i++) {
20616                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20617                try {
20618                    invokeCallback(callback, msg.what, args);
20619                } catch (RemoteException ignored) {
20620                }
20621            }
20622            mCallbacks.finishBroadcast();
20623            args.recycle();
20624        }
20625
20626        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20627                throws RemoteException {
20628            switch (what) {
20629                case MSG_CREATED: {
20630                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20631                    break;
20632                }
20633                case MSG_STATUS_CHANGED: {
20634                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20635                    break;
20636                }
20637            }
20638        }
20639
20640        private void notifyCreated(int moveId, Bundle extras) {
20641            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20642
20643            final SomeArgs args = SomeArgs.obtain();
20644            args.argi1 = moveId;
20645            args.arg2 = extras;
20646            obtainMessage(MSG_CREATED, args).sendToTarget();
20647        }
20648
20649        private void notifyStatusChanged(int moveId, int status) {
20650            notifyStatusChanged(moveId, status, -1);
20651        }
20652
20653        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20654            Slog.v(TAG, "Move " + moveId + " status " + status);
20655
20656            final SomeArgs args = SomeArgs.obtain();
20657            args.argi1 = moveId;
20658            args.argi2 = status;
20659            args.arg3 = estMillis;
20660            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20661
20662            synchronized (mLastStatus) {
20663                mLastStatus.put(moveId, status);
20664            }
20665        }
20666    }
20667
20668    private final static class OnPermissionChangeListeners extends Handler {
20669        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20670
20671        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20672                new RemoteCallbackList<>();
20673
20674        public OnPermissionChangeListeners(Looper looper) {
20675            super(looper);
20676        }
20677
20678        @Override
20679        public void handleMessage(Message msg) {
20680            switch (msg.what) {
20681                case MSG_ON_PERMISSIONS_CHANGED: {
20682                    final int uid = msg.arg1;
20683                    handleOnPermissionsChanged(uid);
20684                } break;
20685            }
20686        }
20687
20688        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20689            mPermissionListeners.register(listener);
20690
20691        }
20692
20693        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20694            mPermissionListeners.unregister(listener);
20695        }
20696
20697        public void onPermissionsChanged(int uid) {
20698            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20699                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20700            }
20701        }
20702
20703        private void handleOnPermissionsChanged(int uid) {
20704            final int count = mPermissionListeners.beginBroadcast();
20705            try {
20706                for (int i = 0; i < count; i++) {
20707                    IOnPermissionsChangeListener callback = mPermissionListeners
20708                            .getBroadcastItem(i);
20709                    try {
20710                        callback.onPermissionsChanged(uid);
20711                    } catch (RemoteException e) {
20712                        Log.e(TAG, "Permission listener is dead", e);
20713                    }
20714                }
20715            } finally {
20716                mPermissionListeners.finishBroadcast();
20717            }
20718        }
20719    }
20720
20721    private class PackageManagerInternalImpl extends PackageManagerInternal {
20722        @Override
20723        public void setLocationPackagesProvider(PackagesProvider provider) {
20724            synchronized (mPackages) {
20725                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20726            }
20727        }
20728
20729        @Override
20730        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20731            synchronized (mPackages) {
20732                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20733            }
20734        }
20735
20736        @Override
20737        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20738            synchronized (mPackages) {
20739                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20740            }
20741        }
20742
20743        @Override
20744        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20745            synchronized (mPackages) {
20746                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20747            }
20748        }
20749
20750        @Override
20751        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20752            synchronized (mPackages) {
20753                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20754            }
20755        }
20756
20757        @Override
20758        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20759            synchronized (mPackages) {
20760                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20761            }
20762        }
20763
20764        @Override
20765        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20766            synchronized (mPackages) {
20767                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20768                        packageName, userId);
20769            }
20770        }
20771
20772        @Override
20773        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20774            synchronized (mPackages) {
20775                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20776                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20777                        packageName, userId);
20778            }
20779        }
20780
20781        @Override
20782        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20783            synchronized (mPackages) {
20784                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20785                        packageName, userId);
20786            }
20787        }
20788
20789        @Override
20790        public void setKeepUninstalledPackages(final List<String> packageList) {
20791            Preconditions.checkNotNull(packageList);
20792            List<String> removedFromList = null;
20793            synchronized (mPackages) {
20794                if (mKeepUninstalledPackages != null) {
20795                    final int packagesCount = mKeepUninstalledPackages.size();
20796                    for (int i = 0; i < packagesCount; i++) {
20797                        String oldPackage = mKeepUninstalledPackages.get(i);
20798                        if (packageList != null && packageList.contains(oldPackage)) {
20799                            continue;
20800                        }
20801                        if (removedFromList == null) {
20802                            removedFromList = new ArrayList<>();
20803                        }
20804                        removedFromList.add(oldPackage);
20805                    }
20806                }
20807                mKeepUninstalledPackages = new ArrayList<>(packageList);
20808                if (removedFromList != null) {
20809                    final int removedCount = removedFromList.size();
20810                    for (int i = 0; i < removedCount; i++) {
20811                        deletePackageIfUnusedLPr(removedFromList.get(i));
20812                    }
20813                }
20814            }
20815        }
20816
20817        @Override
20818        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20819            synchronized (mPackages) {
20820                // If we do not support permission review, done.
20821                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20822                    return false;
20823                }
20824
20825                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20826                if (packageSetting == null) {
20827                    return false;
20828                }
20829
20830                // Permission review applies only to apps not supporting the new permission model.
20831                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20832                    return false;
20833                }
20834
20835                // Legacy apps have the permission and get user consent on launch.
20836                PermissionsState permissionsState = packageSetting.getPermissionsState();
20837                return permissionsState.isPermissionReviewRequired(userId);
20838            }
20839        }
20840
20841        @Override
20842        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20843            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20844        }
20845
20846        @Override
20847        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20848                int userId) {
20849            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20850        }
20851
20852        @Override
20853        public void setDeviceAndProfileOwnerPackages(
20854                int deviceOwnerUserId, String deviceOwnerPackage,
20855                SparseArray<String> profileOwnerPackages) {
20856            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20857                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20858        }
20859
20860        @Override
20861        public boolean isPackageDataProtected(int userId, String packageName) {
20862            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20863        }
20864    }
20865
20866    @Override
20867    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20868        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20869        synchronized (mPackages) {
20870            final long identity = Binder.clearCallingIdentity();
20871            try {
20872                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20873                        packageNames, userId);
20874            } finally {
20875                Binder.restoreCallingIdentity(identity);
20876            }
20877        }
20878    }
20879
20880    private static void enforceSystemOrPhoneCaller(String tag) {
20881        int callingUid = Binder.getCallingUid();
20882        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20883            throw new SecurityException(
20884                    "Cannot call " + tag + " from UID " + callingUid);
20885        }
20886    }
20887
20888    boolean isHistoricalPackageUsageAvailable() {
20889        return mPackageUsage.isHistoricalPackageUsageAvailable();
20890    }
20891
20892    /**
20893     * Return a <b>copy</b> of the collection of packages known to the package manager.
20894     * @return A copy of the values of mPackages.
20895     */
20896    Collection<PackageParser.Package> getPackages() {
20897        synchronized (mPackages) {
20898            return new ArrayList<>(mPackages.values());
20899        }
20900    }
20901
20902    /**
20903     * Logs process start information (including base APK hash) to the security log.
20904     * @hide
20905     */
20906    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20907            String apkFile, int pid) {
20908        if (!SecurityLog.isLoggingEnabled()) {
20909            return;
20910        }
20911        Bundle data = new Bundle();
20912        data.putLong("startTimestamp", System.currentTimeMillis());
20913        data.putString("processName", processName);
20914        data.putInt("uid", uid);
20915        data.putString("seinfo", seinfo);
20916        data.putString("apkFile", apkFile);
20917        data.putInt("pid", pid);
20918        Message msg = mProcessLoggingHandler.obtainMessage(
20919                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20920        msg.setData(data);
20921        mProcessLoggingHandler.sendMessage(msg);
20922    }
20923
20924    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20925        return mCompilerStats.getPackageStats(pkgName);
20926    }
20927
20928    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20929        return getOrCreateCompilerPackageStats(pkg.packageName);
20930    }
20931
20932    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20933        return mCompilerStats.getOrCreatePackageStats(pkgName);
20934    }
20935
20936    public void deleteCompilerPackageStats(String pkgName) {
20937        mCompilerStats.deletePackageStats(pkgName);
20938    }
20939}
20940