PackageManagerService.java revision 4c43fbd1da217cde46fef62e05c9b4fd6ff116fe
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralResolveInfo;
125import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.PatternMatcher;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.provider.Settings.Global;
200import android.security.KeyStore;
201import android.security.SystemKeyStore;
202import android.system.ErrnoException;
203import android.system.Os;
204import android.text.TextUtils;
205import android.text.format.DateUtils;
206import android.util.ArrayMap;
207import android.util.ArraySet;
208import android.util.DisplayMetrics;
209import android.util.EventLog;
210import android.util.ExceptionUtils;
211import android.util.Log;
212import android.util.LogPrinter;
213import android.util.MathUtils;
214import android.util.PrintStreamPrinter;
215import android.util.Slog;
216import android.util.SparseArray;
217import android.util.SparseBooleanArray;
218import android.util.SparseIntArray;
219import android.util.Xml;
220import android.util.jar.StrictJarFile;
221import android.view.Display;
222
223import com.android.internal.R;
224import com.android.internal.annotations.GuardedBy;
225import com.android.internal.app.IMediaContainerService;
226import com.android.internal.app.ResolverActivity;
227import com.android.internal.content.NativeLibraryHelper;
228import com.android.internal.content.PackageHelper;
229import com.android.internal.logging.MetricsLogger;
230import com.android.internal.os.IParcelFileDescriptorFactory;
231import com.android.internal.os.InstallerConnection.InstallerException;
232import com.android.internal.os.SomeArgs;
233import com.android.internal.os.Zygote;
234import com.android.internal.telephony.CarrierAppUtils;
235import com.android.internal.util.ArrayUtils;
236import com.android.internal.util.FastPrintWriter;
237import com.android.internal.util.FastXmlSerializer;
238import com.android.internal.util.IndentingPrintWriter;
239import com.android.internal.util.Preconditions;
240import com.android.internal.util.XmlUtils;
241import com.android.server.AttributeCache;
242import com.android.server.EventLogTags;
243import com.android.server.FgThread;
244import com.android.server.IntentResolver;
245import com.android.server.LocalServices;
246import com.android.server.ServiceThread;
247import com.android.server.SystemConfig;
248import com.android.server.Watchdog;
249import com.android.server.net.NetworkPolicyManagerInternal;
250import com.android.server.pm.PermissionsState.PermissionState;
251import com.android.server.pm.Settings.DatabaseVersion;
252import com.android.server.pm.Settings.VersionInfo;
253import com.android.server.storage.DeviceStorageMonitorInternal;
254
255import dalvik.system.CloseGuard;
256import dalvik.system.DexFile;
257import dalvik.system.VMRuntime;
258
259import libcore.io.IoUtils;
260import libcore.util.EmptyArray;
261
262import org.xmlpull.v1.XmlPullParser;
263import org.xmlpull.v1.XmlPullParserException;
264import org.xmlpull.v1.XmlSerializer;
265
266import java.io.BufferedOutputStream;
267import java.io.BufferedReader;
268import java.io.ByteArrayInputStream;
269import java.io.ByteArrayOutputStream;
270import java.io.File;
271import java.io.FileDescriptor;
272import java.io.FileInputStream;
273import java.io.FileNotFoundException;
274import java.io.FileOutputStream;
275import java.io.FileReader;
276import java.io.FilenameFilter;
277import java.io.IOException;
278import java.io.PrintWriter;
279import java.nio.charset.StandardCharsets;
280import java.security.DigestInputStream;
281import java.security.MessageDigest;
282import java.security.NoSuchAlgorithmException;
283import java.security.PublicKey;
284import java.security.cert.Certificate;
285import java.security.cert.CertificateEncodingException;
286import java.security.cert.CertificateException;
287import java.text.SimpleDateFormat;
288import java.util.ArrayList;
289import java.util.Arrays;
290import java.util.Collection;
291import java.util.Collections;
292import java.util.Comparator;
293import java.util.Date;
294import java.util.HashSet;
295import java.util.Iterator;
296import java.util.List;
297import java.util.Map;
298import java.util.Objects;
299import java.util.Set;
300import java.util.concurrent.CountDownLatch;
301import java.util.concurrent.TimeUnit;
302import java.util.concurrent.atomic.AtomicBoolean;
303import java.util.concurrent.atomic.AtomicInteger;
304
305/**
306 * Keep track of all those APKs everywhere.
307 * <p>
308 * Internally there are two important locks:
309 * <ul>
310 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
311 * and other related state. It is a fine-grained lock that should only be held
312 * momentarily, as it's one of the most contended locks in the system.
313 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
314 * operations typically involve heavy lifting of application data on disk. Since
315 * {@code installd} is single-threaded, and it's operations can often be slow,
316 * this lock should never be acquired while already holding {@link #mPackages}.
317 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
318 * holding {@link #mInstallLock}.
319 * </ul>
320 * Many internal methods rely on the caller to hold the appropriate locks, and
321 * this contract is expressed through method name suffixes:
322 * <ul>
323 * <li>fooLI(): the caller must hold {@link #mInstallLock}
324 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
325 * being modified must be frozen
326 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
327 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
328 * </ul>
329 * <p>
330 * Because this class is very central to the platform's security; please run all
331 * CTS and unit tests whenever making modifications:
332 *
333 * <pre>
334 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
335 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
336 * </pre>
337 */
338public class PackageManagerService extends IPackageManager.Stub {
339    static final String TAG = "PackageManager";
340    static final boolean DEBUG_SETTINGS = false;
341    static final boolean DEBUG_PREFERRED = false;
342    static final boolean DEBUG_UPGRADE = false;
343    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
344    private static final boolean DEBUG_BACKUP = false;
345    private static final boolean DEBUG_INSTALL = false;
346    private static final boolean DEBUG_REMOVE = false;
347    private static final boolean DEBUG_BROADCASTS = false;
348    private static final boolean DEBUG_SHOW_INFO = false;
349    private static final boolean DEBUG_PACKAGE_INFO = false;
350    private static final boolean DEBUG_INTENT_MATCHING = false;
351    private static final boolean DEBUG_PACKAGE_SCANNING = false;
352    private static final boolean DEBUG_VERIFY = false;
353    private static final boolean DEBUG_FILTERS = false;
354
355    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
356    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
357    // user, but by default initialize to this.
358    static final boolean DEBUG_DEXOPT = false;
359
360    private static final boolean DEBUG_ABI_SELECTION = false;
361    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
362    private static final boolean DEBUG_TRIAGED_MISSING = false;
363    private static final boolean DEBUG_APP_DATA = false;
364
365    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
366    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
367
368    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
369
370    private static final int RADIO_UID = Process.PHONE_UID;
371    private static final int LOG_UID = Process.LOG_UID;
372    private static final int NFC_UID = Process.NFC_UID;
373    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
374    private static final int SHELL_UID = Process.SHELL_UID;
375
376    // Cap the size of permission trees that 3rd party apps can define
377    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
378
379    // Suffix used during package installation when copying/moving
380    // package apks to install directory.
381    private static final String INSTALL_PACKAGE_SUFFIX = "-";
382
383    static final int SCAN_NO_DEX = 1<<1;
384    static final int SCAN_FORCE_DEX = 1<<2;
385    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
386    static final int SCAN_NEW_INSTALL = 1<<4;
387    static final int SCAN_NO_PATHS = 1<<5;
388    static final int SCAN_UPDATE_TIME = 1<<6;
389    static final int SCAN_DEFER_DEX = 1<<7;
390    static final int SCAN_BOOTING = 1<<8;
391    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
392    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
393    static final int SCAN_REPLACING = 1<<11;
394    static final int SCAN_REQUIRE_KNOWN = 1<<12;
395    static final int SCAN_MOVE = 1<<13;
396    static final int SCAN_INITIAL = 1<<14;
397    static final int SCAN_CHECK_ONLY = 1<<15;
398    static final int SCAN_DONT_KILL_APP = 1<<17;
399    static final int SCAN_IGNORE_FROZEN = 1<<18;
400
401    static final int REMOVE_CHATTY = 1<<16;
402
403    private static final int[] EMPTY_INT_ARRAY = new int[0];
404
405    /**
406     * Timeout (in milliseconds) after which the watchdog should declare that
407     * our handler thread is wedged.  The usual default for such things is one
408     * minute but we sometimes do very lengthy I/O operations on this thread,
409     * such as installing multi-gigabyte applications, so ours needs to be longer.
410     */
411    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
412
413    /**
414     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
415     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
416     * settings entry if available, otherwise we use the hardcoded default.  If it's been
417     * more than this long since the last fstrim, we force one during the boot sequence.
418     *
419     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
420     * one gets run at the next available charging+idle time.  This final mandatory
421     * no-fstrim check kicks in only of the other scheduling criteria is never met.
422     */
423    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
424
425    /**
426     * Whether verification is enabled by default.
427     */
428    private static final boolean DEFAULT_VERIFY_ENABLE = true;
429
430    /**
431     * The default maximum time to wait for the verification agent to return in
432     * milliseconds.
433     */
434    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
435
436    /**
437     * The default response for package verification timeout.
438     *
439     * This can be either PackageManager.VERIFICATION_ALLOW or
440     * PackageManager.VERIFICATION_REJECT.
441     */
442    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
443
444    static final String PLATFORM_PACKAGE_NAME = "android";
445
446    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
447
448    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
449            DEFAULT_CONTAINER_PACKAGE,
450            "com.android.defcontainer.DefaultContainerService");
451
452    private static final String KILL_APP_REASON_GIDS_CHANGED =
453            "permission grant or revoke changed gids";
454
455    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
456            "permissions revoked";
457
458    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
459
460    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
461
462    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
463    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
464
465    /** Permission grant: not grant the permission. */
466    private static final int GRANT_DENIED = 1;
467
468    /** Permission grant: grant the permission as an install permission. */
469    private static final int GRANT_INSTALL = 2;
470
471    /** Permission grant: grant the permission as a runtime one. */
472    private static final int GRANT_RUNTIME = 3;
473
474    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475    private static final int GRANT_UPGRADE = 4;
476
477    /** Canonical intent used to identify what counts as a "web browser" app */
478    private static final Intent sBrowserIntent;
479    static {
480        sBrowserIntent = new Intent();
481        sBrowserIntent.setAction(Intent.ACTION_VIEW);
482        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483        sBrowserIntent.setData(Uri.parse("http:"));
484    }
485
486    /**
487     * The set of all protected actions [i.e. those actions for which a high priority
488     * intent filter is disallowed].
489     */
490    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491    static {
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496    }
497
498    // Compilation reasons.
499    public static final int REASON_FIRST_BOOT = 0;
500    public static final int REASON_BOOT = 1;
501    public static final int REASON_INSTALL = 2;
502    public static final int REASON_BACKGROUND_DEXOPT = 3;
503    public static final int REASON_AB_OTA = 4;
504    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505    public static final int REASON_SHARED_APK = 6;
506    public static final int REASON_FORCED_DEXOPT = 7;
507    public static final int REASON_CORE_APP = 8;
508
509    public static final int REASON_LAST = REASON_CORE_APP;
510
511    /** Special library name that skips shared libraries check during compilation. */
512    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514    final ServiceThread mHandlerThread;
515
516    final PackageHandler mHandler;
517
518    private final ProcessLoggingHandler mProcessLoggingHandler;
519
520    /**
521     * Messages for {@link #mHandler} that need to wait for system ready before
522     * being dispatched.
523     */
524    private ArrayList<Message> mPostSystemReadyMessages;
525
526    final int mSdkVersion = Build.VERSION.SDK_INT;
527
528    final Context mContext;
529    final boolean mFactoryTest;
530    final boolean mOnlyCore;
531    final DisplayMetrics mMetrics;
532    final int mDefParseFlags;
533    final String[] mSeparateProcesses;
534    final boolean mIsUpgrade;
535    final boolean mIsPreNUpgrade;
536
537    /** The location for ASEC container files on internal storage. */
538    final String mAsecInternalPath;
539
540    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
541    // LOCK HELD.  Can be called with mInstallLock held.
542    @GuardedBy("mInstallLock")
543    final Installer mInstaller;
544
545    /** Directory where installed third-party apps stored */
546    final File mAppInstallDir;
547    final File mEphemeralInstallDir;
548
549    /**
550     * Directory to which applications installed internally have their
551     * 32 bit native libraries copied.
552     */
553    private File mAppLib32InstallDir;
554
555    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
556    // apps.
557    final File mDrmAppPrivateInstallDir;
558
559    // ----------------------------------------------------------------
560
561    // Lock for state used when installing and doing other long running
562    // operations.  Methods that must be called with this lock held have
563    // the suffix "LI".
564    final Object mInstallLock = new Object();
565
566    // ----------------------------------------------------------------
567
568    // Keys are String (package name), values are Package.  This also serves
569    // as the lock for the global state.  Methods that must be called with
570    // this lock held have the prefix "LP".
571    @GuardedBy("mPackages")
572    final ArrayMap<String, PackageParser.Package> mPackages =
573            new ArrayMap<String, PackageParser.Package>();
574
575    final ArrayMap<String, Set<String>> mKnownCodebase =
576            new ArrayMap<String, Set<String>>();
577
578    // Tracks available target package names -> overlay package paths.
579    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
580        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
581
582    /**
583     * Tracks new system packages [received in an OTA] that we expect to
584     * find updated user-installed versions. Keys are package name, values
585     * are package location.
586     */
587    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
588    /**
589     * Tracks high priority intent filters for protected actions. During boot, certain
590     * filter actions are protected and should never be allowed to have a high priority
591     * intent filter for them. However, there is one, and only one exception -- the
592     * setup wizard. It must be able to define a high priority intent filter for these
593     * actions to ensure there are no escapes from the wizard. We need to delay processing
594     * of these during boot as we need to look at all of the system packages in order
595     * to know which component is the setup wizard.
596     */
597    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
598    /**
599     * Whether or not processing protected filters should be deferred.
600     */
601    private boolean mDeferProtectedFilters = true;
602
603    /**
604     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
605     */
606    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
607    /**
608     * Whether or not system app permissions should be promoted from install to runtime.
609     */
610    boolean mPromoteSystemApps;
611
612    @GuardedBy("mPackages")
613    final Settings mSettings;
614
615    /**
616     * Set of package names that are currently "frozen", which means active
617     * surgery is being done on the code/data for that package. The platform
618     * will refuse to launch frozen packages to avoid race conditions.
619     *
620     * @see PackageFreezer
621     */
622    @GuardedBy("mPackages")
623    final ArraySet<String> mFrozenPackages = new ArraySet<>();
624
625    final ProtectedPackages mProtectedPackages;
626
627    boolean mFirstBoot;
628
629    // System configuration read by SystemConfig.
630    final int[] mGlobalGids;
631    final SparseArray<ArraySet<String>> mSystemPermissions;
632    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634    // If mac_permissions.xml was found for seinfo labeling.
635    boolean mFoundPolicyFile;
636
637    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639    public static final class SharedLibraryEntry {
640        public final String path;
641        public final String apk;
642
643        SharedLibraryEntry(String _path, String _apk) {
644            path = _path;
645            apk = _apk;
646        }
647    }
648
649    // Currently known shared libraries.
650    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651            new ArrayMap<String, SharedLibraryEntry>();
652
653    // All available activities, for your resolving pleasure.
654    final ActivityIntentResolver mActivities =
655            new ActivityIntentResolver();
656
657    // All available receivers, for your resolving pleasure.
658    final ActivityIntentResolver mReceivers =
659            new ActivityIntentResolver();
660
661    // All available services, for your resolving pleasure.
662    final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664    // All available providers, for your resolving pleasure.
665    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667    // Mapping from provider base names (first directory in content URI codePath)
668    // to the provider information.
669    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670            new ArrayMap<String, PackageParser.Provider>();
671
672    // Mapping from instrumentation class names to info about them.
673    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676    // Mapping from permission names to info about them.
677    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678            new ArrayMap<String, PackageParser.PermissionGroup>();
679
680    // Packages whose data we have transfered into another package, thus
681    // should no longer exist.
682    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684    // Broadcast actions that are only available to the system.
685    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687    /** List of packages waiting for verification. */
688    final SparseArray<PackageVerificationState> mPendingVerification
689            = new SparseArray<PackageVerificationState>();
690
691    /** Set of packages associated with each app op permission. */
692    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694    final PackageInstallerService mInstallerService;
695
696    private final PackageDexOptimizer mPackageDexOptimizer;
697
698    private AtomicInteger mNextMoveId = new AtomicInteger();
699    private final MoveCallbacks mMoveCallbacks;
700
701    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703    // Cache of users who need badging.
704    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706    /** Token for keys in mPendingVerification. */
707    private int mPendingVerificationToken = 0;
708
709    volatile boolean mSystemReady;
710    volatile boolean mSafeMode;
711    volatile boolean mHasSystemUidErrors;
712
713    ApplicationInfo mAndroidApplication;
714    final ActivityInfo mResolveActivity = new ActivityInfo();
715    final ResolveInfo mResolveInfo = new ResolveInfo();
716    ComponentName mResolveComponentName;
717    PackageParser.Package mPlatformPackage;
718    ComponentName mCustomResolverComponentName;
719
720    boolean mResolverReplaced = false;
721
722    private final @Nullable ComponentName mIntentFilterVerifierComponent;
723    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725    private int mIntentFilterVerificationToken = 0;
726
727    /** Component that knows whether or not an ephemeral application exists */
728    final ComponentName mEphemeralResolverComponent;
729    /** The service connection to the ephemeral resolver */
730    final EphemeralResolverConnection mEphemeralResolverConnection;
731
732    /** Component used to install ephemeral applications */
733    final ComponentName mEphemeralInstallerComponent;
734    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738            = new SparseArray<IntentFilterVerificationState>();
739
740    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
741
742    // List of packages names to keep cached, even if they are uninstalled for all users
743    private List<String> mKeepUninstalledPackages;
744
745    private UserManagerInternal mUserManagerInternal;
746
747    private static class IFVerificationParams {
748        PackageParser.Package pkg;
749        boolean replacing;
750        int userId;
751        int verifierUid;
752
753        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
754                int _userId, int _verifierUid) {
755            pkg = _pkg;
756            replacing = _replacing;
757            userId = _userId;
758            replacing = _replacing;
759            verifierUid = _verifierUid;
760        }
761    }
762
763    private interface IntentFilterVerifier<T extends IntentFilter> {
764        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
765                                               T filter, String packageName);
766        void startVerifications(int userId);
767        void receiveVerificationResponse(int verificationId);
768    }
769
770    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
771        private Context mContext;
772        private ComponentName mIntentFilterVerifierComponent;
773        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
774
775        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
776            mContext = context;
777            mIntentFilterVerifierComponent = verifierComponent;
778        }
779
780        private String getDefaultScheme() {
781            return IntentFilter.SCHEME_HTTPS;
782        }
783
784        @Override
785        public void startVerifications(int userId) {
786            // Launch verifications requests
787            int count = mCurrentIntentFilterVerifications.size();
788            for (int n=0; n<count; n++) {
789                int verificationId = mCurrentIntentFilterVerifications.get(n);
790                final IntentFilterVerificationState ivs =
791                        mIntentFilterVerificationStates.get(verificationId);
792
793                String packageName = ivs.getPackageName();
794
795                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
796                final int filterCount = filters.size();
797                ArraySet<String> domainsSet = new ArraySet<>();
798                for (int m=0; m<filterCount; m++) {
799                    PackageParser.ActivityIntentInfo filter = filters.get(m);
800                    domainsSet.addAll(filter.getHostsList());
801                }
802                synchronized (mPackages) {
803                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
804                            packageName, domainsSet) != null) {
805                        scheduleWriteSettingsLocked();
806                    }
807                }
808                sendVerificationRequest(userId, verificationId, ivs);
809            }
810            mCurrentIntentFilterVerifications.clear();
811        }
812
813        private void sendVerificationRequest(int userId, int verificationId,
814                IntentFilterVerificationState ivs) {
815
816            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
819                    verificationId);
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
822                    getDefaultScheme());
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
825                    ivs.getHostsString());
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
828                    ivs.getPackageName());
829            verificationIntent.setComponent(mIntentFilterVerifierComponent);
830            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
831
832            UserHandle user = new UserHandle(userId);
833            mContext.sendBroadcastAsUser(verificationIntent, user);
834            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
835                    "Sending IntentFilter verification broadcast");
836        }
837
838        public void receiveVerificationResponse(int verificationId) {
839            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
840
841            final boolean verified = ivs.isVerified();
842
843            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
844            final int count = filters.size();
845            if (DEBUG_DOMAIN_VERIFICATION) {
846                Slog.i(TAG, "Received verification response " + verificationId
847                        + " for " + count + " filters, verified=" + verified);
848            }
849            for (int n=0; n<count; n++) {
850                PackageParser.ActivityIntentInfo filter = filters.get(n);
851                filter.setVerified(verified);
852
853                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
854                        + " verified with result:" + verified + " and hosts:"
855                        + ivs.getHostsString());
856            }
857
858            mIntentFilterVerificationStates.remove(verificationId);
859
860            final String packageName = ivs.getPackageName();
861            IntentFilterVerificationInfo ivi = null;
862
863            synchronized (mPackages) {
864                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
865            }
866            if (ivi == null) {
867                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
868                        + verificationId + " packageName:" + packageName);
869                return;
870            }
871            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
872                    "Updating IntentFilterVerificationInfo for package " + packageName
873                            +" verificationId:" + verificationId);
874
875            synchronized (mPackages) {
876                if (verified) {
877                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
878                } else {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
880                }
881                scheduleWriteSettingsLocked();
882
883                final int userId = ivs.getUserId();
884                if (userId != UserHandle.USER_ALL) {
885                    final int userStatus =
886                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
887
888                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
889                    boolean needUpdate = false;
890
891                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
892                    // already been set by the User thru the Disambiguation dialog
893                    switch (userStatus) {
894                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
895                            if (verified) {
896                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
897                            } else {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
899                            }
900                            needUpdate = true;
901                            break;
902
903                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
904                            if (verified) {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
906                                needUpdate = true;
907                            }
908                            break;
909
910                        default:
911                            // Nothing to do
912                    }
913
914                    if (needUpdate) {
915                        mSettings.updateIntentFilterVerificationStatusLPw(
916                                packageName, updatedStatus, userId);
917                        scheduleWritePackageRestrictionsLocked(userId);
918                    }
919                }
920            }
921        }
922
923        @Override
924        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
925                    ActivityIntentInfo filter, String packageName) {
926            if (!hasValidDomains(filter)) {
927                return false;
928            }
929            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
930            if (ivs == null) {
931                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
932                        packageName);
933            }
934            if (DEBUG_DOMAIN_VERIFICATION) {
935                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
936            }
937            ivs.addFilter(filter);
938            return true;
939        }
940
941        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
942                int userId, int verificationId, String packageName) {
943            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
944                    verifierUid, userId, packageName);
945            ivs.setPendingState();
946            synchronized (mPackages) {
947                mIntentFilterVerificationStates.append(verificationId, ivs);
948                mCurrentIntentFilterVerifications.add(verificationId);
949            }
950            return ivs;
951        }
952    }
953
954    private static boolean hasValidDomains(ActivityIntentInfo filter) {
955        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
956                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
957                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
958    }
959
960    // Set of pending broadcasts for aggregating enable/disable of components.
961    static class PendingPackageBroadcasts {
962        // for each user id, a map of <package name -> components within that package>
963        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
964
965        public PendingPackageBroadcasts() {
966            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
967        }
968
969        public ArrayList<String> get(int userId, String packageName) {
970            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
971            return packages.get(packageName);
972        }
973
974        public void put(int userId, String packageName, ArrayList<String> components) {
975            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
976            packages.put(packageName, components);
977        }
978
979        public void remove(int userId, String packageName) {
980            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
981            if (packages != null) {
982                packages.remove(packageName);
983            }
984        }
985
986        public void remove(int userId) {
987            mUidMap.remove(userId);
988        }
989
990        public int userIdCount() {
991            return mUidMap.size();
992        }
993
994        public int userIdAt(int n) {
995            return mUidMap.keyAt(n);
996        }
997
998        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
999            return mUidMap.get(userId);
1000        }
1001
1002        public int size() {
1003            // total number of pending broadcast entries across all userIds
1004            int num = 0;
1005            for (int i = 0; i< mUidMap.size(); i++) {
1006                num += mUidMap.valueAt(i).size();
1007            }
1008            return num;
1009        }
1010
1011        public void clear() {
1012            mUidMap.clear();
1013        }
1014
1015        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1016            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1017            if (map == null) {
1018                map = new ArrayMap<String, ArrayList<String>>();
1019                mUidMap.put(userId, map);
1020            }
1021            return map;
1022        }
1023    }
1024    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1025
1026    // Service Connection to remote media container service to copy
1027    // package uri's from external media onto secure containers
1028    // or internal storage.
1029    private IMediaContainerService mContainerService = null;
1030
1031    static final int SEND_PENDING_BROADCAST = 1;
1032    static final int MCS_BOUND = 3;
1033    static final int END_COPY = 4;
1034    static final int INIT_COPY = 5;
1035    static final int MCS_UNBIND = 6;
1036    static final int START_CLEANING_PACKAGE = 7;
1037    static final int FIND_INSTALL_LOC = 8;
1038    static final int POST_INSTALL = 9;
1039    static final int MCS_RECONNECT = 10;
1040    static final int MCS_GIVE_UP = 11;
1041    static final int UPDATED_MEDIA_STATUS = 12;
1042    static final int WRITE_SETTINGS = 13;
1043    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1044    static final int PACKAGE_VERIFIED = 15;
1045    static final int CHECK_PENDING_VERIFICATION = 16;
1046    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1047    static final int INTENT_FILTER_VERIFIED = 18;
1048    static final int WRITE_PACKAGE_LIST = 19;
1049
1050    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1051
1052    // Delay time in millisecs
1053    static final int BROADCAST_DELAY = 10 * 1000;
1054
1055    static UserManagerService sUserManager;
1056
1057    // Stores a list of users whose package restrictions file needs to be updated
1058    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1059
1060    final private DefaultContainerConnection mDefContainerConn =
1061            new DefaultContainerConnection();
1062    class DefaultContainerConnection implements ServiceConnection {
1063        public void onServiceConnected(ComponentName name, IBinder service) {
1064            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1065            IMediaContainerService imcs =
1066                IMediaContainerService.Stub.asInterface(service);
1067            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1068        }
1069
1070        public void onServiceDisconnected(ComponentName name) {
1071            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1072        }
1073    }
1074
1075    // Recordkeeping of restore-after-install operations that are currently in flight
1076    // between the Package Manager and the Backup Manager
1077    static class PostInstallData {
1078        public InstallArgs args;
1079        public PackageInstalledInfo res;
1080
1081        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1082            args = _a;
1083            res = _r;
1084        }
1085    }
1086
1087    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1088    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1089
1090    // XML tags for backup/restore of various bits of state
1091    private static final String TAG_PREFERRED_BACKUP = "pa";
1092    private static final String TAG_DEFAULT_APPS = "da";
1093    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1094
1095    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1096    private static final String TAG_ALL_GRANTS = "rt-grants";
1097    private static final String TAG_GRANT = "grant";
1098    private static final String ATTR_PACKAGE_NAME = "pkg";
1099
1100    private static final String TAG_PERMISSION = "perm";
1101    private static final String ATTR_PERMISSION_NAME = "name";
1102    private static final String ATTR_IS_GRANTED = "g";
1103    private static final String ATTR_USER_SET = "set";
1104    private static final String ATTR_USER_FIXED = "fixed";
1105    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1106
1107    // System/policy permission grants are not backed up
1108    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1109            FLAG_PERMISSION_POLICY_FIXED
1110            | FLAG_PERMISSION_SYSTEM_FIXED
1111            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1112
1113    // And we back up these user-adjusted states
1114    private static final int USER_RUNTIME_GRANT_MASK =
1115            FLAG_PERMISSION_USER_SET
1116            | FLAG_PERMISSION_USER_FIXED
1117            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1118
1119    final @Nullable String mRequiredVerifierPackage;
1120    final @NonNull String mRequiredInstallerPackage;
1121    final @Nullable String mSetupWizardPackage;
1122    final @Nullable String mStorageManagerPackage;
1123    final @NonNull String mServicesSystemSharedLibraryPackageName;
1124    final @NonNull String mSharedSystemSharedLibraryPackageName;
1125
1126    final boolean mPermissionReviewRequired;
1127
1128    private final PackageUsage mPackageUsage = new PackageUsage();
1129    private final CompilerStats mCompilerStats = new CompilerStats();
1130
1131    class PackageHandler extends Handler {
1132        private boolean mBound = false;
1133        final ArrayList<HandlerParams> mPendingInstalls =
1134            new ArrayList<HandlerParams>();
1135
1136        private boolean connectToService() {
1137            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1138                    " DefaultContainerService");
1139            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1141            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1142                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1143                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1144                mBound = true;
1145                return true;
1146            }
1147            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1148            return false;
1149        }
1150
1151        private void disconnectService() {
1152            mContainerService = null;
1153            mBound = false;
1154            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1155            mContext.unbindService(mDefContainerConn);
1156            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1157        }
1158
1159        PackageHandler(Looper looper) {
1160            super(looper);
1161        }
1162
1163        public void handleMessage(Message msg) {
1164            try {
1165                doHandleMessage(msg);
1166            } finally {
1167                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1168            }
1169        }
1170
1171        void doHandleMessage(Message msg) {
1172            switch (msg.what) {
1173                case INIT_COPY: {
1174                    HandlerParams params = (HandlerParams) msg.obj;
1175                    int idx = mPendingInstalls.size();
1176                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1177                    // If a bind was already initiated we dont really
1178                    // need to do anything. The pending install
1179                    // will be processed later on.
1180                    if (!mBound) {
1181                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1182                                System.identityHashCode(mHandler));
1183                        // If this is the only one pending we might
1184                        // have to bind to the service again.
1185                        if (!connectToService()) {
1186                            Slog.e(TAG, "Failed to bind to media container service");
1187                            params.serviceError();
1188                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1189                                    System.identityHashCode(mHandler));
1190                            if (params.traceMethod != null) {
1191                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1192                                        params.traceCookie);
1193                            }
1194                            return;
1195                        } else {
1196                            // Once we bind to the service, the first
1197                            // pending request will be processed.
1198                            mPendingInstalls.add(idx, params);
1199                        }
1200                    } else {
1201                        mPendingInstalls.add(idx, params);
1202                        // Already bound to the service. Just make
1203                        // sure we trigger off processing the first request.
1204                        if (idx == 0) {
1205                            mHandler.sendEmptyMessage(MCS_BOUND);
1206                        }
1207                    }
1208                    break;
1209                }
1210                case MCS_BOUND: {
1211                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1212                    if (msg.obj != null) {
1213                        mContainerService = (IMediaContainerService) msg.obj;
1214                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1215                                System.identityHashCode(mHandler));
1216                    }
1217                    if (mContainerService == null) {
1218                        if (!mBound) {
1219                            // Something seriously wrong since we are not bound and we are not
1220                            // waiting for connection. Bail out.
1221                            Slog.e(TAG, "Cannot bind to media container service");
1222                            for (HandlerParams params : mPendingInstalls) {
1223                                // Indicate service bind error
1224                                params.serviceError();
1225                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1226                                        System.identityHashCode(params));
1227                                if (params.traceMethod != null) {
1228                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1229                                            params.traceMethod, params.traceCookie);
1230                                }
1231                                return;
1232                            }
1233                            mPendingInstalls.clear();
1234                        } else {
1235                            Slog.w(TAG, "Waiting to connect to media container service");
1236                        }
1237                    } else if (mPendingInstalls.size() > 0) {
1238                        HandlerParams params = mPendingInstalls.get(0);
1239                        if (params != null) {
1240                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1241                                    System.identityHashCode(params));
1242                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1243                            if (params.startCopy()) {
1244                                // We are done...  look for more work or to
1245                                // go idle.
1246                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1247                                        "Checking for more work or unbind...");
1248                                // Delete pending install
1249                                if (mPendingInstalls.size() > 0) {
1250                                    mPendingInstalls.remove(0);
1251                                }
1252                                if (mPendingInstalls.size() == 0) {
1253                                    if (mBound) {
1254                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1255                                                "Posting delayed MCS_UNBIND");
1256                                        removeMessages(MCS_UNBIND);
1257                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1258                                        // Unbind after a little delay, to avoid
1259                                        // continual thrashing.
1260                                        sendMessageDelayed(ubmsg, 10000);
1261                                    }
1262                                } else {
1263                                    // There are more pending requests in queue.
1264                                    // Just post MCS_BOUND message to trigger processing
1265                                    // of next pending install.
1266                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1267                                            "Posting MCS_BOUND for next work");
1268                                    mHandler.sendEmptyMessage(MCS_BOUND);
1269                                }
1270                            }
1271                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1272                        }
1273                    } else {
1274                        // Should never happen ideally.
1275                        Slog.w(TAG, "Empty queue");
1276                    }
1277                    break;
1278                }
1279                case MCS_RECONNECT: {
1280                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1281                    if (mPendingInstalls.size() > 0) {
1282                        if (mBound) {
1283                            disconnectService();
1284                        }
1285                        if (!connectToService()) {
1286                            Slog.e(TAG, "Failed to bind to media container service");
1287                            for (HandlerParams params : mPendingInstalls) {
1288                                // Indicate service bind error
1289                                params.serviceError();
1290                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1291                                        System.identityHashCode(params));
1292                            }
1293                            mPendingInstalls.clear();
1294                        }
1295                    }
1296                    break;
1297                }
1298                case MCS_UNBIND: {
1299                    // If there is no actual work left, then time to unbind.
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1301
1302                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1303                        if (mBound) {
1304                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1305
1306                            disconnectService();
1307                        }
1308                    } else if (mPendingInstalls.size() > 0) {
1309                        // There are more pending requests in queue.
1310                        // Just post MCS_BOUND message to trigger processing
1311                        // of next pending install.
1312                        mHandler.sendEmptyMessage(MCS_BOUND);
1313                    }
1314
1315                    break;
1316                }
1317                case MCS_GIVE_UP: {
1318                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1319                    HandlerParams params = mPendingInstalls.remove(0);
1320                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1321                            System.identityHashCode(params));
1322                    break;
1323                }
1324                case SEND_PENDING_BROADCAST: {
1325                    String packages[];
1326                    ArrayList<String> components[];
1327                    int size = 0;
1328                    int uids[];
1329                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1330                    synchronized (mPackages) {
1331                        if (mPendingBroadcasts == null) {
1332                            return;
1333                        }
1334                        size = mPendingBroadcasts.size();
1335                        if (size <= 0) {
1336                            // Nothing to be done. Just return
1337                            return;
1338                        }
1339                        packages = new String[size];
1340                        components = new ArrayList[size];
1341                        uids = new int[size];
1342                        int i = 0;  // filling out the above arrays
1343
1344                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1345                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1346                            Iterator<Map.Entry<String, ArrayList<String>>> it
1347                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1348                                            .entrySet().iterator();
1349                            while (it.hasNext() && i < size) {
1350                                Map.Entry<String, ArrayList<String>> ent = it.next();
1351                                packages[i] = ent.getKey();
1352                                components[i] = ent.getValue();
1353                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1354                                uids[i] = (ps != null)
1355                                        ? UserHandle.getUid(packageUserId, ps.appId)
1356                                        : -1;
1357                                i++;
1358                            }
1359                        }
1360                        size = i;
1361                        mPendingBroadcasts.clear();
1362                    }
1363                    // Send broadcasts
1364                    for (int i = 0; i < size; i++) {
1365                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1366                    }
1367                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1368                    break;
1369                }
1370                case START_CLEANING_PACKAGE: {
1371                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1372                    final String packageName = (String)msg.obj;
1373                    final int userId = msg.arg1;
1374                    final boolean andCode = msg.arg2 != 0;
1375                    synchronized (mPackages) {
1376                        if (userId == UserHandle.USER_ALL) {
1377                            int[] users = sUserManager.getUserIds();
1378                            for (int user : users) {
1379                                mSettings.addPackageToCleanLPw(
1380                                        new PackageCleanItem(user, packageName, andCode));
1381                            }
1382                        } else {
1383                            mSettings.addPackageToCleanLPw(
1384                                    new PackageCleanItem(userId, packageName, andCode));
1385                        }
1386                    }
1387                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1388                    startCleaningPackages();
1389                } break;
1390                case POST_INSTALL: {
1391                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1392
1393                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1394                    final boolean didRestore = (msg.arg2 != 0);
1395                    mRunningInstalls.delete(msg.arg1);
1396
1397                    if (data != null) {
1398                        InstallArgs args = data.args;
1399                        PackageInstalledInfo parentRes = data.res;
1400
1401                        final boolean grantPermissions = (args.installFlags
1402                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1403                        final boolean killApp = (args.installFlags
1404                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1405                        final String[] grantedPermissions = args.installGrantPermissions;
1406
1407                        // Handle the parent package
1408                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1409                                grantedPermissions, didRestore, args.installerPackageName,
1410                                args.observer);
1411
1412                        // Handle the child packages
1413                        final int childCount = (parentRes.addedChildPackages != null)
1414                                ? parentRes.addedChildPackages.size() : 0;
1415                        for (int i = 0; i < childCount; i++) {
1416                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1417                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1418                                    grantedPermissions, false, args.installerPackageName,
1419                                    args.observer);
1420                        }
1421
1422                        // Log tracing if needed
1423                        if (args.traceMethod != null) {
1424                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1425                                    args.traceCookie);
1426                        }
1427                    } else {
1428                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1429                    }
1430
1431                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1432                } break;
1433                case UPDATED_MEDIA_STATUS: {
1434                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1435                    boolean reportStatus = msg.arg1 == 1;
1436                    boolean doGc = msg.arg2 == 1;
1437                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1438                    if (doGc) {
1439                        // Force a gc to clear up stale containers.
1440                        Runtime.getRuntime().gc();
1441                    }
1442                    if (msg.obj != null) {
1443                        @SuppressWarnings("unchecked")
1444                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1445                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1446                        // Unload containers
1447                        unloadAllContainers(args);
1448                    }
1449                    if (reportStatus) {
1450                        try {
1451                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1452                            PackageHelper.getMountService().finishMediaUpdate();
1453                        } catch (RemoteException e) {
1454                            Log.e(TAG, "MountService not running?");
1455                        }
1456                    }
1457                } break;
1458                case WRITE_SETTINGS: {
1459                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1460                    synchronized (mPackages) {
1461                        removeMessages(WRITE_SETTINGS);
1462                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1463                        mSettings.writeLPr();
1464                        mDirtyUsers.clear();
1465                    }
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1467                } break;
1468                case WRITE_PACKAGE_RESTRICTIONS: {
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470                    synchronized (mPackages) {
1471                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1472                        for (int userId : mDirtyUsers) {
1473                            mSettings.writePackageRestrictionsLPr(userId);
1474                        }
1475                        mDirtyUsers.clear();
1476                    }
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478                } break;
1479                case WRITE_PACKAGE_LIST: {
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1481                    synchronized (mPackages) {
1482                        removeMessages(WRITE_PACKAGE_LIST);
1483                        mSettings.writePackageListLPr(msg.arg1);
1484                    }
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1486                } break;
1487                case CHECK_PENDING_VERIFICATION: {
1488                    final int verificationId = msg.arg1;
1489                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1490
1491                    if ((state != null) && !state.timeoutExtended()) {
1492                        final InstallArgs args = state.getInstallArgs();
1493                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1494
1495                        Slog.i(TAG, "Verification timed out for " + originUri);
1496                        mPendingVerification.remove(verificationId);
1497
1498                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1499
1500                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1501                            Slog.i(TAG, "Continuing with installation of " + originUri);
1502                            state.setVerifierResponse(Binder.getCallingUid(),
1503                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1504                            broadcastPackageVerified(verificationId, originUri,
1505                                    PackageManager.VERIFICATION_ALLOW,
1506                                    state.getInstallArgs().getUser());
1507                            try {
1508                                ret = args.copyApk(mContainerService, true);
1509                            } catch (RemoteException e) {
1510                                Slog.e(TAG, "Could not contact the ContainerService");
1511                            }
1512                        } else {
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    PackageManager.VERIFICATION_REJECT,
1515                                    state.getInstallArgs().getUser());
1516                        }
1517
1518                        Trace.asyncTraceEnd(
1519                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1520
1521                        processPendingInstall(args, ret);
1522                        mHandler.sendEmptyMessage(MCS_UNBIND);
1523                    }
1524                    break;
1525                }
1526                case PACKAGE_VERIFIED: {
1527                    final int verificationId = msg.arg1;
1528
1529                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1530                    if (state == null) {
1531                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1532                        break;
1533                    }
1534
1535                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1536
1537                    state.setVerifierResponse(response.callerUid, response.code);
1538
1539                    if (state.isVerificationComplete()) {
1540                        mPendingVerification.remove(verificationId);
1541
1542                        final InstallArgs args = state.getInstallArgs();
1543                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1544
1545                        int ret;
1546                        if (state.isInstallAllowed()) {
1547                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1548                            broadcastPackageVerified(verificationId, originUri,
1549                                    response.code, state.getInstallArgs().getUser());
1550                            try {
1551                                ret = args.copyApk(mContainerService, true);
1552                            } catch (RemoteException e) {
1553                                Slog.e(TAG, "Could not contact the ContainerService");
1554                            }
1555                        } else {
1556                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1557                        }
1558
1559                        Trace.asyncTraceEnd(
1560                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1561
1562                        processPendingInstall(args, ret);
1563                        mHandler.sendEmptyMessage(MCS_UNBIND);
1564                    }
1565
1566                    break;
1567                }
1568                case START_INTENT_FILTER_VERIFICATIONS: {
1569                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1570                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1571                            params.replacing, params.pkg);
1572                    break;
1573                }
1574                case INTENT_FILTER_VERIFIED: {
1575                    final int verificationId = msg.arg1;
1576
1577                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1578                            verificationId);
1579                    if (state == null) {
1580                        Slog.w(TAG, "Invalid IntentFilter verification token "
1581                                + verificationId + " received");
1582                        break;
1583                    }
1584
1585                    final int userId = state.getUserId();
1586
1587                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1588                            "Processing IntentFilter verification with token:"
1589                            + verificationId + " and userId:" + userId);
1590
1591                    final IntentFilterVerificationResponse response =
1592                            (IntentFilterVerificationResponse) msg.obj;
1593
1594                    state.setVerifierResponse(response.callerUid, response.code);
1595
1596                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1597                            "IntentFilter verification with token:" + verificationId
1598                            + " and userId:" + userId
1599                            + " is settings verifier response with response code:"
1600                            + response.code);
1601
1602                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1603                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1604                                + response.getFailedDomainsString());
1605                    }
1606
1607                    if (state.isVerificationComplete()) {
1608                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1609                    } else {
1610                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                                "IntentFilter verification with token:" + verificationId
1612                                + " was not said to be complete");
1613                    }
1614
1615                    break;
1616                }
1617            }
1618        }
1619    }
1620
1621    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1622            boolean killApp, String[] grantedPermissions,
1623            boolean launchedForRestore, String installerPackage,
1624            IPackageInstallObserver2 installObserver) {
1625        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1626            // Send the removed broadcasts
1627            if (res.removedInfo != null) {
1628                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1629            }
1630
1631            // Now that we successfully installed the package, grant runtime
1632            // permissions if requested before broadcasting the install.
1633            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1634                    >= Build.VERSION_CODES.M) {
1635                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1636            }
1637
1638            final boolean update = res.removedInfo != null
1639                    && res.removedInfo.removedPackage != null;
1640
1641            // If this is the first time we have child packages for a disabled privileged
1642            // app that had no children, we grant requested runtime permissions to the new
1643            // children if the parent on the system image had them already granted.
1644            if (res.pkg.parentPackage != null) {
1645                synchronized (mPackages) {
1646                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1647                }
1648            }
1649
1650            synchronized (mPackages) {
1651                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1652            }
1653
1654            final String packageName = res.pkg.applicationInfo.packageName;
1655            Bundle extras = new Bundle(1);
1656            extras.putInt(Intent.EXTRA_UID, res.uid);
1657
1658            // Determine the set of users who are adding this package for
1659            // the first time vs. those who are seeing an update.
1660            int[] firstUsers = EMPTY_INT_ARRAY;
1661            int[] updateUsers = EMPTY_INT_ARRAY;
1662            if (res.origUsers == null || res.origUsers.length == 0) {
1663                firstUsers = res.newUsers;
1664            } else {
1665                for (int newUser : res.newUsers) {
1666                    boolean isNew = true;
1667                    for (int origUser : res.origUsers) {
1668                        if (origUser == newUser) {
1669                            isNew = false;
1670                            break;
1671                        }
1672                    }
1673                    if (isNew) {
1674                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1675                    } else {
1676                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1677                    }
1678                }
1679            }
1680
1681            // Send installed broadcasts if the install/update is not ephemeral
1682            if (!isEphemeral(res.pkg)) {
1683                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1684
1685                // Send added for users that see the package for the first time
1686                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1687                        extras, 0 /*flags*/, null /*targetPackage*/,
1688                        null /*finishedReceiver*/, firstUsers);
1689
1690                // Send added for users that don't see the package for the first time
1691                if (update) {
1692                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1693                }
1694                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1695                        extras, 0 /*flags*/, null /*targetPackage*/,
1696                        null /*finishedReceiver*/, updateUsers);
1697
1698                // Send replaced for users that don't see the package for the first time
1699                if (update) {
1700                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1701                            packageName, extras, 0 /*flags*/,
1702                            null /*targetPackage*/, null /*finishedReceiver*/,
1703                            updateUsers);
1704                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1705                            null /*package*/, null /*extras*/, 0 /*flags*/,
1706                            packageName /*targetPackage*/,
1707                            null /*finishedReceiver*/, updateUsers);
1708                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1709                    // First-install and we did a restore, so we're responsible for the
1710                    // first-launch broadcast.
1711                    if (DEBUG_BACKUP) {
1712                        Slog.i(TAG, "Post-restore of " + packageName
1713                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1714                    }
1715                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1716                }
1717
1718                // Send broadcast package appeared if forward locked/external for all users
1719                // treat asec-hosted packages like removable media on upgrade
1720                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1721                    if (DEBUG_INSTALL) {
1722                        Slog.i(TAG, "upgrading pkg " + res.pkg
1723                                + " is ASEC-hosted -> AVAILABLE");
1724                    }
1725                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1726                    ArrayList<String> pkgList = new ArrayList<>(1);
1727                    pkgList.add(packageName);
1728                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1729                }
1730            }
1731
1732            // Work that needs to happen on first install within each user
1733            if (firstUsers != null && firstUsers.length > 0) {
1734                synchronized (mPackages) {
1735                    for (int userId : firstUsers) {
1736                        // If this app is a browser and it's newly-installed for some
1737                        // users, clear any default-browser state in those users. The
1738                        // app's nature doesn't depend on the user, so we can just check
1739                        // its browser nature in any user and generalize.
1740                        if (packageIsBrowser(packageName, userId)) {
1741                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1742                        }
1743
1744                        // We may also need to apply pending (restored) runtime
1745                        // permission grants within these users.
1746                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1747                    }
1748                }
1749            }
1750
1751            // Log current value of "unknown sources" setting
1752            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1753                    getUnknownSourcesSettings());
1754
1755            // Force a gc to clear up things
1756            Runtime.getRuntime().gc();
1757
1758            // Remove the replaced package's older resources safely now
1759            // We delete after a gc for applications  on sdcard.
1760            if (res.removedInfo != null && res.removedInfo.args != null) {
1761                synchronized (mInstallLock) {
1762                    res.removedInfo.args.doPostDeleteLI(true);
1763                }
1764            }
1765        }
1766
1767        // If someone is watching installs - notify them
1768        if (installObserver != null) {
1769            try {
1770                Bundle extras = extrasForInstallResult(res);
1771                installObserver.onPackageInstalled(res.name, res.returnCode,
1772                        res.returnMsg, extras);
1773            } catch (RemoteException e) {
1774                Slog.i(TAG, "Observer no longer exists.");
1775            }
1776        }
1777    }
1778
1779    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1780            PackageParser.Package pkg) {
1781        if (pkg.parentPackage == null) {
1782            return;
1783        }
1784        if (pkg.requestedPermissions == null) {
1785            return;
1786        }
1787        final PackageSetting disabledSysParentPs = mSettings
1788                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1789        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1790                || !disabledSysParentPs.isPrivileged()
1791                || (disabledSysParentPs.childPackageNames != null
1792                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1793            return;
1794        }
1795        final int[] allUserIds = sUserManager.getUserIds();
1796        final int permCount = pkg.requestedPermissions.size();
1797        for (int i = 0; i < permCount; i++) {
1798            String permission = pkg.requestedPermissions.get(i);
1799            BasePermission bp = mSettings.mPermissions.get(permission);
1800            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1801                continue;
1802            }
1803            for (int userId : allUserIds) {
1804                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1805                        permission, userId)) {
1806                    grantRuntimePermission(pkg.packageName, permission, userId);
1807                }
1808            }
1809        }
1810    }
1811
1812    private StorageEventListener mStorageListener = new StorageEventListener() {
1813        @Override
1814        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1815            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1816                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1817                    final String volumeUuid = vol.getFsUuid();
1818
1819                    // Clean up any users or apps that were removed or recreated
1820                    // while this volume was missing
1821                    reconcileUsers(volumeUuid);
1822                    reconcileApps(volumeUuid);
1823
1824                    // Clean up any install sessions that expired or were
1825                    // cancelled while this volume was missing
1826                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1827
1828                    loadPrivatePackages(vol);
1829
1830                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1831                    unloadPrivatePackages(vol);
1832                }
1833            }
1834
1835            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1836                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1837                    updateExternalMediaStatus(true, false);
1838                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1839                    updateExternalMediaStatus(false, false);
1840                }
1841            }
1842        }
1843
1844        @Override
1845        public void onVolumeForgotten(String fsUuid) {
1846            if (TextUtils.isEmpty(fsUuid)) {
1847                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1848                return;
1849            }
1850
1851            // Remove any apps installed on the forgotten volume
1852            synchronized (mPackages) {
1853                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1854                for (PackageSetting ps : packages) {
1855                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1856                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1857                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1858                }
1859
1860                mSettings.onVolumeForgotten(fsUuid);
1861                mSettings.writeLPr();
1862            }
1863        }
1864    };
1865
1866    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1867            String[] grantedPermissions) {
1868        for (int userId : userIds) {
1869            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1870        }
1871
1872        // We could have touched GID membership, so flush out packages.list
1873        synchronized (mPackages) {
1874            mSettings.writePackageListLPr();
1875        }
1876    }
1877
1878    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1879            String[] grantedPermissions) {
1880        SettingBase sb = (SettingBase) pkg.mExtras;
1881        if (sb == null) {
1882            return;
1883        }
1884
1885        PermissionsState permissionsState = sb.getPermissionsState();
1886
1887        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1888                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1889
1890        for (String permission : pkg.requestedPermissions) {
1891            final BasePermission bp;
1892            synchronized (mPackages) {
1893                bp = mSettings.mPermissions.get(permission);
1894            }
1895            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1896                    && (grantedPermissions == null
1897                           || ArrayUtils.contains(grantedPermissions, permission))) {
1898                final int flags = permissionsState.getPermissionFlags(permission, userId);
1899                // Installer cannot change immutable permissions.
1900                if ((flags & immutableFlags) == 0) {
1901                    grantRuntimePermission(pkg.packageName, permission, userId);
1902                }
1903            }
1904        }
1905    }
1906
1907    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1908        Bundle extras = null;
1909        switch (res.returnCode) {
1910            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1911                extras = new Bundle();
1912                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1913                        res.origPermission);
1914                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1915                        res.origPackage);
1916                break;
1917            }
1918            case PackageManager.INSTALL_SUCCEEDED: {
1919                extras = new Bundle();
1920                extras.putBoolean(Intent.EXTRA_REPLACING,
1921                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1922                break;
1923            }
1924        }
1925        return extras;
1926    }
1927
1928    void scheduleWriteSettingsLocked() {
1929        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1930            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1931        }
1932    }
1933
1934    void scheduleWritePackageListLocked(int userId) {
1935        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1936            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1937            msg.arg1 = userId;
1938            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1939        }
1940    }
1941
1942    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1943        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1944        scheduleWritePackageRestrictionsLocked(userId);
1945    }
1946
1947    void scheduleWritePackageRestrictionsLocked(int userId) {
1948        final int[] userIds = (userId == UserHandle.USER_ALL)
1949                ? sUserManager.getUserIds() : new int[]{userId};
1950        for (int nextUserId : userIds) {
1951            if (!sUserManager.exists(nextUserId)) return;
1952            mDirtyUsers.add(nextUserId);
1953            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1954                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1955            }
1956        }
1957    }
1958
1959    public static PackageManagerService main(Context context, Installer installer,
1960            boolean factoryTest, boolean onlyCore) {
1961        // Self-check for initial settings.
1962        PackageManagerServiceCompilerMapping.checkProperties();
1963
1964        PackageManagerService m = new PackageManagerService(context, installer,
1965                factoryTest, onlyCore);
1966        m.enableSystemUserPackages();
1967        ServiceManager.addService("package", m);
1968        return m;
1969    }
1970
1971    private void enableSystemUserPackages() {
1972        if (!UserManager.isSplitSystemUser()) {
1973            return;
1974        }
1975        // For system user, enable apps based on the following conditions:
1976        // - app is whitelisted or belong to one of these groups:
1977        //   -- system app which has no launcher icons
1978        //   -- system app which has INTERACT_ACROSS_USERS permission
1979        //   -- system IME app
1980        // - app is not in the blacklist
1981        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1982        Set<String> enableApps = new ArraySet<>();
1983        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1984                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1985                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1986        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1987        enableApps.addAll(wlApps);
1988        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1989                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1990        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1991        enableApps.removeAll(blApps);
1992        Log.i(TAG, "Applications installed for system user: " + enableApps);
1993        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1994                UserHandle.SYSTEM);
1995        final int allAppsSize = allAps.size();
1996        synchronized (mPackages) {
1997            for (int i = 0; i < allAppsSize; i++) {
1998                String pName = allAps.get(i);
1999                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2000                // Should not happen, but we shouldn't be failing if it does
2001                if (pkgSetting == null) {
2002                    continue;
2003                }
2004                boolean install = enableApps.contains(pName);
2005                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2006                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2007                            + " for system user");
2008                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2009                }
2010            }
2011        }
2012    }
2013
2014    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2015        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2016                Context.DISPLAY_SERVICE);
2017        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2018    }
2019
2020    /**
2021     * Requests that files preopted on a secondary system partition be copied to the data partition
2022     * if possible.  Note that the actual copying of the files is accomplished by init for security
2023     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2024     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2025     */
2026    private static void requestCopyPreoptedFiles() {
2027        final int WAIT_TIME_MS = 100;
2028        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2029        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2030            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2031            // We will wait for up to 100 seconds.
2032            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2033            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2034                try {
2035                    Thread.sleep(WAIT_TIME_MS);
2036                } catch (InterruptedException e) {
2037                    // Do nothing
2038                }
2039                if (SystemClock.uptimeMillis() > timeEnd) {
2040                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2041                    Slog.wtf(TAG, "cppreopt did not finish!");
2042                    break;
2043                }
2044            }
2045        }
2046    }
2047
2048    public PackageManagerService(Context context, Installer installer,
2049            boolean factoryTest, boolean onlyCore) {
2050        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2051        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2052                SystemClock.uptimeMillis());
2053
2054        if (mSdkVersion <= 0) {
2055            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2056        }
2057
2058        mContext = context;
2059
2060        mPermissionReviewRequired = context.getResources().getBoolean(
2061                R.bool.config_permissionReviewRequired);
2062
2063        mFactoryTest = factoryTest;
2064        mOnlyCore = onlyCore;
2065        mMetrics = new DisplayMetrics();
2066        mSettings = new Settings(mPackages);
2067        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2068                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2069        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2070                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2071        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2072                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2073        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2074                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2075        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2076                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2077        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2078                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2079
2080        String separateProcesses = SystemProperties.get("debug.separate_processes");
2081        if (separateProcesses != null && separateProcesses.length() > 0) {
2082            if ("*".equals(separateProcesses)) {
2083                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2084                mSeparateProcesses = null;
2085                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2086            } else {
2087                mDefParseFlags = 0;
2088                mSeparateProcesses = separateProcesses.split(",");
2089                Slog.w(TAG, "Running with debug.separate_processes: "
2090                        + separateProcesses);
2091            }
2092        } else {
2093            mDefParseFlags = 0;
2094            mSeparateProcesses = null;
2095        }
2096
2097        mInstaller = installer;
2098        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2099                "*dexopt*");
2100        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2101
2102        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2103                FgThread.get().getLooper());
2104
2105        getDefaultDisplayMetrics(context, mMetrics);
2106
2107        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2108        SystemConfig systemConfig = SystemConfig.getInstance();
2109        mGlobalGids = systemConfig.getGlobalGids();
2110        mSystemPermissions = systemConfig.getSystemPermissions();
2111        mAvailableFeatures = systemConfig.getAvailableFeatures();
2112        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2113
2114        mProtectedPackages = new ProtectedPackages(mContext);
2115
2116        synchronized (mInstallLock) {
2117        // writer
2118        synchronized (mPackages) {
2119            mHandlerThread = new ServiceThread(TAG,
2120                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2121            mHandlerThread.start();
2122            mHandler = new PackageHandler(mHandlerThread.getLooper());
2123            mProcessLoggingHandler = new ProcessLoggingHandler();
2124            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2125
2126            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2127
2128            File dataDir = Environment.getDataDirectory();
2129            mAppInstallDir = new File(dataDir, "app");
2130            mAppLib32InstallDir = new File(dataDir, "app-lib");
2131            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2132            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2133            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2134
2135            sUserManager = new UserManagerService(context, this, mPackages);
2136
2137            // Propagate permission configuration in to package manager.
2138            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2139                    = systemConfig.getPermissions();
2140            for (int i=0; i<permConfig.size(); i++) {
2141                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2142                BasePermission bp = mSettings.mPermissions.get(perm.name);
2143                if (bp == null) {
2144                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2145                    mSettings.mPermissions.put(perm.name, bp);
2146                }
2147                if (perm.gids != null) {
2148                    bp.setGids(perm.gids, perm.perUser);
2149                }
2150            }
2151
2152            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2153            for (int i=0; i<libConfig.size(); i++) {
2154                mSharedLibraries.put(libConfig.keyAt(i),
2155                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2156            }
2157
2158            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2159
2160            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2161            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2162            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2163
2164            if (mFirstBoot) {
2165                requestCopyPreoptedFiles();
2166            }
2167
2168            String customResolverActivity = Resources.getSystem().getString(
2169                    R.string.config_customResolverActivity);
2170            if (TextUtils.isEmpty(customResolverActivity)) {
2171                customResolverActivity = null;
2172            } else {
2173                mCustomResolverComponentName = ComponentName.unflattenFromString(
2174                        customResolverActivity);
2175            }
2176
2177            long startTime = SystemClock.uptimeMillis();
2178
2179            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2180                    startTime);
2181
2182            // Set flag to monitor and not change apk file paths when
2183            // scanning install directories.
2184            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2185
2186            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2187            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2188
2189            if (bootClassPath == null) {
2190                Slog.w(TAG, "No BOOTCLASSPATH found!");
2191            }
2192
2193            if (systemServerClassPath == null) {
2194                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2195            }
2196
2197            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2198            final String[] dexCodeInstructionSets =
2199                    getDexCodeInstructionSets(
2200                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2201
2202            /**
2203             * Ensure all external libraries have had dexopt run on them.
2204             */
2205            if (mSharedLibraries.size() > 0) {
2206                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2207                // NOTE: For now, we're compiling these system "shared libraries"
2208                // (and framework jars) into all available architectures. It's possible
2209                // to compile them only when we come across an app that uses them (there's
2210                // already logic for that in scanPackageLI) but that adds some complexity.
2211                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2212                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2213                        final String lib = libEntry.path;
2214                        if (lib == null) {
2215                            continue;
2216                        }
2217
2218                        try {
2219                            // Shared libraries do not have profiles so we perform a full
2220                            // AOT compilation (if needed).
2221                            int dexoptNeeded = DexFile.getDexOptNeeded(
2222                                    lib, dexCodeInstructionSet,
2223                                    getCompilerFilterForReason(REASON_SHARED_APK),
2224                                    false /* newProfile */);
2225                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2226                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2227                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2228                                        getCompilerFilterForReason(REASON_SHARED_APK),
2229                                        StorageManager.UUID_PRIVATE_INTERNAL,
2230                                        SKIP_SHARED_LIBRARY_CHECK);
2231                            }
2232                        } catch (FileNotFoundException e) {
2233                            Slog.w(TAG, "Library not found: " + lib);
2234                        } catch (IOException | InstallerException e) {
2235                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2236                                    + e.getMessage());
2237                        }
2238                    }
2239                }
2240                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2241            }
2242
2243            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2244
2245            final VersionInfo ver = mSettings.getInternalVersion();
2246            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2247
2248            // when upgrading from pre-M, promote system app permissions from install to runtime
2249            mPromoteSystemApps =
2250                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2251
2252            // When upgrading from pre-N, we need to handle package extraction like first boot,
2253            // as there is no profiling data available.
2254            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2255
2256            // save off the names of pre-existing system packages prior to scanning; we don't
2257            // want to automatically grant runtime permissions for new system apps
2258            if (mPromoteSystemApps) {
2259                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2260                while (pkgSettingIter.hasNext()) {
2261                    PackageSetting ps = pkgSettingIter.next();
2262                    if (isSystemApp(ps)) {
2263                        mExistingSystemPackages.add(ps.name);
2264                    }
2265                }
2266            }
2267
2268            // Collect vendor overlay packages.
2269            // (Do this before scanning any apps.)
2270            // For security and version matching reason, only consider
2271            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2272            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2273            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2274                    | PackageParser.PARSE_IS_SYSTEM
2275                    | PackageParser.PARSE_IS_SYSTEM_DIR
2276                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2277
2278            // Find base frameworks (resource packages without code).
2279            scanDirTracedLI(frameworkDir, mDefParseFlags
2280                    | PackageParser.PARSE_IS_SYSTEM
2281                    | PackageParser.PARSE_IS_SYSTEM_DIR
2282                    | PackageParser.PARSE_IS_PRIVILEGED,
2283                    scanFlags | SCAN_NO_DEX, 0);
2284
2285            // Collected privileged system packages.
2286            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2287            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2288                    | PackageParser.PARSE_IS_SYSTEM
2289                    | PackageParser.PARSE_IS_SYSTEM_DIR
2290                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2291
2292            // Collect ordinary system packages.
2293            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2294            scanDirTracedLI(systemAppDir, mDefParseFlags
2295                    | PackageParser.PARSE_IS_SYSTEM
2296                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2297
2298            // Collect all vendor packages.
2299            File vendorAppDir = new File("/vendor/app");
2300            try {
2301                vendorAppDir = vendorAppDir.getCanonicalFile();
2302            } catch (IOException e) {
2303                // failed to look up canonical path, continue with original one
2304            }
2305            scanDirTracedLI(vendorAppDir, mDefParseFlags
2306                    | PackageParser.PARSE_IS_SYSTEM
2307                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2308
2309            // Collect all OEM packages.
2310            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2311            scanDirTracedLI(oemAppDir, mDefParseFlags
2312                    | PackageParser.PARSE_IS_SYSTEM
2313                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2314
2315            // Prune any system packages that no longer exist.
2316            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2317            if (!mOnlyCore) {
2318                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2319                while (psit.hasNext()) {
2320                    PackageSetting ps = psit.next();
2321
2322                    /*
2323                     * If this is not a system app, it can't be a
2324                     * disable system app.
2325                     */
2326                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2327                        continue;
2328                    }
2329
2330                    /*
2331                     * If the package is scanned, it's not erased.
2332                     */
2333                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2334                    if (scannedPkg != null) {
2335                        /*
2336                         * If the system app is both scanned and in the
2337                         * disabled packages list, then it must have been
2338                         * added via OTA. Remove it from the currently
2339                         * scanned package so the previously user-installed
2340                         * application can be scanned.
2341                         */
2342                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2343                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2344                                    + ps.name + "; removing system app.  Last known codePath="
2345                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2346                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2347                                    + scannedPkg.mVersionCode);
2348                            removePackageLI(scannedPkg, true);
2349                            mExpectingBetter.put(ps.name, ps.codePath);
2350                        }
2351
2352                        continue;
2353                    }
2354
2355                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2356                        psit.remove();
2357                        logCriticalInfo(Log.WARN, "System package " + ps.name
2358                                + " no longer exists; it's data will be wiped");
2359                        // Actual deletion of code and data will be handled by later
2360                        // reconciliation step
2361                    } else {
2362                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2363                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2364                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2365                        }
2366                    }
2367                }
2368            }
2369
2370            //look for any incomplete package installations
2371            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2372            for (int i = 0; i < deletePkgsList.size(); i++) {
2373                // Actual deletion of code and data will be handled by later
2374                // reconciliation step
2375                final String packageName = deletePkgsList.get(i).name;
2376                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2377                synchronized (mPackages) {
2378                    mSettings.removePackageLPw(packageName);
2379                }
2380            }
2381
2382            //delete tmp files
2383            deleteTempPackageFiles();
2384
2385            // Remove any shared userIDs that have no associated packages
2386            mSettings.pruneSharedUsersLPw();
2387
2388            if (!mOnlyCore) {
2389                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2390                        SystemClock.uptimeMillis());
2391                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2392
2393                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2394                        | PackageParser.PARSE_FORWARD_LOCK,
2395                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2396
2397                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2398                        | PackageParser.PARSE_IS_EPHEMERAL,
2399                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2400
2401                /**
2402                 * Remove disable package settings for any updated system
2403                 * apps that were removed via an OTA. If they're not a
2404                 * previously-updated app, remove them completely.
2405                 * Otherwise, just revoke their system-level permissions.
2406                 */
2407                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2408                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2409                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2410
2411                    String msg;
2412                    if (deletedPkg == null) {
2413                        msg = "Updated system package " + deletedAppName
2414                                + " no longer exists; it's data will be wiped";
2415                        // Actual deletion of code and data will be handled by later
2416                        // reconciliation step
2417                    } else {
2418                        msg = "Updated system app + " + deletedAppName
2419                                + " no longer present; removing system privileges for "
2420                                + deletedAppName;
2421
2422                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2423
2424                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2425                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2426                    }
2427                    logCriticalInfo(Log.WARN, msg);
2428                }
2429
2430                /**
2431                 * Make sure all system apps that we expected to appear on
2432                 * the userdata partition actually showed up. If they never
2433                 * appeared, crawl back and revive the system version.
2434                 */
2435                for (int i = 0; i < mExpectingBetter.size(); i++) {
2436                    final String packageName = mExpectingBetter.keyAt(i);
2437                    if (!mPackages.containsKey(packageName)) {
2438                        final File scanFile = mExpectingBetter.valueAt(i);
2439
2440                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2441                                + " but never showed up; reverting to system");
2442
2443                        int reparseFlags = mDefParseFlags;
2444                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2445                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2446                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2447                                    | PackageParser.PARSE_IS_PRIVILEGED;
2448                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2449                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2450                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2451                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2452                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2453                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2454                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2455                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2456                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2457                        } else {
2458                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2459                            continue;
2460                        }
2461
2462                        mSettings.enableSystemPackageLPw(packageName);
2463
2464                        try {
2465                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2466                        } catch (PackageManagerException e) {
2467                            Slog.e(TAG, "Failed to parse original system package: "
2468                                    + e.getMessage());
2469                        }
2470                    }
2471                }
2472            }
2473            mExpectingBetter.clear();
2474
2475            // Resolve the storage manager.
2476            mStorageManagerPackage = getStorageManagerPackageName();
2477
2478            // Resolve protected action filters. Only the setup wizard is allowed to
2479            // have a high priority filter for these actions.
2480            mSetupWizardPackage = getSetupWizardPackageName();
2481            if (mProtectedFilters.size() > 0) {
2482                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2483                    Slog.i(TAG, "No setup wizard;"
2484                        + " All protected intents capped to priority 0");
2485                }
2486                for (ActivityIntentInfo filter : mProtectedFilters) {
2487                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2488                        if (DEBUG_FILTERS) {
2489                            Slog.i(TAG, "Found setup wizard;"
2490                                + " allow priority " + filter.getPriority() + ";"
2491                                + " package: " + filter.activity.info.packageName
2492                                + " activity: " + filter.activity.className
2493                                + " priority: " + filter.getPriority());
2494                        }
2495                        // skip setup wizard; allow it to keep the high priority filter
2496                        continue;
2497                    }
2498                    Slog.w(TAG, "Protected action; cap priority to 0;"
2499                            + " package: " + filter.activity.info.packageName
2500                            + " activity: " + filter.activity.className
2501                            + " origPrio: " + filter.getPriority());
2502                    filter.setPriority(0);
2503                }
2504            }
2505            mDeferProtectedFilters = false;
2506            mProtectedFilters.clear();
2507
2508            // Now that we know all of the shared libraries, update all clients to have
2509            // the correct library paths.
2510            updateAllSharedLibrariesLPw();
2511
2512            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2513                // NOTE: We ignore potential failures here during a system scan (like
2514                // the rest of the commands above) because there's precious little we
2515                // can do about it. A settings error is reported, though.
2516                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2517                        false /* boot complete */);
2518            }
2519
2520            // Now that we know all the packages we are keeping,
2521            // read and update their last usage times.
2522            mPackageUsage.read(mPackages);
2523            mCompilerStats.read();
2524
2525            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2526                    SystemClock.uptimeMillis());
2527            Slog.i(TAG, "Time to scan packages: "
2528                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2529                    + " seconds");
2530
2531            // If the platform SDK has changed since the last time we booted,
2532            // we need to re-grant app permission to catch any new ones that
2533            // appear.  This is really a hack, and means that apps can in some
2534            // cases get permissions that the user didn't initially explicitly
2535            // allow...  it would be nice to have some better way to handle
2536            // this situation.
2537            int updateFlags = UPDATE_PERMISSIONS_ALL;
2538            if (ver.sdkVersion != mSdkVersion) {
2539                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2540                        + mSdkVersion + "; regranting permissions for internal storage");
2541                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2542            }
2543            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2544            ver.sdkVersion = mSdkVersion;
2545
2546            // If this is the first boot or an update from pre-M, and it is a normal
2547            // boot, then we need to initialize the default preferred apps across
2548            // all defined users.
2549            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2550                for (UserInfo user : sUserManager.getUsers(true)) {
2551                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2552                    applyFactoryDefaultBrowserLPw(user.id);
2553                    primeDomainVerificationsLPw(user.id);
2554                }
2555            }
2556
2557            // Prepare storage for system user really early during boot,
2558            // since core system apps like SettingsProvider and SystemUI
2559            // can't wait for user to start
2560            final int storageFlags;
2561            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2562                storageFlags = StorageManager.FLAG_STORAGE_DE;
2563            } else {
2564                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2565            }
2566            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2567                    storageFlags, true /* migrateAppData */);
2568
2569            // If this is first boot after an OTA, and a normal boot, then
2570            // we need to clear code cache directories.
2571            // Note that we do *not* clear the application profiles. These remain valid
2572            // across OTAs and are used to drive profile verification (post OTA) and
2573            // profile compilation (without waiting to collect a fresh set of profiles).
2574            if (mIsUpgrade && !onlyCore) {
2575                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2576                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2577                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2578                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2579                        // No apps are running this early, so no need to freeze
2580                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2581                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2582                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2583                    }
2584                }
2585                ver.fingerprint = Build.FINGERPRINT;
2586            }
2587
2588            checkDefaultBrowser();
2589
2590            // clear only after permissions and other defaults have been updated
2591            mExistingSystemPackages.clear();
2592            mPromoteSystemApps = false;
2593
2594            // All the changes are done during package scanning.
2595            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2596
2597            // can downgrade to reader
2598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2599            mSettings.writeLPr();
2600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2601
2602            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2603            // early on (before the package manager declares itself as early) because other
2604            // components in the system server might ask for package contexts for these apps.
2605            //
2606            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2607            // (i.e, that the data partition is unavailable).
2608            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2609                long start = System.nanoTime();
2610                List<PackageParser.Package> coreApps = new ArrayList<>();
2611                for (PackageParser.Package pkg : mPackages.values()) {
2612                    if (pkg.coreApp) {
2613                        coreApps.add(pkg);
2614                    }
2615                }
2616
2617                int[] stats = performDexOptUpgrade(coreApps, false,
2618                        getCompilerFilterForReason(REASON_CORE_APP));
2619
2620                final int elapsedTimeSeconds =
2621                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2622                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2623
2624                if (DEBUG_DEXOPT) {
2625                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2626                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2627                }
2628
2629
2630                // TODO: Should we log these stats to tron too ?
2631                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2632                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2633                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2634                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2635            }
2636
2637            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2638                    SystemClock.uptimeMillis());
2639
2640            if (!mOnlyCore) {
2641                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2642                mRequiredInstallerPackage = getRequiredInstallerLPr();
2643                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2644                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2645                        mIntentFilterVerifierComponent);
2646                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2647                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2648                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2649                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2650            } else {
2651                mRequiredVerifierPackage = null;
2652                mRequiredInstallerPackage = null;
2653                mIntentFilterVerifierComponent = null;
2654                mIntentFilterVerifier = null;
2655                mServicesSystemSharedLibraryPackageName = null;
2656                mSharedSystemSharedLibraryPackageName = null;
2657            }
2658
2659            mInstallerService = new PackageInstallerService(context, this);
2660
2661            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2662            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2663            // both the installer and resolver must be present to enable ephemeral
2664            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2665                if (DEBUG_EPHEMERAL) {
2666                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2667                            + " installer:" + ephemeralInstallerComponent);
2668                }
2669                mEphemeralResolverComponent = ephemeralResolverComponent;
2670                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2671                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2672                mEphemeralResolverConnection =
2673                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2674            } else {
2675                if (DEBUG_EPHEMERAL) {
2676                    final String missingComponent =
2677                            (ephemeralResolverComponent == null)
2678                            ? (ephemeralInstallerComponent == null)
2679                                    ? "resolver and installer"
2680                                    : "resolver"
2681                            : "installer";
2682                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2683                }
2684                mEphemeralResolverComponent = null;
2685                mEphemeralInstallerComponent = null;
2686                mEphemeralResolverConnection = null;
2687            }
2688
2689            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2690        } // synchronized (mPackages)
2691        } // synchronized (mInstallLock)
2692
2693        // Now after opening every single application zip, make sure they
2694        // are all flushed.  Not really needed, but keeps things nice and
2695        // tidy.
2696        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2697        Runtime.getRuntime().gc();
2698        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2699
2700        // The initial scanning above does many calls into installd while
2701        // holding the mPackages lock, but we're mostly interested in yelling
2702        // once we have a booted system.
2703        mInstaller.setWarnIfHeld(mPackages);
2704
2705        // Expose private service for system components to use.
2706        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2707        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2708    }
2709
2710    @Override
2711    public boolean isFirstBoot() {
2712        return mFirstBoot;
2713    }
2714
2715    @Override
2716    public boolean isOnlyCoreApps() {
2717        return mOnlyCore;
2718    }
2719
2720    @Override
2721    public boolean isUpgrade() {
2722        return mIsUpgrade;
2723    }
2724
2725    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2726        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2727
2728        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2729                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2730                UserHandle.USER_SYSTEM);
2731        if (matches.size() == 1) {
2732            return matches.get(0).getComponentInfo().packageName;
2733        } else {
2734            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2735            return null;
2736        }
2737    }
2738
2739    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2740        synchronized (mPackages) {
2741            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2742            if (libraryEntry == null) {
2743                throw new IllegalStateException("Missing required shared library:" + libraryName);
2744            }
2745            return libraryEntry.apk;
2746        }
2747    }
2748
2749    private @NonNull String getRequiredInstallerLPr() {
2750        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2751        intent.addCategory(Intent.CATEGORY_DEFAULT);
2752        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2753
2754        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2755                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2756                UserHandle.USER_SYSTEM);
2757        if (matches.size() == 1) {
2758            ResolveInfo resolveInfo = matches.get(0);
2759            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2760                throw new RuntimeException("The installer must be a privileged app");
2761            }
2762            return matches.get(0).getComponentInfo().packageName;
2763        } else {
2764            throw new RuntimeException("There must be exactly one installer; found " + matches);
2765        }
2766    }
2767
2768    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2769        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2770
2771        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2772                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2773                UserHandle.USER_SYSTEM);
2774        ResolveInfo best = null;
2775        final int N = matches.size();
2776        for (int i = 0; i < N; i++) {
2777            final ResolveInfo cur = matches.get(i);
2778            final String packageName = cur.getComponentInfo().packageName;
2779            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2780                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2781                continue;
2782            }
2783
2784            if (best == null || cur.priority > best.priority) {
2785                best = cur;
2786            }
2787        }
2788
2789        if (best != null) {
2790            return best.getComponentInfo().getComponentName();
2791        } else {
2792            throw new RuntimeException("There must be at least one intent filter verifier");
2793        }
2794    }
2795
2796    private @Nullable ComponentName getEphemeralResolverLPr() {
2797        final String[] packageArray =
2798                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2799        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2800            if (DEBUG_EPHEMERAL) {
2801                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2802            }
2803            return null;
2804        }
2805
2806        final int resolveFlags =
2807                MATCH_DIRECT_BOOT_AWARE
2808                | MATCH_DIRECT_BOOT_UNAWARE
2809                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2810        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2811        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2812                resolveFlags, UserHandle.USER_SYSTEM);
2813
2814        final int N = resolvers.size();
2815        if (N == 0) {
2816            if (DEBUG_EPHEMERAL) {
2817                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2818            }
2819            return null;
2820        }
2821
2822        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2823        for (int i = 0; i < N; i++) {
2824            final ResolveInfo info = resolvers.get(i);
2825
2826            if (info.serviceInfo == null) {
2827                continue;
2828            }
2829
2830            final String packageName = info.serviceInfo.packageName;
2831            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2832                if (DEBUG_EPHEMERAL) {
2833                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2834                            + " pkg: " + packageName + ", info:" + info);
2835                }
2836                continue;
2837            }
2838
2839            if (DEBUG_EPHEMERAL) {
2840                Slog.v(TAG, "Ephemeral resolver found;"
2841                        + " pkg: " + packageName + ", info:" + info);
2842            }
2843            return new ComponentName(packageName, info.serviceInfo.name);
2844        }
2845        if (DEBUG_EPHEMERAL) {
2846            Slog.v(TAG, "Ephemeral resolver NOT found");
2847        }
2848        return null;
2849    }
2850
2851    private @Nullable ComponentName getEphemeralInstallerLPr() {
2852        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2853        intent.addCategory(Intent.CATEGORY_DEFAULT);
2854        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2855
2856        final int resolveFlags =
2857                MATCH_DIRECT_BOOT_AWARE
2858                | MATCH_DIRECT_BOOT_UNAWARE
2859                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2860        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2861                resolveFlags, UserHandle.USER_SYSTEM);
2862        if (matches.size() == 0) {
2863            return null;
2864        } else if (matches.size() == 1) {
2865            return matches.get(0).getComponentInfo().getComponentName();
2866        } else {
2867            throw new RuntimeException(
2868                    "There must be at most one ephemeral installer; found " + matches);
2869        }
2870    }
2871
2872    private void primeDomainVerificationsLPw(int userId) {
2873        if (DEBUG_DOMAIN_VERIFICATION) {
2874            Slog.d(TAG, "Priming domain verifications in user " + userId);
2875        }
2876
2877        SystemConfig systemConfig = SystemConfig.getInstance();
2878        ArraySet<String> packages = systemConfig.getLinkedApps();
2879
2880        for (String packageName : packages) {
2881            PackageParser.Package pkg = mPackages.get(packageName);
2882            if (pkg != null) {
2883                if (!pkg.isSystemApp()) {
2884                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2885                    continue;
2886                }
2887
2888                ArraySet<String> domains = null;
2889                for (PackageParser.Activity a : pkg.activities) {
2890                    for (ActivityIntentInfo filter : a.intents) {
2891                        if (hasValidDomains(filter)) {
2892                            if (domains == null) {
2893                                domains = new ArraySet<String>();
2894                            }
2895                            domains.addAll(filter.getHostsList());
2896                        }
2897                    }
2898                }
2899
2900                if (domains != null && domains.size() > 0) {
2901                    if (DEBUG_DOMAIN_VERIFICATION) {
2902                        Slog.v(TAG, "      + " + packageName);
2903                    }
2904                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2905                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2906                    // and then 'always' in the per-user state actually used for intent resolution.
2907                    final IntentFilterVerificationInfo ivi;
2908                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2909                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2910                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2911                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2912                } else {
2913                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2914                            + "' does not handle web links");
2915                }
2916            } else {
2917                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2918            }
2919        }
2920
2921        scheduleWritePackageRestrictionsLocked(userId);
2922        scheduleWriteSettingsLocked();
2923    }
2924
2925    private void applyFactoryDefaultBrowserLPw(int userId) {
2926        // The default browser app's package name is stored in a string resource,
2927        // with a product-specific overlay used for vendor customization.
2928        String browserPkg = mContext.getResources().getString(
2929                com.android.internal.R.string.default_browser);
2930        if (!TextUtils.isEmpty(browserPkg)) {
2931            // non-empty string => required to be a known package
2932            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2933            if (ps == null) {
2934                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2935                browserPkg = null;
2936            } else {
2937                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2938            }
2939        }
2940
2941        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2942        // default.  If there's more than one, just leave everything alone.
2943        if (browserPkg == null) {
2944            calculateDefaultBrowserLPw(userId);
2945        }
2946    }
2947
2948    private void calculateDefaultBrowserLPw(int userId) {
2949        List<String> allBrowsers = resolveAllBrowserApps(userId);
2950        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2951        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2952    }
2953
2954    private List<String> resolveAllBrowserApps(int userId) {
2955        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2956        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2957                PackageManager.MATCH_ALL, userId);
2958
2959        final int count = list.size();
2960        List<String> result = new ArrayList<String>(count);
2961        for (int i=0; i<count; i++) {
2962            ResolveInfo info = list.get(i);
2963            if (info.activityInfo == null
2964                    || !info.handleAllWebDataURI
2965                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2966                    || result.contains(info.activityInfo.packageName)) {
2967                continue;
2968            }
2969            result.add(info.activityInfo.packageName);
2970        }
2971
2972        return result;
2973    }
2974
2975    private boolean packageIsBrowser(String packageName, int userId) {
2976        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2977                PackageManager.MATCH_ALL, userId);
2978        final int N = list.size();
2979        for (int i = 0; i < N; i++) {
2980            ResolveInfo info = list.get(i);
2981            if (packageName.equals(info.activityInfo.packageName)) {
2982                return true;
2983            }
2984        }
2985        return false;
2986    }
2987
2988    private void checkDefaultBrowser() {
2989        final int myUserId = UserHandle.myUserId();
2990        final String packageName = getDefaultBrowserPackageName(myUserId);
2991        if (packageName != null) {
2992            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2993            if (info == null) {
2994                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2995                synchronized (mPackages) {
2996                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2997                }
2998            }
2999        }
3000    }
3001
3002    @Override
3003    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3004            throws RemoteException {
3005        try {
3006            return super.onTransact(code, data, reply, flags);
3007        } catch (RuntimeException e) {
3008            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3009                Slog.wtf(TAG, "Package Manager Crash", e);
3010            }
3011            throw e;
3012        }
3013    }
3014
3015    static int[] appendInts(int[] cur, int[] add) {
3016        if (add == null) return cur;
3017        if (cur == null) return add;
3018        final int N = add.length;
3019        for (int i=0; i<N; i++) {
3020            cur = appendInt(cur, add[i]);
3021        }
3022        return cur;
3023    }
3024
3025    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3026        if (!sUserManager.exists(userId)) return null;
3027        if (ps == null) {
3028            return null;
3029        }
3030        final PackageParser.Package p = ps.pkg;
3031        if (p == null) {
3032            return null;
3033        }
3034
3035        final PermissionsState permissionsState = ps.getPermissionsState();
3036
3037        // Compute GIDs only if requested
3038        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3039                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3040        // Compute granted permissions only if package has requested permissions
3041        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3042                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3043        final PackageUserState state = ps.readUserState(userId);
3044
3045        return PackageParser.generatePackageInfo(p, gids, flags,
3046                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3047    }
3048
3049    @Override
3050    public void checkPackageStartable(String packageName, int userId) {
3051        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3052
3053        synchronized (mPackages) {
3054            final PackageSetting ps = mSettings.mPackages.get(packageName);
3055            if (ps == null) {
3056                throw new SecurityException("Package " + packageName + " was not found!");
3057            }
3058
3059            if (!ps.getInstalled(userId)) {
3060                throw new SecurityException(
3061                        "Package " + packageName + " was not installed for user " + userId + "!");
3062            }
3063
3064            if (mSafeMode && !ps.isSystem()) {
3065                throw new SecurityException("Package " + packageName + " not a system app!");
3066            }
3067
3068            if (mFrozenPackages.contains(packageName)) {
3069                throw new SecurityException("Package " + packageName + " is currently frozen!");
3070            }
3071
3072            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3073                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3074                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3075            }
3076        }
3077    }
3078
3079    @Override
3080    public boolean isPackageAvailable(String packageName, int userId) {
3081        if (!sUserManager.exists(userId)) return false;
3082        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3083                false /* requireFullPermission */, false /* checkShell */, "is package available");
3084        synchronized (mPackages) {
3085            PackageParser.Package p = mPackages.get(packageName);
3086            if (p != null) {
3087                final PackageSetting ps = (PackageSetting) p.mExtras;
3088                if (ps != null) {
3089                    final PackageUserState state = ps.readUserState(userId);
3090                    if (state != null) {
3091                        return PackageParser.isAvailable(state);
3092                    }
3093                }
3094            }
3095        }
3096        return false;
3097    }
3098
3099    @Override
3100    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3101        if (!sUserManager.exists(userId)) return null;
3102        flags = updateFlagsForPackage(flags, userId, packageName);
3103        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3104                false /* requireFullPermission */, false /* checkShell */, "get package info");
3105        // reader
3106        synchronized (mPackages) {
3107            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3108            PackageParser.Package p = null;
3109            if (matchFactoryOnly) {
3110                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3111                if (ps != null) {
3112                    return generatePackageInfo(ps, flags, userId);
3113                }
3114            }
3115            if (p == null) {
3116                p = mPackages.get(packageName);
3117                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3118                    return null;
3119                }
3120            }
3121            if (DEBUG_PACKAGE_INFO)
3122                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3123            if (p != null) {
3124                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3125            }
3126            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3127                final PackageSetting ps = mSettings.mPackages.get(packageName);
3128                return generatePackageInfo(ps, flags, userId);
3129            }
3130        }
3131        return null;
3132    }
3133
3134    @Override
3135    public String[] currentToCanonicalPackageNames(String[] names) {
3136        String[] out = new String[names.length];
3137        // reader
3138        synchronized (mPackages) {
3139            for (int i=names.length-1; i>=0; i--) {
3140                PackageSetting ps = mSettings.mPackages.get(names[i]);
3141                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3142            }
3143        }
3144        return out;
3145    }
3146
3147    @Override
3148    public String[] canonicalToCurrentPackageNames(String[] names) {
3149        String[] out = new String[names.length];
3150        // reader
3151        synchronized (mPackages) {
3152            for (int i=names.length-1; i>=0; i--) {
3153                String cur = mSettings.getRenamedPackage(names[i]);
3154                out[i] = cur != null ? cur : names[i];
3155            }
3156        }
3157        return out;
3158    }
3159
3160    @Override
3161    public int getPackageUid(String packageName, int flags, int userId) {
3162        if (!sUserManager.exists(userId)) return -1;
3163        flags = updateFlagsForPackage(flags, userId, packageName);
3164        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3165                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3166
3167        // reader
3168        synchronized (mPackages) {
3169            final PackageParser.Package p = mPackages.get(packageName);
3170            if (p != null && p.isMatch(flags)) {
3171                return UserHandle.getUid(userId, p.applicationInfo.uid);
3172            }
3173            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3174                final PackageSetting ps = mSettings.mPackages.get(packageName);
3175                if (ps != null && ps.isMatch(flags)) {
3176                    return UserHandle.getUid(userId, ps.appId);
3177                }
3178            }
3179        }
3180
3181        return -1;
3182    }
3183
3184    @Override
3185    public int[] getPackageGids(String packageName, int flags, int userId) {
3186        if (!sUserManager.exists(userId)) return null;
3187        flags = updateFlagsForPackage(flags, userId, packageName);
3188        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3189                false /* requireFullPermission */, false /* checkShell */,
3190                "getPackageGids");
3191
3192        // reader
3193        synchronized (mPackages) {
3194            final PackageParser.Package p = mPackages.get(packageName);
3195            if (p != null && p.isMatch(flags)) {
3196                PackageSetting ps = (PackageSetting) p.mExtras;
3197                return ps.getPermissionsState().computeGids(userId);
3198            }
3199            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3200                final PackageSetting ps = mSettings.mPackages.get(packageName);
3201                if (ps != null && ps.isMatch(flags)) {
3202                    return ps.getPermissionsState().computeGids(userId);
3203                }
3204            }
3205        }
3206
3207        return null;
3208    }
3209
3210    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3211        if (bp.perm != null) {
3212            return PackageParser.generatePermissionInfo(bp.perm, flags);
3213        }
3214        PermissionInfo pi = new PermissionInfo();
3215        pi.name = bp.name;
3216        pi.packageName = bp.sourcePackage;
3217        pi.nonLocalizedLabel = bp.name;
3218        pi.protectionLevel = bp.protectionLevel;
3219        return pi;
3220    }
3221
3222    @Override
3223    public PermissionInfo getPermissionInfo(String name, int flags) {
3224        // reader
3225        synchronized (mPackages) {
3226            final BasePermission p = mSettings.mPermissions.get(name);
3227            if (p != null) {
3228                return generatePermissionInfo(p, flags);
3229            }
3230            return null;
3231        }
3232    }
3233
3234    @Override
3235    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3236            int flags) {
3237        // reader
3238        synchronized (mPackages) {
3239            if (group != null && !mPermissionGroups.containsKey(group)) {
3240                // This is thrown as NameNotFoundException
3241                return null;
3242            }
3243
3244            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3245            for (BasePermission p : mSettings.mPermissions.values()) {
3246                if (group == null) {
3247                    if (p.perm == null || p.perm.info.group == null) {
3248                        out.add(generatePermissionInfo(p, flags));
3249                    }
3250                } else {
3251                    if (p.perm != null && group.equals(p.perm.info.group)) {
3252                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3253                    }
3254                }
3255            }
3256            return new ParceledListSlice<>(out);
3257        }
3258    }
3259
3260    @Override
3261    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3262        // reader
3263        synchronized (mPackages) {
3264            return PackageParser.generatePermissionGroupInfo(
3265                    mPermissionGroups.get(name), flags);
3266        }
3267    }
3268
3269    @Override
3270    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3271        // reader
3272        synchronized (mPackages) {
3273            final int N = mPermissionGroups.size();
3274            ArrayList<PermissionGroupInfo> out
3275                    = new ArrayList<PermissionGroupInfo>(N);
3276            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3277                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3278            }
3279            return new ParceledListSlice<>(out);
3280        }
3281    }
3282
3283    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3284            int userId) {
3285        if (!sUserManager.exists(userId)) return null;
3286        PackageSetting ps = mSettings.mPackages.get(packageName);
3287        if (ps != null) {
3288            if (ps.pkg == null) {
3289                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3290                if (pInfo != null) {
3291                    return pInfo.applicationInfo;
3292                }
3293                return null;
3294            }
3295            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3296                    ps.readUserState(userId), userId);
3297        }
3298        return null;
3299    }
3300
3301    @Override
3302    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3303        if (!sUserManager.exists(userId)) return null;
3304        flags = updateFlagsForApplication(flags, userId, packageName);
3305        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3306                false /* requireFullPermission */, false /* checkShell */, "get application info");
3307        // writer
3308        synchronized (mPackages) {
3309            PackageParser.Package p = mPackages.get(packageName);
3310            if (DEBUG_PACKAGE_INFO) Log.v(
3311                    TAG, "getApplicationInfo " + packageName
3312                    + ": " + p);
3313            if (p != null) {
3314                PackageSetting ps = mSettings.mPackages.get(packageName);
3315                if (ps == null) return null;
3316                // Note: isEnabledLP() does not apply here - always return info
3317                return PackageParser.generateApplicationInfo(
3318                        p, flags, ps.readUserState(userId), userId);
3319            }
3320            if ("android".equals(packageName)||"system".equals(packageName)) {
3321                return mAndroidApplication;
3322            }
3323            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3324                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3325            }
3326        }
3327        return null;
3328    }
3329
3330    @Override
3331    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3332            final IPackageDataObserver observer) {
3333        mContext.enforceCallingOrSelfPermission(
3334                android.Manifest.permission.CLEAR_APP_CACHE, null);
3335        // Queue up an async operation since clearing cache may take a little while.
3336        mHandler.post(new Runnable() {
3337            public void run() {
3338                mHandler.removeCallbacks(this);
3339                boolean success = true;
3340                synchronized (mInstallLock) {
3341                    try {
3342                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3343                    } catch (InstallerException e) {
3344                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3345                        success = false;
3346                    }
3347                }
3348                if (observer != null) {
3349                    try {
3350                        observer.onRemoveCompleted(null, success);
3351                    } catch (RemoteException e) {
3352                        Slog.w(TAG, "RemoveException when invoking call back");
3353                    }
3354                }
3355            }
3356        });
3357    }
3358
3359    @Override
3360    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3361            final IntentSender pi) {
3362        mContext.enforceCallingOrSelfPermission(
3363                android.Manifest.permission.CLEAR_APP_CACHE, null);
3364        // Queue up an async operation since clearing cache may take a little while.
3365        mHandler.post(new Runnable() {
3366            public void run() {
3367                mHandler.removeCallbacks(this);
3368                boolean success = true;
3369                synchronized (mInstallLock) {
3370                    try {
3371                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3372                    } catch (InstallerException e) {
3373                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3374                        success = false;
3375                    }
3376                }
3377                if(pi != null) {
3378                    try {
3379                        // Callback via pending intent
3380                        int code = success ? 1 : 0;
3381                        pi.sendIntent(null, code, null,
3382                                null, null);
3383                    } catch (SendIntentException e1) {
3384                        Slog.i(TAG, "Failed to send pending intent");
3385                    }
3386                }
3387            }
3388        });
3389    }
3390
3391    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3392        synchronized (mInstallLock) {
3393            try {
3394                mInstaller.freeCache(volumeUuid, freeStorageSize);
3395            } catch (InstallerException e) {
3396                throw new IOException("Failed to free enough space", e);
3397            }
3398        }
3399    }
3400
3401    /**
3402     * Update given flags based on encryption status of current user.
3403     */
3404    private int updateFlags(int flags, int userId) {
3405        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3406                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3407            // Caller expressed an explicit opinion about what encryption
3408            // aware/unaware components they want to see, so fall through and
3409            // give them what they want
3410        } else {
3411            // Caller expressed no opinion, so match based on user state
3412            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3413                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3414            } else {
3415                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3416            }
3417        }
3418        return flags;
3419    }
3420
3421    private UserManagerInternal getUserManagerInternal() {
3422        if (mUserManagerInternal == null) {
3423            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3424        }
3425        return mUserManagerInternal;
3426    }
3427
3428    /**
3429     * Update given flags when being used to request {@link PackageInfo}.
3430     */
3431    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3432        boolean triaged = true;
3433        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3434                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3435            // Caller is asking for component details, so they'd better be
3436            // asking for specific encryption matching behavior, or be triaged
3437            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3438                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3439                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3440                triaged = false;
3441            }
3442        }
3443        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3444                | PackageManager.MATCH_SYSTEM_ONLY
3445                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3446            triaged = false;
3447        }
3448        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3449            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3450                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3451        }
3452        return updateFlags(flags, userId);
3453    }
3454
3455    /**
3456     * Update given flags when being used to request {@link ApplicationInfo}.
3457     */
3458    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3459        return updateFlagsForPackage(flags, userId, cookie);
3460    }
3461
3462    /**
3463     * Update given flags when being used to request {@link ComponentInfo}.
3464     */
3465    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3466        if (cookie instanceof Intent) {
3467            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3468                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3469            }
3470        }
3471
3472        boolean triaged = true;
3473        // Caller is asking for component details, so they'd better be
3474        // asking for specific encryption matching behavior, or be triaged
3475        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3476                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3477                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3478            triaged = false;
3479        }
3480        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3481            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3482                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3483        }
3484
3485        return updateFlags(flags, userId);
3486    }
3487
3488    /**
3489     * Update given flags when being used to request {@link ResolveInfo}.
3490     */
3491    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3492        // Safe mode means we shouldn't match any third-party components
3493        if (mSafeMode) {
3494            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3495        }
3496
3497        return updateFlagsForComponent(flags, userId, cookie);
3498    }
3499
3500    @Override
3501    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3502        if (!sUserManager.exists(userId)) return null;
3503        flags = updateFlagsForComponent(flags, userId, component);
3504        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3505                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3506        synchronized (mPackages) {
3507            PackageParser.Activity a = mActivities.mActivities.get(component);
3508
3509            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3510            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3511                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3512                if (ps == null) return null;
3513                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3514                        userId);
3515            }
3516            if (mResolveComponentName.equals(component)) {
3517                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3518                        new PackageUserState(), userId);
3519            }
3520        }
3521        return null;
3522    }
3523
3524    @Override
3525    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3526            String resolvedType) {
3527        synchronized (mPackages) {
3528            if (component.equals(mResolveComponentName)) {
3529                // The resolver supports EVERYTHING!
3530                return true;
3531            }
3532            PackageParser.Activity a = mActivities.mActivities.get(component);
3533            if (a == null) {
3534                return false;
3535            }
3536            for (int i=0; i<a.intents.size(); i++) {
3537                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3538                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3539                    return true;
3540                }
3541            }
3542            return false;
3543        }
3544    }
3545
3546    @Override
3547    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3548        if (!sUserManager.exists(userId)) return null;
3549        flags = updateFlagsForComponent(flags, userId, component);
3550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3551                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3552        synchronized (mPackages) {
3553            PackageParser.Activity a = mReceivers.mActivities.get(component);
3554            if (DEBUG_PACKAGE_INFO) Log.v(
3555                TAG, "getReceiverInfo " + component + ": " + a);
3556            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3557                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3558                if (ps == null) return null;
3559                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3560                        userId);
3561            }
3562        }
3563        return null;
3564    }
3565
3566    @Override
3567    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3568        if (!sUserManager.exists(userId)) return null;
3569        flags = updateFlagsForComponent(flags, userId, component);
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3571                false /* requireFullPermission */, false /* checkShell */, "get service info");
3572        synchronized (mPackages) {
3573            PackageParser.Service s = mServices.mServices.get(component);
3574            if (DEBUG_PACKAGE_INFO) Log.v(
3575                TAG, "getServiceInfo " + component + ": " + s);
3576            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3577                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3578                if (ps == null) return null;
3579                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3580                        userId);
3581            }
3582        }
3583        return null;
3584    }
3585
3586    @Override
3587    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3588        if (!sUserManager.exists(userId)) return null;
3589        flags = updateFlagsForComponent(flags, userId, component);
3590        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3591                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3592        synchronized (mPackages) {
3593            PackageParser.Provider p = mProviders.mProviders.get(component);
3594            if (DEBUG_PACKAGE_INFO) Log.v(
3595                TAG, "getProviderInfo " + component + ": " + p);
3596            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3597                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3598                if (ps == null) return null;
3599                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3600                        userId);
3601            }
3602        }
3603        return null;
3604    }
3605
3606    @Override
3607    public String[] getSystemSharedLibraryNames() {
3608        Set<String> libSet;
3609        synchronized (mPackages) {
3610            libSet = mSharedLibraries.keySet();
3611            int size = libSet.size();
3612            if (size > 0) {
3613                String[] libs = new String[size];
3614                libSet.toArray(libs);
3615                return libs;
3616            }
3617        }
3618        return null;
3619    }
3620
3621    @Override
3622    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3623        synchronized (mPackages) {
3624            return mServicesSystemSharedLibraryPackageName;
3625        }
3626    }
3627
3628    @Override
3629    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3630        synchronized (mPackages) {
3631            return mSharedSystemSharedLibraryPackageName;
3632        }
3633    }
3634
3635    @Override
3636    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3637        synchronized (mPackages) {
3638            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3639
3640            final FeatureInfo fi = new FeatureInfo();
3641            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3642                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3643            res.add(fi);
3644
3645            return new ParceledListSlice<>(res);
3646        }
3647    }
3648
3649    @Override
3650    public boolean hasSystemFeature(String name, int version) {
3651        synchronized (mPackages) {
3652            final FeatureInfo feat = mAvailableFeatures.get(name);
3653            if (feat == null) {
3654                return false;
3655            } else {
3656                return feat.version >= version;
3657            }
3658        }
3659    }
3660
3661    @Override
3662    public int checkPermission(String permName, String pkgName, int userId) {
3663        if (!sUserManager.exists(userId)) {
3664            return PackageManager.PERMISSION_DENIED;
3665        }
3666
3667        synchronized (mPackages) {
3668            final PackageParser.Package p = mPackages.get(pkgName);
3669            if (p != null && p.mExtras != null) {
3670                final PackageSetting ps = (PackageSetting) p.mExtras;
3671                final PermissionsState permissionsState = ps.getPermissionsState();
3672                if (permissionsState.hasPermission(permName, userId)) {
3673                    return PackageManager.PERMISSION_GRANTED;
3674                }
3675                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3676                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3677                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3678                    return PackageManager.PERMISSION_GRANTED;
3679                }
3680            }
3681        }
3682
3683        return PackageManager.PERMISSION_DENIED;
3684    }
3685
3686    @Override
3687    public int checkUidPermission(String permName, int uid) {
3688        final int userId = UserHandle.getUserId(uid);
3689
3690        if (!sUserManager.exists(userId)) {
3691            return PackageManager.PERMISSION_DENIED;
3692        }
3693
3694        synchronized (mPackages) {
3695            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3696            if (obj != null) {
3697                final SettingBase ps = (SettingBase) obj;
3698                final PermissionsState permissionsState = ps.getPermissionsState();
3699                if (permissionsState.hasPermission(permName, userId)) {
3700                    return PackageManager.PERMISSION_GRANTED;
3701                }
3702                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3703                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3704                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3705                    return PackageManager.PERMISSION_GRANTED;
3706                }
3707            } else {
3708                ArraySet<String> perms = mSystemPermissions.get(uid);
3709                if (perms != null) {
3710                    if (perms.contains(permName)) {
3711                        return PackageManager.PERMISSION_GRANTED;
3712                    }
3713                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3714                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3715                        return PackageManager.PERMISSION_GRANTED;
3716                    }
3717                }
3718            }
3719        }
3720
3721        return PackageManager.PERMISSION_DENIED;
3722    }
3723
3724    @Override
3725    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3726        if (UserHandle.getCallingUserId() != userId) {
3727            mContext.enforceCallingPermission(
3728                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3729                    "isPermissionRevokedByPolicy for user " + userId);
3730        }
3731
3732        if (checkPermission(permission, packageName, userId)
3733                == PackageManager.PERMISSION_GRANTED) {
3734            return false;
3735        }
3736
3737        final long identity = Binder.clearCallingIdentity();
3738        try {
3739            final int flags = getPermissionFlags(permission, packageName, userId);
3740            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3741        } finally {
3742            Binder.restoreCallingIdentity(identity);
3743        }
3744    }
3745
3746    @Override
3747    public String getPermissionControllerPackageName() {
3748        synchronized (mPackages) {
3749            return mRequiredInstallerPackage;
3750        }
3751    }
3752
3753    /**
3754     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3755     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3756     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3757     * @param message the message to log on security exception
3758     */
3759    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3760            boolean checkShell, String message) {
3761        if (userId < 0) {
3762            throw new IllegalArgumentException("Invalid userId " + userId);
3763        }
3764        if (checkShell) {
3765            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3766        }
3767        if (userId == UserHandle.getUserId(callingUid)) return;
3768        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3769            if (requireFullPermission) {
3770                mContext.enforceCallingOrSelfPermission(
3771                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3772            } else {
3773                try {
3774                    mContext.enforceCallingOrSelfPermission(
3775                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3776                } catch (SecurityException se) {
3777                    mContext.enforceCallingOrSelfPermission(
3778                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3779                }
3780            }
3781        }
3782    }
3783
3784    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3785        if (callingUid == Process.SHELL_UID) {
3786            if (userHandle >= 0
3787                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3788                throw new SecurityException("Shell does not have permission to access user "
3789                        + userHandle);
3790            } else if (userHandle < 0) {
3791                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3792                        + Debug.getCallers(3));
3793            }
3794        }
3795    }
3796
3797    private BasePermission findPermissionTreeLP(String permName) {
3798        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3799            if (permName.startsWith(bp.name) &&
3800                    permName.length() > bp.name.length() &&
3801                    permName.charAt(bp.name.length()) == '.') {
3802                return bp;
3803            }
3804        }
3805        return null;
3806    }
3807
3808    private BasePermission checkPermissionTreeLP(String permName) {
3809        if (permName != null) {
3810            BasePermission bp = findPermissionTreeLP(permName);
3811            if (bp != null) {
3812                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3813                    return bp;
3814                }
3815                throw new SecurityException("Calling uid "
3816                        + Binder.getCallingUid()
3817                        + " is not allowed to add to permission tree "
3818                        + bp.name + " owned by uid " + bp.uid);
3819            }
3820        }
3821        throw new SecurityException("No permission tree found for " + permName);
3822    }
3823
3824    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3825        if (s1 == null) {
3826            return s2 == null;
3827        }
3828        if (s2 == null) {
3829            return false;
3830        }
3831        if (s1.getClass() != s2.getClass()) {
3832            return false;
3833        }
3834        return s1.equals(s2);
3835    }
3836
3837    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3838        if (pi1.icon != pi2.icon) return false;
3839        if (pi1.logo != pi2.logo) return false;
3840        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3841        if (!compareStrings(pi1.name, pi2.name)) return false;
3842        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3843        // We'll take care of setting this one.
3844        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3845        // These are not currently stored in settings.
3846        //if (!compareStrings(pi1.group, pi2.group)) return false;
3847        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3848        //if (pi1.labelRes != pi2.labelRes) return false;
3849        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3850        return true;
3851    }
3852
3853    int permissionInfoFootprint(PermissionInfo info) {
3854        int size = info.name.length();
3855        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3856        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3857        return size;
3858    }
3859
3860    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3861        int size = 0;
3862        for (BasePermission perm : mSettings.mPermissions.values()) {
3863            if (perm.uid == tree.uid) {
3864                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3865            }
3866        }
3867        return size;
3868    }
3869
3870    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3871        // We calculate the max size of permissions defined by this uid and throw
3872        // if that plus the size of 'info' would exceed our stated maximum.
3873        if (tree.uid != Process.SYSTEM_UID) {
3874            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3875            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3876                throw new SecurityException("Permission tree size cap exceeded");
3877            }
3878        }
3879    }
3880
3881    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3882        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3883            throw new SecurityException("Label must be specified in permission");
3884        }
3885        BasePermission tree = checkPermissionTreeLP(info.name);
3886        BasePermission bp = mSettings.mPermissions.get(info.name);
3887        boolean added = bp == null;
3888        boolean changed = true;
3889        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3890        if (added) {
3891            enforcePermissionCapLocked(info, tree);
3892            bp = new BasePermission(info.name, tree.sourcePackage,
3893                    BasePermission.TYPE_DYNAMIC);
3894        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3895            throw new SecurityException(
3896                    "Not allowed to modify non-dynamic permission "
3897                    + info.name);
3898        } else {
3899            if (bp.protectionLevel == fixedLevel
3900                    && bp.perm.owner.equals(tree.perm.owner)
3901                    && bp.uid == tree.uid
3902                    && comparePermissionInfos(bp.perm.info, info)) {
3903                changed = false;
3904            }
3905        }
3906        bp.protectionLevel = fixedLevel;
3907        info = new PermissionInfo(info);
3908        info.protectionLevel = fixedLevel;
3909        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3910        bp.perm.info.packageName = tree.perm.info.packageName;
3911        bp.uid = tree.uid;
3912        if (added) {
3913            mSettings.mPermissions.put(info.name, bp);
3914        }
3915        if (changed) {
3916            if (!async) {
3917                mSettings.writeLPr();
3918            } else {
3919                scheduleWriteSettingsLocked();
3920            }
3921        }
3922        return added;
3923    }
3924
3925    @Override
3926    public boolean addPermission(PermissionInfo info) {
3927        synchronized (mPackages) {
3928            return addPermissionLocked(info, false);
3929        }
3930    }
3931
3932    @Override
3933    public boolean addPermissionAsync(PermissionInfo info) {
3934        synchronized (mPackages) {
3935            return addPermissionLocked(info, true);
3936        }
3937    }
3938
3939    @Override
3940    public void removePermission(String name) {
3941        synchronized (mPackages) {
3942            checkPermissionTreeLP(name);
3943            BasePermission bp = mSettings.mPermissions.get(name);
3944            if (bp != null) {
3945                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3946                    throw new SecurityException(
3947                            "Not allowed to modify non-dynamic permission "
3948                            + name);
3949                }
3950                mSettings.mPermissions.remove(name);
3951                mSettings.writeLPr();
3952            }
3953        }
3954    }
3955
3956    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3957            BasePermission bp) {
3958        int index = pkg.requestedPermissions.indexOf(bp.name);
3959        if (index == -1) {
3960            throw new SecurityException("Package " + pkg.packageName
3961                    + " has not requested permission " + bp.name);
3962        }
3963        if (!bp.isRuntime() && !bp.isDevelopment()) {
3964            throw new SecurityException("Permission " + bp.name
3965                    + " is not a changeable permission type");
3966        }
3967    }
3968
3969    @Override
3970    public void grantRuntimePermission(String packageName, String name, final int userId) {
3971        if (!sUserManager.exists(userId)) {
3972            Log.e(TAG, "No such user:" + userId);
3973            return;
3974        }
3975
3976        mContext.enforceCallingOrSelfPermission(
3977                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3978                "grantRuntimePermission");
3979
3980        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3981                true /* requireFullPermission */, true /* checkShell */,
3982                "grantRuntimePermission");
3983
3984        final int uid;
3985        final SettingBase sb;
3986
3987        synchronized (mPackages) {
3988            final PackageParser.Package pkg = mPackages.get(packageName);
3989            if (pkg == null) {
3990                throw new IllegalArgumentException("Unknown package: " + packageName);
3991            }
3992
3993            final BasePermission bp = mSettings.mPermissions.get(name);
3994            if (bp == null) {
3995                throw new IllegalArgumentException("Unknown permission: " + name);
3996            }
3997
3998            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3999
4000            // If a permission review is required for legacy apps we represent
4001            // their permissions as always granted runtime ones since we need
4002            // to keep the review required permission flag per user while an
4003            // install permission's state is shared across all users.
4004            if (mPermissionReviewRequired
4005                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4006                    && bp.isRuntime()) {
4007                return;
4008            }
4009
4010            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4011            sb = (SettingBase) pkg.mExtras;
4012            if (sb == null) {
4013                throw new IllegalArgumentException("Unknown package: " + packageName);
4014            }
4015
4016            final PermissionsState permissionsState = sb.getPermissionsState();
4017
4018            final int flags = permissionsState.getPermissionFlags(name, userId);
4019            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4020                throw new SecurityException("Cannot grant system fixed permission "
4021                        + name + " for package " + packageName);
4022            }
4023
4024            if (bp.isDevelopment()) {
4025                // Development permissions must be handled specially, since they are not
4026                // normal runtime permissions.  For now they apply to all users.
4027                if (permissionsState.grantInstallPermission(bp) !=
4028                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4029                    scheduleWriteSettingsLocked();
4030                }
4031                return;
4032            }
4033
4034            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4035                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4036                return;
4037            }
4038
4039            final int result = permissionsState.grantRuntimePermission(bp, userId);
4040            switch (result) {
4041                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4042                    return;
4043                }
4044
4045                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4046                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4047                    mHandler.post(new Runnable() {
4048                        @Override
4049                        public void run() {
4050                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4051                        }
4052                    });
4053                }
4054                break;
4055            }
4056
4057            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4058
4059            // Not critical if that is lost - app has to request again.
4060            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4061        }
4062
4063        // Only need to do this if user is initialized. Otherwise it's a new user
4064        // and there are no processes running as the user yet and there's no need
4065        // to make an expensive call to remount processes for the changed permissions.
4066        if (READ_EXTERNAL_STORAGE.equals(name)
4067                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4068            final long token = Binder.clearCallingIdentity();
4069            try {
4070                if (sUserManager.isInitialized(userId)) {
4071                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4072                            MountServiceInternal.class);
4073                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4074                }
4075            } finally {
4076                Binder.restoreCallingIdentity(token);
4077            }
4078        }
4079    }
4080
4081    @Override
4082    public void revokeRuntimePermission(String packageName, String name, int userId) {
4083        if (!sUserManager.exists(userId)) {
4084            Log.e(TAG, "No such user:" + userId);
4085            return;
4086        }
4087
4088        mContext.enforceCallingOrSelfPermission(
4089                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4090                "revokeRuntimePermission");
4091
4092        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4093                true /* requireFullPermission */, true /* checkShell */,
4094                "revokeRuntimePermission");
4095
4096        final int appId;
4097
4098        synchronized (mPackages) {
4099            final PackageParser.Package pkg = mPackages.get(packageName);
4100            if (pkg == null) {
4101                throw new IllegalArgumentException("Unknown package: " + packageName);
4102            }
4103
4104            final BasePermission bp = mSettings.mPermissions.get(name);
4105            if (bp == null) {
4106                throw new IllegalArgumentException("Unknown permission: " + name);
4107            }
4108
4109            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4110
4111            // If a permission review is required for legacy apps we represent
4112            // their permissions as always granted runtime ones since we need
4113            // to keep the review required permission flag per user while an
4114            // install permission's state is shared across all users.
4115            if (mPermissionReviewRequired
4116                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4117                    && bp.isRuntime()) {
4118                return;
4119            }
4120
4121            SettingBase sb = (SettingBase) pkg.mExtras;
4122            if (sb == null) {
4123                throw new IllegalArgumentException("Unknown package: " + packageName);
4124            }
4125
4126            final PermissionsState permissionsState = sb.getPermissionsState();
4127
4128            final int flags = permissionsState.getPermissionFlags(name, userId);
4129            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4130                throw new SecurityException("Cannot revoke system fixed permission "
4131                        + name + " for package " + packageName);
4132            }
4133
4134            if (bp.isDevelopment()) {
4135                // Development permissions must be handled specially, since they are not
4136                // normal runtime permissions.  For now they apply to all users.
4137                if (permissionsState.revokeInstallPermission(bp) !=
4138                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4139                    scheduleWriteSettingsLocked();
4140                }
4141                return;
4142            }
4143
4144            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4145                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4146                return;
4147            }
4148
4149            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4150
4151            // Critical, after this call app should never have the permission.
4152            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4153
4154            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4155        }
4156
4157        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4158    }
4159
4160    @Override
4161    public void resetRuntimePermissions() {
4162        mContext.enforceCallingOrSelfPermission(
4163                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4164                "revokeRuntimePermission");
4165
4166        int callingUid = Binder.getCallingUid();
4167        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4168            mContext.enforceCallingOrSelfPermission(
4169                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4170                    "resetRuntimePermissions");
4171        }
4172
4173        synchronized (mPackages) {
4174            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4175            for (int userId : UserManagerService.getInstance().getUserIds()) {
4176                final int packageCount = mPackages.size();
4177                for (int i = 0; i < packageCount; i++) {
4178                    PackageParser.Package pkg = mPackages.valueAt(i);
4179                    if (!(pkg.mExtras instanceof PackageSetting)) {
4180                        continue;
4181                    }
4182                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4183                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4184                }
4185            }
4186        }
4187    }
4188
4189    @Override
4190    public int getPermissionFlags(String name, String packageName, int userId) {
4191        if (!sUserManager.exists(userId)) {
4192            return 0;
4193        }
4194
4195        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4196
4197        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4198                true /* requireFullPermission */, false /* checkShell */,
4199                "getPermissionFlags");
4200
4201        synchronized (mPackages) {
4202            final PackageParser.Package pkg = mPackages.get(packageName);
4203            if (pkg == null) {
4204                return 0;
4205            }
4206
4207            final BasePermission bp = mSettings.mPermissions.get(name);
4208            if (bp == null) {
4209                return 0;
4210            }
4211
4212            SettingBase sb = (SettingBase) pkg.mExtras;
4213            if (sb == null) {
4214                return 0;
4215            }
4216
4217            PermissionsState permissionsState = sb.getPermissionsState();
4218            return permissionsState.getPermissionFlags(name, userId);
4219        }
4220    }
4221
4222    @Override
4223    public void updatePermissionFlags(String name, String packageName, int flagMask,
4224            int flagValues, int userId) {
4225        if (!sUserManager.exists(userId)) {
4226            return;
4227        }
4228
4229        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4230
4231        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4232                true /* requireFullPermission */, true /* checkShell */,
4233                "updatePermissionFlags");
4234
4235        // Only the system can change these flags and nothing else.
4236        if (getCallingUid() != Process.SYSTEM_UID) {
4237            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4238            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4239            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4240            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4241            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4242        }
4243
4244        synchronized (mPackages) {
4245            final PackageParser.Package pkg = mPackages.get(packageName);
4246            if (pkg == null) {
4247                throw new IllegalArgumentException("Unknown package: " + packageName);
4248            }
4249
4250            final BasePermission bp = mSettings.mPermissions.get(name);
4251            if (bp == null) {
4252                throw new IllegalArgumentException("Unknown permission: " + name);
4253            }
4254
4255            SettingBase sb = (SettingBase) pkg.mExtras;
4256            if (sb == null) {
4257                throw new IllegalArgumentException("Unknown package: " + packageName);
4258            }
4259
4260            PermissionsState permissionsState = sb.getPermissionsState();
4261
4262            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4263
4264            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4265                // Install and runtime permissions are stored in different places,
4266                // so figure out what permission changed and persist the change.
4267                if (permissionsState.getInstallPermissionState(name) != null) {
4268                    scheduleWriteSettingsLocked();
4269                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4270                        || hadState) {
4271                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4272                }
4273            }
4274        }
4275    }
4276
4277    /**
4278     * Update the permission flags for all packages and runtime permissions of a user in order
4279     * to allow device or profile owner to remove POLICY_FIXED.
4280     */
4281    @Override
4282    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4283        if (!sUserManager.exists(userId)) {
4284            return;
4285        }
4286
4287        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4288
4289        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4290                true /* requireFullPermission */, true /* checkShell */,
4291                "updatePermissionFlagsForAllApps");
4292
4293        // Only the system can change system fixed flags.
4294        if (getCallingUid() != Process.SYSTEM_UID) {
4295            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4296            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4297        }
4298
4299        synchronized (mPackages) {
4300            boolean changed = false;
4301            final int packageCount = mPackages.size();
4302            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4303                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4304                SettingBase sb = (SettingBase) pkg.mExtras;
4305                if (sb == null) {
4306                    continue;
4307                }
4308                PermissionsState permissionsState = sb.getPermissionsState();
4309                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4310                        userId, flagMask, flagValues);
4311            }
4312            if (changed) {
4313                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4314            }
4315        }
4316    }
4317
4318    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4319        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4320                != PackageManager.PERMISSION_GRANTED
4321            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4322                != PackageManager.PERMISSION_GRANTED) {
4323            throw new SecurityException(message + " requires "
4324                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4325                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4326        }
4327    }
4328
4329    @Override
4330    public boolean shouldShowRequestPermissionRationale(String permissionName,
4331            String packageName, int userId) {
4332        if (UserHandle.getCallingUserId() != userId) {
4333            mContext.enforceCallingPermission(
4334                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4335                    "canShowRequestPermissionRationale for user " + userId);
4336        }
4337
4338        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4339        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4340            return false;
4341        }
4342
4343        if (checkPermission(permissionName, packageName, userId)
4344                == PackageManager.PERMISSION_GRANTED) {
4345            return false;
4346        }
4347
4348        final int flags;
4349
4350        final long identity = Binder.clearCallingIdentity();
4351        try {
4352            flags = getPermissionFlags(permissionName,
4353                    packageName, userId);
4354        } finally {
4355            Binder.restoreCallingIdentity(identity);
4356        }
4357
4358        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4359                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4360                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4361
4362        if ((flags & fixedFlags) != 0) {
4363            return false;
4364        }
4365
4366        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4367    }
4368
4369    @Override
4370    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4371        mContext.enforceCallingOrSelfPermission(
4372                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4373                "addOnPermissionsChangeListener");
4374
4375        synchronized (mPackages) {
4376            mOnPermissionChangeListeners.addListenerLocked(listener);
4377        }
4378    }
4379
4380    @Override
4381    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4382        synchronized (mPackages) {
4383            mOnPermissionChangeListeners.removeListenerLocked(listener);
4384        }
4385    }
4386
4387    @Override
4388    public boolean isProtectedBroadcast(String actionName) {
4389        synchronized (mPackages) {
4390            if (mProtectedBroadcasts.contains(actionName)) {
4391                return true;
4392            } else if (actionName != null) {
4393                // TODO: remove these terrible hacks
4394                if (actionName.startsWith("android.net.netmon.lingerExpired")
4395                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4396                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4397                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4398                    return true;
4399                }
4400            }
4401        }
4402        return false;
4403    }
4404
4405    @Override
4406    public int checkSignatures(String pkg1, String pkg2) {
4407        synchronized (mPackages) {
4408            final PackageParser.Package p1 = mPackages.get(pkg1);
4409            final PackageParser.Package p2 = mPackages.get(pkg2);
4410            if (p1 == null || p1.mExtras == null
4411                    || p2 == null || p2.mExtras == null) {
4412                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4413            }
4414            return compareSignatures(p1.mSignatures, p2.mSignatures);
4415        }
4416    }
4417
4418    @Override
4419    public int checkUidSignatures(int uid1, int uid2) {
4420        // Map to base uids.
4421        uid1 = UserHandle.getAppId(uid1);
4422        uid2 = UserHandle.getAppId(uid2);
4423        // reader
4424        synchronized (mPackages) {
4425            Signature[] s1;
4426            Signature[] s2;
4427            Object obj = mSettings.getUserIdLPr(uid1);
4428            if (obj != null) {
4429                if (obj instanceof SharedUserSetting) {
4430                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4431                } else if (obj instanceof PackageSetting) {
4432                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4433                } else {
4434                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4435                }
4436            } else {
4437                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4438            }
4439            obj = mSettings.getUserIdLPr(uid2);
4440            if (obj != null) {
4441                if (obj instanceof SharedUserSetting) {
4442                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4443                } else if (obj instanceof PackageSetting) {
4444                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4445                } else {
4446                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4447                }
4448            } else {
4449                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4450            }
4451            return compareSignatures(s1, s2);
4452        }
4453    }
4454
4455    /**
4456     * This method should typically only be used when granting or revoking
4457     * permissions, since the app may immediately restart after this call.
4458     * <p>
4459     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4460     * guard your work against the app being relaunched.
4461     */
4462    private void killUid(int appId, int userId, String reason) {
4463        final long identity = Binder.clearCallingIdentity();
4464        try {
4465            IActivityManager am = ActivityManagerNative.getDefault();
4466            if (am != null) {
4467                try {
4468                    am.killUid(appId, userId, reason);
4469                } catch (RemoteException e) {
4470                    /* ignore - same process */
4471                }
4472            }
4473        } finally {
4474            Binder.restoreCallingIdentity(identity);
4475        }
4476    }
4477
4478    /**
4479     * Compares two sets of signatures. Returns:
4480     * <br />
4481     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4482     * <br />
4483     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4484     * <br />
4485     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4486     * <br />
4487     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4488     * <br />
4489     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4490     */
4491    static int compareSignatures(Signature[] s1, Signature[] s2) {
4492        if (s1 == null) {
4493            return s2 == null
4494                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4495                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4496        }
4497
4498        if (s2 == null) {
4499            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4500        }
4501
4502        if (s1.length != s2.length) {
4503            return PackageManager.SIGNATURE_NO_MATCH;
4504        }
4505
4506        // Since both signature sets are of size 1, we can compare without HashSets.
4507        if (s1.length == 1) {
4508            return s1[0].equals(s2[0]) ?
4509                    PackageManager.SIGNATURE_MATCH :
4510                    PackageManager.SIGNATURE_NO_MATCH;
4511        }
4512
4513        ArraySet<Signature> set1 = new ArraySet<Signature>();
4514        for (Signature sig : s1) {
4515            set1.add(sig);
4516        }
4517        ArraySet<Signature> set2 = new ArraySet<Signature>();
4518        for (Signature sig : s2) {
4519            set2.add(sig);
4520        }
4521        // Make sure s2 contains all signatures in s1.
4522        if (set1.equals(set2)) {
4523            return PackageManager.SIGNATURE_MATCH;
4524        }
4525        return PackageManager.SIGNATURE_NO_MATCH;
4526    }
4527
4528    /**
4529     * If the database version for this type of package (internal storage or
4530     * external storage) is less than the version where package signatures
4531     * were updated, return true.
4532     */
4533    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4534        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4535        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4536    }
4537
4538    /**
4539     * Used for backward compatibility to make sure any packages with
4540     * certificate chains get upgraded to the new style. {@code existingSigs}
4541     * will be in the old format (since they were stored on disk from before the
4542     * system upgrade) and {@code scannedSigs} will be in the newer format.
4543     */
4544    private int compareSignaturesCompat(PackageSignatures existingSigs,
4545            PackageParser.Package scannedPkg) {
4546        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4547            return PackageManager.SIGNATURE_NO_MATCH;
4548        }
4549
4550        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4551        for (Signature sig : existingSigs.mSignatures) {
4552            existingSet.add(sig);
4553        }
4554        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4555        for (Signature sig : scannedPkg.mSignatures) {
4556            try {
4557                Signature[] chainSignatures = sig.getChainSignatures();
4558                for (Signature chainSig : chainSignatures) {
4559                    scannedCompatSet.add(chainSig);
4560                }
4561            } catch (CertificateEncodingException e) {
4562                scannedCompatSet.add(sig);
4563            }
4564        }
4565        /*
4566         * Make sure the expanded scanned set contains all signatures in the
4567         * existing one.
4568         */
4569        if (scannedCompatSet.equals(existingSet)) {
4570            // Migrate the old signatures to the new scheme.
4571            existingSigs.assignSignatures(scannedPkg.mSignatures);
4572            // The new KeySets will be re-added later in the scanning process.
4573            synchronized (mPackages) {
4574                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4575            }
4576            return PackageManager.SIGNATURE_MATCH;
4577        }
4578        return PackageManager.SIGNATURE_NO_MATCH;
4579    }
4580
4581    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4582        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4583        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4584    }
4585
4586    private int compareSignaturesRecover(PackageSignatures existingSigs,
4587            PackageParser.Package scannedPkg) {
4588        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4589            return PackageManager.SIGNATURE_NO_MATCH;
4590        }
4591
4592        String msg = null;
4593        try {
4594            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4595                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4596                        + scannedPkg.packageName);
4597                return PackageManager.SIGNATURE_MATCH;
4598            }
4599        } catch (CertificateException e) {
4600            msg = e.getMessage();
4601        }
4602
4603        logCriticalInfo(Log.INFO,
4604                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4605        return PackageManager.SIGNATURE_NO_MATCH;
4606    }
4607
4608    @Override
4609    public List<String> getAllPackages() {
4610        synchronized (mPackages) {
4611            return new ArrayList<String>(mPackages.keySet());
4612        }
4613    }
4614
4615    @Override
4616    public String[] getPackagesForUid(int uid) {
4617        uid = UserHandle.getAppId(uid);
4618        // reader
4619        synchronized (mPackages) {
4620            Object obj = mSettings.getUserIdLPr(uid);
4621            if (obj instanceof SharedUserSetting) {
4622                final SharedUserSetting sus = (SharedUserSetting) obj;
4623                final int N = sus.packages.size();
4624                final String[] res = new String[N];
4625                for (int i = 0; i < N; i++) {
4626                    res[i] = sus.packages.valueAt(i).name;
4627                }
4628                return res;
4629            } else if (obj instanceof PackageSetting) {
4630                final PackageSetting ps = (PackageSetting) obj;
4631                return new String[] { ps.name };
4632            }
4633        }
4634        return null;
4635    }
4636
4637    @Override
4638    public String getNameForUid(int uid) {
4639        // reader
4640        synchronized (mPackages) {
4641            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4642            if (obj instanceof SharedUserSetting) {
4643                final SharedUserSetting sus = (SharedUserSetting) obj;
4644                return sus.name + ":" + sus.userId;
4645            } else if (obj instanceof PackageSetting) {
4646                final PackageSetting ps = (PackageSetting) obj;
4647                return ps.name;
4648            }
4649        }
4650        return null;
4651    }
4652
4653    @Override
4654    public int getUidForSharedUser(String sharedUserName) {
4655        if(sharedUserName == null) {
4656            return -1;
4657        }
4658        // reader
4659        synchronized (mPackages) {
4660            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4661            if (suid == null) {
4662                return -1;
4663            }
4664            return suid.userId;
4665        }
4666    }
4667
4668    @Override
4669    public int getFlagsForUid(int uid) {
4670        synchronized (mPackages) {
4671            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4672            if (obj instanceof SharedUserSetting) {
4673                final SharedUserSetting sus = (SharedUserSetting) obj;
4674                return sus.pkgFlags;
4675            } else if (obj instanceof PackageSetting) {
4676                final PackageSetting ps = (PackageSetting) obj;
4677                return ps.pkgFlags;
4678            }
4679        }
4680        return 0;
4681    }
4682
4683    @Override
4684    public int getPrivateFlagsForUid(int uid) {
4685        synchronized (mPackages) {
4686            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4687            if (obj instanceof SharedUserSetting) {
4688                final SharedUserSetting sus = (SharedUserSetting) obj;
4689                return sus.pkgPrivateFlags;
4690            } else if (obj instanceof PackageSetting) {
4691                final PackageSetting ps = (PackageSetting) obj;
4692                return ps.pkgPrivateFlags;
4693            }
4694        }
4695        return 0;
4696    }
4697
4698    @Override
4699    public boolean isUidPrivileged(int uid) {
4700        uid = UserHandle.getAppId(uid);
4701        // reader
4702        synchronized (mPackages) {
4703            Object obj = mSettings.getUserIdLPr(uid);
4704            if (obj instanceof SharedUserSetting) {
4705                final SharedUserSetting sus = (SharedUserSetting) obj;
4706                final Iterator<PackageSetting> it = sus.packages.iterator();
4707                while (it.hasNext()) {
4708                    if (it.next().isPrivileged()) {
4709                        return true;
4710                    }
4711                }
4712            } else if (obj instanceof PackageSetting) {
4713                final PackageSetting ps = (PackageSetting) obj;
4714                return ps.isPrivileged();
4715            }
4716        }
4717        return false;
4718    }
4719
4720    @Override
4721    public String[] getAppOpPermissionPackages(String permissionName) {
4722        synchronized (mPackages) {
4723            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4724            if (pkgs == null) {
4725                return null;
4726            }
4727            return pkgs.toArray(new String[pkgs.size()]);
4728        }
4729    }
4730
4731    @Override
4732    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4733            int flags, int userId) {
4734        try {
4735            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4736
4737            if (!sUserManager.exists(userId)) return null;
4738            flags = updateFlagsForResolve(flags, userId, intent);
4739            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4740                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4741
4742            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4743            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4744                    flags, userId);
4745            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4746
4747            final ResolveInfo bestChoice =
4748                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4749            return bestChoice;
4750        } finally {
4751            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4752        }
4753    }
4754
4755    @Override
4756    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4757            IntentFilter filter, int match, ComponentName activity) {
4758        final int userId = UserHandle.getCallingUserId();
4759        if (DEBUG_PREFERRED) {
4760            Log.v(TAG, "setLastChosenActivity intent=" + intent
4761                + " resolvedType=" + resolvedType
4762                + " flags=" + flags
4763                + " filter=" + filter
4764                + " match=" + match
4765                + " activity=" + activity);
4766            filter.dump(new PrintStreamPrinter(System.out), "    ");
4767        }
4768        intent.setComponent(null);
4769        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4770                userId);
4771        // Find any earlier preferred or last chosen entries and nuke them
4772        findPreferredActivity(intent, resolvedType,
4773                flags, query, 0, false, true, false, userId);
4774        // Add the new activity as the last chosen for this filter
4775        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4776                "Setting last chosen");
4777    }
4778
4779    @Override
4780    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4781        final int userId = UserHandle.getCallingUserId();
4782        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4783        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4784                userId);
4785        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4786                false, false, false, userId);
4787    }
4788
4789    private boolean isEphemeralAllowed(
4790            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4791            boolean skipPackageCheck) {
4792        // Short circuit and return early if possible.
4793        if (DISABLE_EPHEMERAL_APPS) {
4794            return false;
4795        }
4796        final int callingUser = UserHandle.getCallingUserId();
4797        if (callingUser != UserHandle.USER_SYSTEM) {
4798            return false;
4799        }
4800        if (mEphemeralResolverConnection == null) {
4801            return false;
4802        }
4803        if (intent.getComponent() != null) {
4804            return false;
4805        }
4806        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4807            return false;
4808        }
4809        if (!skipPackageCheck && intent.getPackage() != null) {
4810            return false;
4811        }
4812        final boolean isWebUri = hasWebURI(intent);
4813        if (!isWebUri || intent.getData().getHost() == null) {
4814            return false;
4815        }
4816        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4817        synchronized (mPackages) {
4818            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4819            for (int n = 0; n < count; n++) {
4820                ResolveInfo info = resolvedActivities.get(n);
4821                String packageName = info.activityInfo.packageName;
4822                PackageSetting ps = mSettings.mPackages.get(packageName);
4823                if (ps != null) {
4824                    // Try to get the status from User settings first
4825                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4826                    int status = (int) (packedStatus >> 32);
4827                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4828                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4829                        if (DEBUG_EPHEMERAL) {
4830                            Slog.v(TAG, "DENY ephemeral apps;"
4831                                + " pkg: " + packageName + ", status: " + status);
4832                        }
4833                        return false;
4834                    }
4835                }
4836            }
4837        }
4838        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4839        return true;
4840    }
4841
4842    private static EphemeralResolveInfo getEphemeralResolveInfo(
4843            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4844            String resolvedType, int userId, String packageName) {
4845        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4846                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4847        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4848                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4849        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4850                ephemeralPrefixCount);
4851        final int[] shaPrefix = digest.getDigestPrefix();
4852        final byte[][] digestBytes = digest.getDigestBytes();
4853        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4854                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4855        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4856            // No hash prefix match; there are no ephemeral apps for this domain.
4857            return null;
4858        }
4859
4860        // Go in reverse order so we match the narrowest scope first.
4861        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4862            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4863                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4864                    continue;
4865                }
4866                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4867                // No filters; this should never happen.
4868                if (filters.isEmpty()) {
4869                    continue;
4870                }
4871                if (packageName != null
4872                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4873                    continue;
4874                }
4875                // We have a domain match; resolve the filters to see if anything matches.
4876                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4877                for (int j = filters.size() - 1; j >= 0; --j) {
4878                    final EphemeralResolveIntentInfo intentInfo =
4879                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4880                    ephemeralResolver.addFilter(intentInfo);
4881                }
4882                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4883                        intent, resolvedType, false /*defaultOnly*/, userId);
4884                if (!matchedResolveInfoList.isEmpty()) {
4885                    return matchedResolveInfoList.get(0);
4886                }
4887            }
4888        }
4889        // Hash or filter mis-match; no ephemeral apps for this domain.
4890        return null;
4891    }
4892
4893    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4894            int flags, List<ResolveInfo> query, int userId) {
4895        if (query != null) {
4896            final int N = query.size();
4897            if (N == 1) {
4898                return query.get(0);
4899            } else if (N > 1) {
4900                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4901                // If there is more than one activity with the same priority,
4902                // then let the user decide between them.
4903                ResolveInfo r0 = query.get(0);
4904                ResolveInfo r1 = query.get(1);
4905                if (DEBUG_INTENT_MATCHING || debug) {
4906                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4907                            + r1.activityInfo.name + "=" + r1.priority);
4908                }
4909                // If the first activity has a higher priority, or a different
4910                // default, then it is always desirable to pick it.
4911                if (r0.priority != r1.priority
4912                        || r0.preferredOrder != r1.preferredOrder
4913                        || r0.isDefault != r1.isDefault) {
4914                    return query.get(0);
4915                }
4916                // If we have saved a preference for a preferred activity for
4917                // this Intent, use that.
4918                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4919                        flags, query, r0.priority, true, false, debug, userId);
4920                if (ri != null) {
4921                    return ri;
4922                }
4923                ri = new ResolveInfo(mResolveInfo);
4924                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4925                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4926                // If all of the options come from the same package, show the application's
4927                // label and icon instead of the generic resolver's.
4928                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4929                // and then throw away the ResolveInfo itself, meaning that the caller loses
4930                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4931                // a fallback for this case; we only set the target package's resources on
4932                // the ResolveInfo, not the ActivityInfo.
4933                final String intentPackage = intent.getPackage();
4934                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4935                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4936                    ri.resolvePackageName = intentPackage;
4937                    if (userNeedsBadging(userId)) {
4938                        ri.noResourceId = true;
4939                    } else {
4940                        ri.icon = appi.icon;
4941                    }
4942                    ri.iconResourceId = appi.icon;
4943                    ri.labelRes = appi.labelRes;
4944                }
4945                ri.activityInfo.applicationInfo = new ApplicationInfo(
4946                        ri.activityInfo.applicationInfo);
4947                if (userId != 0) {
4948                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4949                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4950                }
4951                // Make sure that the resolver is displayable in car mode
4952                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4953                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4954                return ri;
4955            }
4956        }
4957        return null;
4958    }
4959
4960    /**
4961     * Return true if the given list is not empty and all of its contents have
4962     * an activityInfo with the given package name.
4963     */
4964    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4965        if (ArrayUtils.isEmpty(list)) {
4966            return false;
4967        }
4968        for (int i = 0, N = list.size(); i < N; i++) {
4969            final ResolveInfo ri = list.get(i);
4970            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4971            if (ai == null || !packageName.equals(ai.packageName)) {
4972                return false;
4973            }
4974        }
4975        return true;
4976    }
4977
4978    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4979            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4980        final int N = query.size();
4981        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4982                .get(userId);
4983        // Get the list of persistent preferred activities that handle the intent
4984        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4985        List<PersistentPreferredActivity> pprefs = ppir != null
4986                ? ppir.queryIntent(intent, resolvedType,
4987                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4988                : null;
4989        if (pprefs != null && pprefs.size() > 0) {
4990            final int M = pprefs.size();
4991            for (int i=0; i<M; i++) {
4992                final PersistentPreferredActivity ppa = pprefs.get(i);
4993                if (DEBUG_PREFERRED || debug) {
4994                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4995                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4996                            + "\n  component=" + ppa.mComponent);
4997                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4998                }
4999                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5000                        flags | MATCH_DISABLED_COMPONENTS, userId);
5001                if (DEBUG_PREFERRED || debug) {
5002                    Slog.v(TAG, "Found persistent preferred activity:");
5003                    if (ai != null) {
5004                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5005                    } else {
5006                        Slog.v(TAG, "  null");
5007                    }
5008                }
5009                if (ai == null) {
5010                    // This previously registered persistent preferred activity
5011                    // component is no longer known. Ignore it and do NOT remove it.
5012                    continue;
5013                }
5014                for (int j=0; j<N; j++) {
5015                    final ResolveInfo ri = query.get(j);
5016                    if (!ri.activityInfo.applicationInfo.packageName
5017                            .equals(ai.applicationInfo.packageName)) {
5018                        continue;
5019                    }
5020                    if (!ri.activityInfo.name.equals(ai.name)) {
5021                        continue;
5022                    }
5023                    //  Found a persistent preference that can handle the intent.
5024                    if (DEBUG_PREFERRED || debug) {
5025                        Slog.v(TAG, "Returning persistent preferred activity: " +
5026                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5027                    }
5028                    return ri;
5029                }
5030            }
5031        }
5032        return null;
5033    }
5034
5035    // TODO: handle preferred activities missing while user has amnesia
5036    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5037            List<ResolveInfo> query, int priority, boolean always,
5038            boolean removeMatches, boolean debug, int userId) {
5039        if (!sUserManager.exists(userId)) return null;
5040        flags = updateFlagsForResolve(flags, userId, intent);
5041        // writer
5042        synchronized (mPackages) {
5043            if (intent.getSelector() != null) {
5044                intent = intent.getSelector();
5045            }
5046            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5047
5048            // Try to find a matching persistent preferred activity.
5049            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5050                    debug, userId);
5051
5052            // If a persistent preferred activity matched, use it.
5053            if (pri != null) {
5054                return pri;
5055            }
5056
5057            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5058            // Get the list of preferred activities that handle the intent
5059            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5060            List<PreferredActivity> prefs = pir != null
5061                    ? pir.queryIntent(intent, resolvedType,
5062                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5063                    : null;
5064            if (prefs != null && prefs.size() > 0) {
5065                boolean changed = false;
5066                try {
5067                    // First figure out how good the original match set is.
5068                    // We will only allow preferred activities that came
5069                    // from the same match quality.
5070                    int match = 0;
5071
5072                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5073
5074                    final int N = query.size();
5075                    for (int j=0; j<N; j++) {
5076                        final ResolveInfo ri = query.get(j);
5077                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5078                                + ": 0x" + Integer.toHexString(match));
5079                        if (ri.match > match) {
5080                            match = ri.match;
5081                        }
5082                    }
5083
5084                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5085                            + Integer.toHexString(match));
5086
5087                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5088                    final int M = prefs.size();
5089                    for (int i=0; i<M; i++) {
5090                        final PreferredActivity pa = prefs.get(i);
5091                        if (DEBUG_PREFERRED || debug) {
5092                            Slog.v(TAG, "Checking PreferredActivity ds="
5093                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5094                                    + "\n  component=" + pa.mPref.mComponent);
5095                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5096                        }
5097                        if (pa.mPref.mMatch != match) {
5098                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5099                                    + Integer.toHexString(pa.mPref.mMatch));
5100                            continue;
5101                        }
5102                        // If it's not an "always" type preferred activity and that's what we're
5103                        // looking for, skip it.
5104                        if (always && !pa.mPref.mAlways) {
5105                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5106                            continue;
5107                        }
5108                        final ActivityInfo ai = getActivityInfo(
5109                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5110                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5111                                userId);
5112                        if (DEBUG_PREFERRED || debug) {
5113                            Slog.v(TAG, "Found preferred activity:");
5114                            if (ai != null) {
5115                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5116                            } else {
5117                                Slog.v(TAG, "  null");
5118                            }
5119                        }
5120                        if (ai == null) {
5121                            // This previously registered preferred activity
5122                            // component is no longer known.  Most likely an update
5123                            // to the app was installed and in the new version this
5124                            // component no longer exists.  Clean it up by removing
5125                            // it from the preferred activities list, and skip it.
5126                            Slog.w(TAG, "Removing dangling preferred activity: "
5127                                    + pa.mPref.mComponent);
5128                            pir.removeFilter(pa);
5129                            changed = true;
5130                            continue;
5131                        }
5132                        for (int j=0; j<N; j++) {
5133                            final ResolveInfo ri = query.get(j);
5134                            if (!ri.activityInfo.applicationInfo.packageName
5135                                    .equals(ai.applicationInfo.packageName)) {
5136                                continue;
5137                            }
5138                            if (!ri.activityInfo.name.equals(ai.name)) {
5139                                continue;
5140                            }
5141
5142                            if (removeMatches) {
5143                                pir.removeFilter(pa);
5144                                changed = true;
5145                                if (DEBUG_PREFERRED) {
5146                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5147                                }
5148                                break;
5149                            }
5150
5151                            // Okay we found a previously set preferred or last chosen app.
5152                            // If the result set is different from when this
5153                            // was created, we need to clear it and re-ask the
5154                            // user their preference, if we're looking for an "always" type entry.
5155                            if (always && !pa.mPref.sameSet(query)) {
5156                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5157                                        + intent + " type " + resolvedType);
5158                                if (DEBUG_PREFERRED) {
5159                                    Slog.v(TAG, "Removing preferred activity since set changed "
5160                                            + pa.mPref.mComponent);
5161                                }
5162                                pir.removeFilter(pa);
5163                                // Re-add the filter as a "last chosen" entry (!always)
5164                                PreferredActivity lastChosen = new PreferredActivity(
5165                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5166                                pir.addFilter(lastChosen);
5167                                changed = true;
5168                                return null;
5169                            }
5170
5171                            // Yay! Either the set matched or we're looking for the last chosen
5172                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5173                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5174                            return ri;
5175                        }
5176                    }
5177                } finally {
5178                    if (changed) {
5179                        if (DEBUG_PREFERRED) {
5180                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5181                        }
5182                        scheduleWritePackageRestrictionsLocked(userId);
5183                    }
5184                }
5185            }
5186        }
5187        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5188        return null;
5189    }
5190
5191    /*
5192     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5193     */
5194    @Override
5195    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5196            int targetUserId) {
5197        mContext.enforceCallingOrSelfPermission(
5198                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5199        List<CrossProfileIntentFilter> matches =
5200                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5201        if (matches != null) {
5202            int size = matches.size();
5203            for (int i = 0; i < size; i++) {
5204                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5205            }
5206        }
5207        if (hasWebURI(intent)) {
5208            // cross-profile app linking works only towards the parent.
5209            final UserInfo parent = getProfileParent(sourceUserId);
5210            synchronized(mPackages) {
5211                int flags = updateFlagsForResolve(0, parent.id, intent);
5212                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5213                        intent, resolvedType, flags, sourceUserId, parent.id);
5214                return xpDomainInfo != null;
5215            }
5216        }
5217        return false;
5218    }
5219
5220    private UserInfo getProfileParent(int userId) {
5221        final long identity = Binder.clearCallingIdentity();
5222        try {
5223            return sUserManager.getProfileParent(userId);
5224        } finally {
5225            Binder.restoreCallingIdentity(identity);
5226        }
5227    }
5228
5229    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5230            String resolvedType, int userId) {
5231        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5232        if (resolver != null) {
5233            return resolver.queryIntent(intent, resolvedType, false, userId);
5234        }
5235        return null;
5236    }
5237
5238    @Override
5239    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5240            String resolvedType, int flags, int userId) {
5241        try {
5242            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5243
5244            return new ParceledListSlice<>(
5245                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5246        } finally {
5247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5248        }
5249    }
5250
5251    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5252            String resolvedType, int flags, int userId) {
5253        if (!sUserManager.exists(userId)) return Collections.emptyList();
5254        flags = updateFlagsForResolve(flags, userId, intent);
5255        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5256                false /* requireFullPermission */, false /* checkShell */,
5257                "query intent activities");
5258        ComponentName comp = intent.getComponent();
5259        if (comp == null) {
5260            if (intent.getSelector() != null) {
5261                intent = intent.getSelector();
5262                comp = intent.getComponent();
5263            }
5264        }
5265
5266        if (comp != null) {
5267            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5268            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5269            if (ai != null) {
5270                final ResolveInfo ri = new ResolveInfo();
5271                ri.activityInfo = ai;
5272                list.add(ri);
5273            }
5274            return list;
5275        }
5276
5277        // reader
5278        boolean sortResult = false;
5279        boolean addEphemeral = false;
5280        boolean matchEphemeralPackage = false;
5281        List<ResolveInfo> result;
5282        final String pkgName = intent.getPackage();
5283        synchronized (mPackages) {
5284            if (pkgName == null) {
5285                List<CrossProfileIntentFilter> matchingFilters =
5286                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5287                // Check for results that need to skip the current profile.
5288                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5289                        resolvedType, flags, userId);
5290                if (xpResolveInfo != null) {
5291                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5292                    xpResult.add(xpResolveInfo);
5293                    return filterIfNotSystemUser(xpResult, userId);
5294                }
5295
5296                // Check for results in the current profile.
5297                result = filterIfNotSystemUser(mActivities.queryIntent(
5298                        intent, resolvedType, flags, userId), userId);
5299                addEphemeral =
5300                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5301
5302                // Check for cross profile results.
5303                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5304                xpResolveInfo = queryCrossProfileIntents(
5305                        matchingFilters, intent, resolvedType, flags, userId,
5306                        hasNonNegativePriorityResult);
5307                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5308                    boolean isVisibleToUser = filterIfNotSystemUser(
5309                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5310                    if (isVisibleToUser) {
5311                        result.add(xpResolveInfo);
5312                        sortResult = true;
5313                    }
5314                }
5315                if (hasWebURI(intent)) {
5316                    CrossProfileDomainInfo xpDomainInfo = null;
5317                    final UserInfo parent = getProfileParent(userId);
5318                    if (parent != null) {
5319                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5320                                flags, userId, parent.id);
5321                    }
5322                    if (xpDomainInfo != null) {
5323                        if (xpResolveInfo != null) {
5324                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5325                            // in the result.
5326                            result.remove(xpResolveInfo);
5327                        }
5328                        if (result.size() == 0 && !addEphemeral) {
5329                            result.add(xpDomainInfo.resolveInfo);
5330                            return result;
5331                        }
5332                    }
5333                    if (result.size() > 1 || addEphemeral) {
5334                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5335                                intent, flags, result, xpDomainInfo, userId);
5336                        sortResult = true;
5337                    }
5338                }
5339            } else {
5340                final PackageParser.Package pkg = mPackages.get(pkgName);
5341                if (pkg != null) {
5342                    result = filterIfNotSystemUser(
5343                            mActivities.queryIntentForPackage(
5344                                    intent, resolvedType, flags, pkg.activities, userId),
5345                            userId);
5346                } else {
5347                    // the caller wants to resolve for a particular package; however, there
5348                    // were no installed results, so, try to find an ephemeral result
5349                    addEphemeral = isEphemeralAllowed(
5350                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5351                    matchEphemeralPackage = true;
5352                    result = new ArrayList<ResolveInfo>();
5353                }
5354            }
5355        }
5356        if (addEphemeral) {
5357            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5358            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5359                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5360                    matchEphemeralPackage ? pkgName : null);
5361            if (ai != null) {
5362                if (DEBUG_EPHEMERAL) {
5363                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5364                }
5365                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5366                ephemeralInstaller.ephemeralResolveInfo = ai;
5367                // make sure this resolver is the default
5368                ephemeralInstaller.isDefault = true;
5369                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5370                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5371                // add a non-generic filter
5372                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5373                ephemeralInstaller.filter.addDataPath(
5374                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5375                result.add(ephemeralInstaller);
5376            }
5377            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5378        }
5379        if (sortResult) {
5380            Collections.sort(result, mResolvePrioritySorter);
5381        }
5382        return result;
5383    }
5384
5385    private static class CrossProfileDomainInfo {
5386        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5387        ResolveInfo resolveInfo;
5388        /* Best domain verification status of the activities found in the other profile */
5389        int bestDomainVerificationStatus;
5390    }
5391
5392    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5393            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5394        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5395                sourceUserId)) {
5396            return null;
5397        }
5398        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5399                resolvedType, flags, parentUserId);
5400
5401        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5402            return null;
5403        }
5404        CrossProfileDomainInfo result = null;
5405        int size = resultTargetUser.size();
5406        for (int i = 0; i < size; i++) {
5407            ResolveInfo riTargetUser = resultTargetUser.get(i);
5408            // Intent filter verification is only for filters that specify a host. So don't return
5409            // those that handle all web uris.
5410            if (riTargetUser.handleAllWebDataURI) {
5411                continue;
5412            }
5413            String packageName = riTargetUser.activityInfo.packageName;
5414            PackageSetting ps = mSettings.mPackages.get(packageName);
5415            if (ps == null) {
5416                continue;
5417            }
5418            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5419            int status = (int)(verificationState >> 32);
5420            if (result == null) {
5421                result = new CrossProfileDomainInfo();
5422                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5423                        sourceUserId, parentUserId);
5424                result.bestDomainVerificationStatus = status;
5425            } else {
5426                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5427                        result.bestDomainVerificationStatus);
5428            }
5429        }
5430        // Don't consider matches with status NEVER across profiles.
5431        if (result != null && result.bestDomainVerificationStatus
5432                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5433            return null;
5434        }
5435        return result;
5436    }
5437
5438    /**
5439     * Verification statuses are ordered from the worse to the best, except for
5440     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5441     */
5442    private int bestDomainVerificationStatus(int status1, int status2) {
5443        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5444            return status2;
5445        }
5446        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5447            return status1;
5448        }
5449        return (int) MathUtils.max(status1, status2);
5450    }
5451
5452    private boolean isUserEnabled(int userId) {
5453        long callingId = Binder.clearCallingIdentity();
5454        try {
5455            UserInfo userInfo = sUserManager.getUserInfo(userId);
5456            return userInfo != null && userInfo.isEnabled();
5457        } finally {
5458            Binder.restoreCallingIdentity(callingId);
5459        }
5460    }
5461
5462    /**
5463     * Filter out activities with systemUserOnly flag set, when current user is not System.
5464     *
5465     * @return filtered list
5466     */
5467    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5468        if (userId == UserHandle.USER_SYSTEM) {
5469            return resolveInfos;
5470        }
5471        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5472            ResolveInfo info = resolveInfos.get(i);
5473            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5474                resolveInfos.remove(i);
5475            }
5476        }
5477        return resolveInfos;
5478    }
5479
5480    /**
5481     * @param resolveInfos list of resolve infos in descending priority order
5482     * @return if the list contains a resolve info with non-negative priority
5483     */
5484    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5485        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5486    }
5487
5488    private static boolean hasWebURI(Intent intent) {
5489        if (intent.getData() == null) {
5490            return false;
5491        }
5492        final String scheme = intent.getScheme();
5493        if (TextUtils.isEmpty(scheme)) {
5494            return false;
5495        }
5496        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5497    }
5498
5499    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5500            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5501            int userId) {
5502        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5503
5504        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5505            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5506                    candidates.size());
5507        }
5508
5509        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5510        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5511        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5512        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5513        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5514        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5515
5516        synchronized (mPackages) {
5517            final int count = candidates.size();
5518            // First, try to use linked apps. Partition the candidates into four lists:
5519            // one for the final results, one for the "do not use ever", one for "undefined status"
5520            // and finally one for "browser app type".
5521            for (int n=0; n<count; n++) {
5522                ResolveInfo info = candidates.get(n);
5523                String packageName = info.activityInfo.packageName;
5524                PackageSetting ps = mSettings.mPackages.get(packageName);
5525                if (ps != null) {
5526                    // Add to the special match all list (Browser use case)
5527                    if (info.handleAllWebDataURI) {
5528                        matchAllList.add(info);
5529                        continue;
5530                    }
5531                    // Try to get the status from User settings first
5532                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5533                    int status = (int)(packedStatus >> 32);
5534                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5535                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5536                        if (DEBUG_DOMAIN_VERIFICATION) {
5537                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5538                                    + " : linkgen=" + linkGeneration);
5539                        }
5540                        // Use link-enabled generation as preferredOrder, i.e.
5541                        // prefer newly-enabled over earlier-enabled.
5542                        info.preferredOrder = linkGeneration;
5543                        alwaysList.add(info);
5544                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5545                        if (DEBUG_DOMAIN_VERIFICATION) {
5546                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5547                        }
5548                        neverList.add(info);
5549                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5550                        if (DEBUG_DOMAIN_VERIFICATION) {
5551                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5552                        }
5553                        alwaysAskList.add(info);
5554                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5555                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5556                        if (DEBUG_DOMAIN_VERIFICATION) {
5557                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5558                        }
5559                        undefinedList.add(info);
5560                    }
5561                }
5562            }
5563
5564            // We'll want to include browser possibilities in a few cases
5565            boolean includeBrowser = false;
5566
5567            // First try to add the "always" resolution(s) for the current user, if any
5568            if (alwaysList.size() > 0) {
5569                result.addAll(alwaysList);
5570            } else {
5571                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5572                result.addAll(undefinedList);
5573                // Maybe add one for the other profile.
5574                if (xpDomainInfo != null && (
5575                        xpDomainInfo.bestDomainVerificationStatus
5576                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5577                    result.add(xpDomainInfo.resolveInfo);
5578                }
5579                includeBrowser = true;
5580            }
5581
5582            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5583            // If there were 'always' entries their preferred order has been set, so we also
5584            // back that off to make the alternatives equivalent
5585            if (alwaysAskList.size() > 0) {
5586                for (ResolveInfo i : result) {
5587                    i.preferredOrder = 0;
5588                }
5589                result.addAll(alwaysAskList);
5590                includeBrowser = true;
5591            }
5592
5593            if (includeBrowser) {
5594                // Also add browsers (all of them or only the default one)
5595                if (DEBUG_DOMAIN_VERIFICATION) {
5596                    Slog.v(TAG, "   ...including browsers in candidate set");
5597                }
5598                if ((matchFlags & MATCH_ALL) != 0) {
5599                    result.addAll(matchAllList);
5600                } else {
5601                    // Browser/generic handling case.  If there's a default browser, go straight
5602                    // to that (but only if there is no other higher-priority match).
5603                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5604                    int maxMatchPrio = 0;
5605                    ResolveInfo defaultBrowserMatch = null;
5606                    final int numCandidates = matchAllList.size();
5607                    for (int n = 0; n < numCandidates; n++) {
5608                        ResolveInfo info = matchAllList.get(n);
5609                        // track the highest overall match priority...
5610                        if (info.priority > maxMatchPrio) {
5611                            maxMatchPrio = info.priority;
5612                        }
5613                        // ...and the highest-priority default browser match
5614                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5615                            if (defaultBrowserMatch == null
5616                                    || (defaultBrowserMatch.priority < info.priority)) {
5617                                if (debug) {
5618                                    Slog.v(TAG, "Considering default browser match " + info);
5619                                }
5620                                defaultBrowserMatch = info;
5621                            }
5622                        }
5623                    }
5624                    if (defaultBrowserMatch != null
5625                            && defaultBrowserMatch.priority >= maxMatchPrio
5626                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5627                    {
5628                        if (debug) {
5629                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5630                        }
5631                        result.add(defaultBrowserMatch);
5632                    } else {
5633                        result.addAll(matchAllList);
5634                    }
5635                }
5636
5637                // If there is nothing selected, add all candidates and remove the ones that the user
5638                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5639                if (result.size() == 0) {
5640                    result.addAll(candidates);
5641                    result.removeAll(neverList);
5642                }
5643            }
5644        }
5645        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5646            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5647                    result.size());
5648            for (ResolveInfo info : result) {
5649                Slog.v(TAG, "  + " + info.activityInfo);
5650            }
5651        }
5652        return result;
5653    }
5654
5655    // Returns a packed value as a long:
5656    //
5657    // high 'int'-sized word: link status: undefined/ask/never/always.
5658    // low 'int'-sized word: relative priority among 'always' results.
5659    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5660        long result = ps.getDomainVerificationStatusForUser(userId);
5661        // if none available, get the master status
5662        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5663            if (ps.getIntentFilterVerificationInfo() != null) {
5664                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5665            }
5666        }
5667        return result;
5668    }
5669
5670    private ResolveInfo querySkipCurrentProfileIntents(
5671            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5672            int flags, int sourceUserId) {
5673        if (matchingFilters != null) {
5674            int size = matchingFilters.size();
5675            for (int i = 0; i < size; i ++) {
5676                CrossProfileIntentFilter filter = matchingFilters.get(i);
5677                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5678                    // Checking if there are activities in the target user that can handle the
5679                    // intent.
5680                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5681                            resolvedType, flags, sourceUserId);
5682                    if (resolveInfo != null) {
5683                        return resolveInfo;
5684                    }
5685                }
5686            }
5687        }
5688        return null;
5689    }
5690
5691    // Return matching ResolveInfo in target user if any.
5692    private ResolveInfo queryCrossProfileIntents(
5693            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5694            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5695        if (matchingFilters != null) {
5696            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5697            // match the same intent. For performance reasons, it is better not to
5698            // run queryIntent twice for the same userId
5699            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5700            int size = matchingFilters.size();
5701            for (int i = 0; i < size; i++) {
5702                CrossProfileIntentFilter filter = matchingFilters.get(i);
5703                int targetUserId = filter.getTargetUserId();
5704                boolean skipCurrentProfile =
5705                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5706                boolean skipCurrentProfileIfNoMatchFound =
5707                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5708                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5709                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5710                    // Checking if there are activities in the target user that can handle the
5711                    // intent.
5712                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5713                            resolvedType, flags, sourceUserId);
5714                    if (resolveInfo != null) return resolveInfo;
5715                    alreadyTriedUserIds.put(targetUserId, true);
5716                }
5717            }
5718        }
5719        return null;
5720    }
5721
5722    /**
5723     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5724     * will forward the intent to the filter's target user.
5725     * Otherwise, returns null.
5726     */
5727    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5728            String resolvedType, int flags, int sourceUserId) {
5729        int targetUserId = filter.getTargetUserId();
5730        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5731                resolvedType, flags, targetUserId);
5732        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5733            // If all the matches in the target profile are suspended, return null.
5734            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5735                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5736                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5737                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5738                            targetUserId);
5739                }
5740            }
5741        }
5742        return null;
5743    }
5744
5745    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5746            int sourceUserId, int targetUserId) {
5747        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5748        long ident = Binder.clearCallingIdentity();
5749        boolean targetIsProfile;
5750        try {
5751            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5752        } finally {
5753            Binder.restoreCallingIdentity(ident);
5754        }
5755        String className;
5756        if (targetIsProfile) {
5757            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5758        } else {
5759            className = FORWARD_INTENT_TO_PARENT;
5760        }
5761        ComponentName forwardingActivityComponentName = new ComponentName(
5762                mAndroidApplication.packageName, className);
5763        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5764                sourceUserId);
5765        if (!targetIsProfile) {
5766            forwardingActivityInfo.showUserIcon = targetUserId;
5767            forwardingResolveInfo.noResourceId = true;
5768        }
5769        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5770        forwardingResolveInfo.priority = 0;
5771        forwardingResolveInfo.preferredOrder = 0;
5772        forwardingResolveInfo.match = 0;
5773        forwardingResolveInfo.isDefault = true;
5774        forwardingResolveInfo.filter = filter;
5775        forwardingResolveInfo.targetUserId = targetUserId;
5776        return forwardingResolveInfo;
5777    }
5778
5779    @Override
5780    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5781            Intent[] specifics, String[] specificTypes, Intent intent,
5782            String resolvedType, int flags, int userId) {
5783        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5784                specificTypes, intent, resolvedType, flags, userId));
5785    }
5786
5787    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5788            Intent[] specifics, String[] specificTypes, Intent intent,
5789            String resolvedType, int flags, int userId) {
5790        if (!sUserManager.exists(userId)) return Collections.emptyList();
5791        flags = updateFlagsForResolve(flags, userId, intent);
5792        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5793                false /* requireFullPermission */, false /* checkShell */,
5794                "query intent activity options");
5795        final String resultsAction = intent.getAction();
5796
5797        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5798                | PackageManager.GET_RESOLVED_FILTER, userId);
5799
5800        if (DEBUG_INTENT_MATCHING) {
5801            Log.v(TAG, "Query " + intent + ": " + results);
5802        }
5803
5804        int specificsPos = 0;
5805        int N;
5806
5807        // todo: note that the algorithm used here is O(N^2).  This
5808        // isn't a problem in our current environment, but if we start running
5809        // into situations where we have more than 5 or 10 matches then this
5810        // should probably be changed to something smarter...
5811
5812        // First we go through and resolve each of the specific items
5813        // that were supplied, taking care of removing any corresponding
5814        // duplicate items in the generic resolve list.
5815        if (specifics != null) {
5816            for (int i=0; i<specifics.length; i++) {
5817                final Intent sintent = specifics[i];
5818                if (sintent == null) {
5819                    continue;
5820                }
5821
5822                if (DEBUG_INTENT_MATCHING) {
5823                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5824                }
5825
5826                String action = sintent.getAction();
5827                if (resultsAction != null && resultsAction.equals(action)) {
5828                    // If this action was explicitly requested, then don't
5829                    // remove things that have it.
5830                    action = null;
5831                }
5832
5833                ResolveInfo ri = null;
5834                ActivityInfo ai = null;
5835
5836                ComponentName comp = sintent.getComponent();
5837                if (comp == null) {
5838                    ri = resolveIntent(
5839                        sintent,
5840                        specificTypes != null ? specificTypes[i] : null,
5841                            flags, userId);
5842                    if (ri == null) {
5843                        continue;
5844                    }
5845                    if (ri == mResolveInfo) {
5846                        // ACK!  Must do something better with this.
5847                    }
5848                    ai = ri.activityInfo;
5849                    comp = new ComponentName(ai.applicationInfo.packageName,
5850                            ai.name);
5851                } else {
5852                    ai = getActivityInfo(comp, flags, userId);
5853                    if (ai == null) {
5854                        continue;
5855                    }
5856                }
5857
5858                // Look for any generic query activities that are duplicates
5859                // of this specific one, and remove them from the results.
5860                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5861                N = results.size();
5862                int j;
5863                for (j=specificsPos; j<N; j++) {
5864                    ResolveInfo sri = results.get(j);
5865                    if ((sri.activityInfo.name.equals(comp.getClassName())
5866                            && sri.activityInfo.applicationInfo.packageName.equals(
5867                                    comp.getPackageName()))
5868                        || (action != null && sri.filter.matchAction(action))) {
5869                        results.remove(j);
5870                        if (DEBUG_INTENT_MATCHING) Log.v(
5871                            TAG, "Removing duplicate item from " + j
5872                            + " due to specific " + specificsPos);
5873                        if (ri == null) {
5874                            ri = sri;
5875                        }
5876                        j--;
5877                        N--;
5878                    }
5879                }
5880
5881                // Add this specific item to its proper place.
5882                if (ri == null) {
5883                    ri = new ResolveInfo();
5884                    ri.activityInfo = ai;
5885                }
5886                results.add(specificsPos, ri);
5887                ri.specificIndex = i;
5888                specificsPos++;
5889            }
5890        }
5891
5892        // Now we go through the remaining generic results and remove any
5893        // duplicate actions that are found here.
5894        N = results.size();
5895        for (int i=specificsPos; i<N-1; i++) {
5896            final ResolveInfo rii = results.get(i);
5897            if (rii.filter == null) {
5898                continue;
5899            }
5900
5901            // Iterate over all of the actions of this result's intent
5902            // filter...  typically this should be just one.
5903            final Iterator<String> it = rii.filter.actionsIterator();
5904            if (it == null) {
5905                continue;
5906            }
5907            while (it.hasNext()) {
5908                final String action = it.next();
5909                if (resultsAction != null && resultsAction.equals(action)) {
5910                    // If this action was explicitly requested, then don't
5911                    // remove things that have it.
5912                    continue;
5913                }
5914                for (int j=i+1; j<N; j++) {
5915                    final ResolveInfo rij = results.get(j);
5916                    if (rij.filter != null && rij.filter.hasAction(action)) {
5917                        results.remove(j);
5918                        if (DEBUG_INTENT_MATCHING) Log.v(
5919                            TAG, "Removing duplicate item from " + j
5920                            + " due to action " + action + " at " + i);
5921                        j--;
5922                        N--;
5923                    }
5924                }
5925            }
5926
5927            // If the caller didn't request filter information, drop it now
5928            // so we don't have to marshall/unmarshall it.
5929            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5930                rii.filter = null;
5931            }
5932        }
5933
5934        // Filter out the caller activity if so requested.
5935        if (caller != null) {
5936            N = results.size();
5937            for (int i=0; i<N; i++) {
5938                ActivityInfo ainfo = results.get(i).activityInfo;
5939                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5940                        && caller.getClassName().equals(ainfo.name)) {
5941                    results.remove(i);
5942                    break;
5943                }
5944            }
5945        }
5946
5947        // If the caller didn't request filter information,
5948        // drop them now so we don't have to
5949        // marshall/unmarshall it.
5950        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5951            N = results.size();
5952            for (int i=0; i<N; i++) {
5953                results.get(i).filter = null;
5954            }
5955        }
5956
5957        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5958        return results;
5959    }
5960
5961    @Override
5962    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5963            String resolvedType, int flags, int userId) {
5964        return new ParceledListSlice<>(
5965                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5966    }
5967
5968    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5969            String resolvedType, int flags, int userId) {
5970        if (!sUserManager.exists(userId)) return Collections.emptyList();
5971        flags = updateFlagsForResolve(flags, userId, intent);
5972        ComponentName comp = intent.getComponent();
5973        if (comp == null) {
5974            if (intent.getSelector() != null) {
5975                intent = intent.getSelector();
5976                comp = intent.getComponent();
5977            }
5978        }
5979        if (comp != null) {
5980            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5981            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5982            if (ai != null) {
5983                ResolveInfo ri = new ResolveInfo();
5984                ri.activityInfo = ai;
5985                list.add(ri);
5986            }
5987            return list;
5988        }
5989
5990        // reader
5991        synchronized (mPackages) {
5992            String pkgName = intent.getPackage();
5993            if (pkgName == null) {
5994                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5995            }
5996            final PackageParser.Package pkg = mPackages.get(pkgName);
5997            if (pkg != null) {
5998                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5999                        userId);
6000            }
6001            return Collections.emptyList();
6002        }
6003    }
6004
6005    @Override
6006    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6007        if (!sUserManager.exists(userId)) return null;
6008        flags = updateFlagsForResolve(flags, userId, intent);
6009        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6010        if (query != null) {
6011            if (query.size() >= 1) {
6012                // If there is more than one service with the same priority,
6013                // just arbitrarily pick the first one.
6014                return query.get(0);
6015            }
6016        }
6017        return null;
6018    }
6019
6020    @Override
6021    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6022            String resolvedType, int flags, int userId) {
6023        return new ParceledListSlice<>(
6024                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6025    }
6026
6027    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6028            String resolvedType, int flags, int userId) {
6029        if (!sUserManager.exists(userId)) return Collections.emptyList();
6030        flags = updateFlagsForResolve(flags, userId, intent);
6031        ComponentName comp = intent.getComponent();
6032        if (comp == null) {
6033            if (intent.getSelector() != null) {
6034                intent = intent.getSelector();
6035                comp = intent.getComponent();
6036            }
6037        }
6038        if (comp != null) {
6039            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6040            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6041            if (si != null) {
6042                final ResolveInfo ri = new ResolveInfo();
6043                ri.serviceInfo = si;
6044                list.add(ri);
6045            }
6046            return list;
6047        }
6048
6049        // reader
6050        synchronized (mPackages) {
6051            String pkgName = intent.getPackage();
6052            if (pkgName == null) {
6053                return mServices.queryIntent(intent, resolvedType, flags, userId);
6054            }
6055            final PackageParser.Package pkg = mPackages.get(pkgName);
6056            if (pkg != null) {
6057                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6058                        userId);
6059            }
6060            return Collections.emptyList();
6061        }
6062    }
6063
6064    @Override
6065    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6066            String resolvedType, int flags, int userId) {
6067        return new ParceledListSlice<>(
6068                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6069    }
6070
6071    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6072            Intent intent, String resolvedType, int flags, int userId) {
6073        if (!sUserManager.exists(userId)) return Collections.emptyList();
6074        flags = updateFlagsForResolve(flags, userId, intent);
6075        ComponentName comp = intent.getComponent();
6076        if (comp == null) {
6077            if (intent.getSelector() != null) {
6078                intent = intent.getSelector();
6079                comp = intent.getComponent();
6080            }
6081        }
6082        if (comp != null) {
6083            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6084            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6085            if (pi != null) {
6086                final ResolveInfo ri = new ResolveInfo();
6087                ri.providerInfo = pi;
6088                list.add(ri);
6089            }
6090            return list;
6091        }
6092
6093        // reader
6094        synchronized (mPackages) {
6095            String pkgName = intent.getPackage();
6096            if (pkgName == null) {
6097                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6098            }
6099            final PackageParser.Package pkg = mPackages.get(pkgName);
6100            if (pkg != null) {
6101                return mProviders.queryIntentForPackage(
6102                        intent, resolvedType, flags, pkg.providers, userId);
6103            }
6104            return Collections.emptyList();
6105        }
6106    }
6107
6108    @Override
6109    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6110        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6111        flags = updateFlagsForPackage(flags, userId, null);
6112        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6113        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6114                true /* requireFullPermission */, false /* checkShell */,
6115                "get installed packages");
6116
6117        // writer
6118        synchronized (mPackages) {
6119            ArrayList<PackageInfo> list;
6120            if (listUninstalled) {
6121                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6122                for (PackageSetting ps : mSettings.mPackages.values()) {
6123                    final PackageInfo pi;
6124                    if (ps.pkg != null) {
6125                        pi = generatePackageInfo(ps, flags, userId);
6126                    } else {
6127                        pi = generatePackageInfo(ps, flags, userId);
6128                    }
6129                    if (pi != null) {
6130                        list.add(pi);
6131                    }
6132                }
6133            } else {
6134                list = new ArrayList<PackageInfo>(mPackages.size());
6135                for (PackageParser.Package p : mPackages.values()) {
6136                    final PackageInfo pi =
6137                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6138                    if (pi != null) {
6139                        list.add(pi);
6140                    }
6141                }
6142            }
6143
6144            return new ParceledListSlice<PackageInfo>(list);
6145        }
6146    }
6147
6148    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6149            String[] permissions, boolean[] tmp, int flags, int userId) {
6150        int numMatch = 0;
6151        final PermissionsState permissionsState = ps.getPermissionsState();
6152        for (int i=0; i<permissions.length; i++) {
6153            final String permission = permissions[i];
6154            if (permissionsState.hasPermission(permission, userId)) {
6155                tmp[i] = true;
6156                numMatch++;
6157            } else {
6158                tmp[i] = false;
6159            }
6160        }
6161        if (numMatch == 0) {
6162            return;
6163        }
6164        final PackageInfo pi;
6165        if (ps.pkg != null) {
6166            pi = generatePackageInfo(ps, flags, userId);
6167        } else {
6168            pi = generatePackageInfo(ps, flags, userId);
6169        }
6170        // The above might return null in cases of uninstalled apps or install-state
6171        // skew across users/profiles.
6172        if (pi != null) {
6173            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6174                if (numMatch == permissions.length) {
6175                    pi.requestedPermissions = permissions;
6176                } else {
6177                    pi.requestedPermissions = new String[numMatch];
6178                    numMatch = 0;
6179                    for (int i=0; i<permissions.length; i++) {
6180                        if (tmp[i]) {
6181                            pi.requestedPermissions[numMatch] = permissions[i];
6182                            numMatch++;
6183                        }
6184                    }
6185                }
6186            }
6187            list.add(pi);
6188        }
6189    }
6190
6191    @Override
6192    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6193            String[] permissions, int flags, int userId) {
6194        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6195        flags = updateFlagsForPackage(flags, userId, permissions);
6196        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6197
6198        // writer
6199        synchronized (mPackages) {
6200            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6201            boolean[] tmpBools = new boolean[permissions.length];
6202            if (listUninstalled) {
6203                for (PackageSetting ps : mSettings.mPackages.values()) {
6204                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6205                }
6206            } else {
6207                for (PackageParser.Package pkg : mPackages.values()) {
6208                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6209                    if (ps != null) {
6210                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6211                                userId);
6212                    }
6213                }
6214            }
6215
6216            return new ParceledListSlice<PackageInfo>(list);
6217        }
6218    }
6219
6220    @Override
6221    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6222        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6223        flags = updateFlagsForApplication(flags, userId, null);
6224        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6225
6226        // writer
6227        synchronized (mPackages) {
6228            ArrayList<ApplicationInfo> list;
6229            if (listUninstalled) {
6230                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6231                for (PackageSetting ps : mSettings.mPackages.values()) {
6232                    ApplicationInfo ai;
6233                    if (ps.pkg != null) {
6234                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6235                                ps.readUserState(userId), userId);
6236                    } else {
6237                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6238                    }
6239                    if (ai != null) {
6240                        list.add(ai);
6241                    }
6242                }
6243            } else {
6244                list = new ArrayList<ApplicationInfo>(mPackages.size());
6245                for (PackageParser.Package p : mPackages.values()) {
6246                    if (p.mExtras != null) {
6247                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6248                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6249                        if (ai != null) {
6250                            list.add(ai);
6251                        }
6252                    }
6253                }
6254            }
6255
6256            return new ParceledListSlice<ApplicationInfo>(list);
6257        }
6258    }
6259
6260    @Override
6261    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6262        if (DISABLE_EPHEMERAL_APPS) {
6263            return null;
6264        }
6265
6266        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6267                "getEphemeralApplications");
6268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6269                true /* requireFullPermission */, false /* checkShell */,
6270                "getEphemeralApplications");
6271        synchronized (mPackages) {
6272            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6273                    .getEphemeralApplicationsLPw(userId);
6274            if (ephemeralApps != null) {
6275                return new ParceledListSlice<>(ephemeralApps);
6276            }
6277        }
6278        return null;
6279    }
6280
6281    @Override
6282    public boolean isEphemeralApplication(String packageName, int userId) {
6283        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6284                true /* requireFullPermission */, false /* checkShell */,
6285                "isEphemeral");
6286        if (DISABLE_EPHEMERAL_APPS) {
6287            return false;
6288        }
6289
6290        if (!isCallerSameApp(packageName)) {
6291            return false;
6292        }
6293        synchronized (mPackages) {
6294            PackageParser.Package pkg = mPackages.get(packageName);
6295            if (pkg != null) {
6296                return pkg.applicationInfo.isEphemeralApp();
6297            }
6298        }
6299        return false;
6300    }
6301
6302    @Override
6303    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6304        if (DISABLE_EPHEMERAL_APPS) {
6305            return null;
6306        }
6307
6308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6309                true /* requireFullPermission */, false /* checkShell */,
6310                "getCookie");
6311        if (!isCallerSameApp(packageName)) {
6312            return null;
6313        }
6314        synchronized (mPackages) {
6315            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6316                    packageName, userId);
6317        }
6318    }
6319
6320    @Override
6321    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6322        if (DISABLE_EPHEMERAL_APPS) {
6323            return true;
6324        }
6325
6326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6327                true /* requireFullPermission */, true /* checkShell */,
6328                "setCookie");
6329        if (!isCallerSameApp(packageName)) {
6330            return false;
6331        }
6332        synchronized (mPackages) {
6333            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6334                    packageName, cookie, userId);
6335        }
6336    }
6337
6338    @Override
6339    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6340        if (DISABLE_EPHEMERAL_APPS) {
6341            return null;
6342        }
6343
6344        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6345                "getEphemeralApplicationIcon");
6346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6347                true /* requireFullPermission */, false /* checkShell */,
6348                "getEphemeralApplicationIcon");
6349        synchronized (mPackages) {
6350            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6351                    packageName, userId);
6352        }
6353    }
6354
6355    private boolean isCallerSameApp(String packageName) {
6356        PackageParser.Package pkg = mPackages.get(packageName);
6357        return pkg != null
6358                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6359    }
6360
6361    @Override
6362    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6363        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6364    }
6365
6366    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6367        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6368
6369        // reader
6370        synchronized (mPackages) {
6371            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6372            final int userId = UserHandle.getCallingUserId();
6373            while (i.hasNext()) {
6374                final PackageParser.Package p = i.next();
6375                if (p.applicationInfo == null) continue;
6376
6377                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6378                        && !p.applicationInfo.isDirectBootAware();
6379                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6380                        && p.applicationInfo.isDirectBootAware();
6381
6382                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6383                        && (!mSafeMode || isSystemApp(p))
6384                        && (matchesUnaware || matchesAware)) {
6385                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6386                    if (ps != null) {
6387                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6388                                ps.readUserState(userId), userId);
6389                        if (ai != null) {
6390                            finalList.add(ai);
6391                        }
6392                    }
6393                }
6394            }
6395        }
6396
6397        return finalList;
6398    }
6399
6400    @Override
6401    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6402        if (!sUserManager.exists(userId)) return null;
6403        flags = updateFlagsForComponent(flags, userId, name);
6404        // reader
6405        synchronized (mPackages) {
6406            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6407            PackageSetting ps = provider != null
6408                    ? mSettings.mPackages.get(provider.owner.packageName)
6409                    : null;
6410            return ps != null
6411                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6412                    ? PackageParser.generateProviderInfo(provider, flags,
6413                            ps.readUserState(userId), userId)
6414                    : null;
6415        }
6416    }
6417
6418    /**
6419     * @deprecated
6420     */
6421    @Deprecated
6422    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6423        // reader
6424        synchronized (mPackages) {
6425            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6426                    .entrySet().iterator();
6427            final int userId = UserHandle.getCallingUserId();
6428            while (i.hasNext()) {
6429                Map.Entry<String, PackageParser.Provider> entry = i.next();
6430                PackageParser.Provider p = entry.getValue();
6431                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6432
6433                if (ps != null && p.syncable
6434                        && (!mSafeMode || (p.info.applicationInfo.flags
6435                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6436                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6437                            ps.readUserState(userId), userId);
6438                    if (info != null) {
6439                        outNames.add(entry.getKey());
6440                        outInfo.add(info);
6441                    }
6442                }
6443            }
6444        }
6445    }
6446
6447    @Override
6448    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6449            int uid, int flags) {
6450        final int userId = processName != null ? UserHandle.getUserId(uid)
6451                : UserHandle.getCallingUserId();
6452        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6453        flags = updateFlagsForComponent(flags, userId, processName);
6454
6455        ArrayList<ProviderInfo> finalList = null;
6456        // reader
6457        synchronized (mPackages) {
6458            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6459            while (i.hasNext()) {
6460                final PackageParser.Provider p = i.next();
6461                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6462                if (ps != null && p.info.authority != null
6463                        && (processName == null
6464                                || (p.info.processName.equals(processName)
6465                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6466                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6467                    if (finalList == null) {
6468                        finalList = new ArrayList<ProviderInfo>(3);
6469                    }
6470                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6471                            ps.readUserState(userId), userId);
6472                    if (info != null) {
6473                        finalList.add(info);
6474                    }
6475                }
6476            }
6477        }
6478
6479        if (finalList != null) {
6480            Collections.sort(finalList, mProviderInitOrderSorter);
6481            return new ParceledListSlice<ProviderInfo>(finalList);
6482        }
6483
6484        return ParceledListSlice.emptyList();
6485    }
6486
6487    @Override
6488    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6489        // reader
6490        synchronized (mPackages) {
6491            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6492            return PackageParser.generateInstrumentationInfo(i, flags);
6493        }
6494    }
6495
6496    @Override
6497    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6498            String targetPackage, int flags) {
6499        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6500    }
6501
6502    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6503            int flags) {
6504        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6505
6506        // reader
6507        synchronized (mPackages) {
6508            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6509            while (i.hasNext()) {
6510                final PackageParser.Instrumentation p = i.next();
6511                if (targetPackage == null
6512                        || targetPackage.equals(p.info.targetPackage)) {
6513                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6514                            flags);
6515                    if (ii != null) {
6516                        finalList.add(ii);
6517                    }
6518                }
6519            }
6520        }
6521
6522        return finalList;
6523    }
6524
6525    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6526        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6527        if (overlays == null) {
6528            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6529            return;
6530        }
6531        for (PackageParser.Package opkg : overlays.values()) {
6532            // Not much to do if idmap fails: we already logged the error
6533            // and we certainly don't want to abort installation of pkg simply
6534            // because an overlay didn't fit properly. For these reasons,
6535            // ignore the return value of createIdmapForPackagePairLI.
6536            createIdmapForPackagePairLI(pkg, opkg);
6537        }
6538    }
6539
6540    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6541            PackageParser.Package opkg) {
6542        if (!opkg.mTrustedOverlay) {
6543            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6544                    opkg.baseCodePath + ": overlay not trusted");
6545            return false;
6546        }
6547        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6548        if (overlaySet == null) {
6549            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6550                    opkg.baseCodePath + " but target package has no known overlays");
6551            return false;
6552        }
6553        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6554        // TODO: generate idmap for split APKs
6555        try {
6556            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6557        } catch (InstallerException e) {
6558            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6559                    + opkg.baseCodePath);
6560            return false;
6561        }
6562        PackageParser.Package[] overlayArray =
6563            overlaySet.values().toArray(new PackageParser.Package[0]);
6564        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6565            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6566                return p1.mOverlayPriority - p2.mOverlayPriority;
6567            }
6568        };
6569        Arrays.sort(overlayArray, cmp);
6570
6571        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6572        int i = 0;
6573        for (PackageParser.Package p : overlayArray) {
6574            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6575        }
6576        return true;
6577    }
6578
6579    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6580        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6581        try {
6582            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6583        } finally {
6584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6585        }
6586    }
6587
6588    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6589        final File[] files = dir.listFiles();
6590        if (ArrayUtils.isEmpty(files)) {
6591            Log.d(TAG, "No files in app dir " + dir);
6592            return;
6593        }
6594
6595        if (DEBUG_PACKAGE_SCANNING) {
6596            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6597                    + " flags=0x" + Integer.toHexString(parseFlags));
6598        }
6599
6600        for (File file : files) {
6601            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6602                    && !PackageInstallerService.isStageName(file.getName());
6603            if (!isPackage) {
6604                // Ignore entries which are not packages
6605                continue;
6606            }
6607            try {
6608                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6609                        scanFlags, currentTime, null);
6610            } catch (PackageManagerException e) {
6611                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6612
6613                // Delete invalid userdata apps
6614                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6615                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6616                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6617                    removeCodePathLI(file);
6618                }
6619            }
6620        }
6621    }
6622
6623    private static File getSettingsProblemFile() {
6624        File dataDir = Environment.getDataDirectory();
6625        File systemDir = new File(dataDir, "system");
6626        File fname = new File(systemDir, "uiderrors.txt");
6627        return fname;
6628    }
6629
6630    static void reportSettingsProblem(int priority, String msg) {
6631        logCriticalInfo(priority, msg);
6632    }
6633
6634    static void logCriticalInfo(int priority, String msg) {
6635        Slog.println(priority, TAG, msg);
6636        EventLogTags.writePmCriticalInfo(msg);
6637        try {
6638            File fname = getSettingsProblemFile();
6639            FileOutputStream out = new FileOutputStream(fname, true);
6640            PrintWriter pw = new FastPrintWriter(out);
6641            SimpleDateFormat formatter = new SimpleDateFormat();
6642            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6643            pw.println(dateString + ": " + msg);
6644            pw.close();
6645            FileUtils.setPermissions(
6646                    fname.toString(),
6647                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6648                    -1, -1);
6649        } catch (java.io.IOException e) {
6650        }
6651    }
6652
6653    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6654        if (srcFile.isDirectory()) {
6655            final File baseFile = new File(pkg.baseCodePath);
6656            long maxModifiedTime = baseFile.lastModified();
6657            if (pkg.splitCodePaths != null) {
6658                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6659                    final File splitFile = new File(pkg.splitCodePaths[i]);
6660                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6661                }
6662            }
6663            return maxModifiedTime;
6664        }
6665        return srcFile.lastModified();
6666    }
6667
6668    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6669            final int policyFlags) throws PackageManagerException {
6670        if (ps != null
6671                && ps.codePath.equals(srcFile)
6672                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6673                && !isCompatSignatureUpdateNeeded(pkg)
6674                && !isRecoverSignatureUpdateNeeded(pkg)) {
6675            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6676            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6677            ArraySet<PublicKey> signingKs;
6678            synchronized (mPackages) {
6679                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6680            }
6681            if (ps.signatures.mSignatures != null
6682                    && ps.signatures.mSignatures.length != 0
6683                    && signingKs != null) {
6684                // Optimization: reuse the existing cached certificates
6685                // if the package appears to be unchanged.
6686                pkg.mSignatures = ps.signatures.mSignatures;
6687                pkg.mSigningKeys = signingKs;
6688                return;
6689            }
6690
6691            Slog.w(TAG, "PackageSetting for " + ps.name
6692                    + " is missing signatures.  Collecting certs again to recover them.");
6693        } else {
6694            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6695        }
6696
6697        try {
6698            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6699            PackageParser.collectCertificates(pkg, policyFlags);
6700        } catch (PackageParserException e) {
6701            throw PackageManagerException.from(e);
6702        } finally {
6703            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6704        }
6705    }
6706
6707    /**
6708     *  Traces a package scan.
6709     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6710     */
6711    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6712            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6713        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6714        try {
6715            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6716        } finally {
6717            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6718        }
6719    }
6720
6721    /**
6722     *  Scans a package and returns the newly parsed package.
6723     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6724     */
6725    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6726            long currentTime, UserHandle user) throws PackageManagerException {
6727        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6728        PackageParser pp = new PackageParser();
6729        pp.setSeparateProcesses(mSeparateProcesses);
6730        pp.setOnlyCoreApps(mOnlyCore);
6731        pp.setDisplayMetrics(mMetrics);
6732
6733        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6734            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6735        }
6736
6737        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6738        final PackageParser.Package pkg;
6739        try {
6740            pkg = pp.parsePackage(scanFile, parseFlags);
6741        } catch (PackageParserException e) {
6742            throw PackageManagerException.from(e);
6743        } finally {
6744            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6745        }
6746
6747        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6748    }
6749
6750    /**
6751     *  Scans a package and returns the newly parsed package.
6752     *  @throws PackageManagerException on a parse error.
6753     */
6754    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6755            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6756            throws PackageManagerException {
6757        // If the package has children and this is the first dive in the function
6758        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6759        // packages (parent and children) would be successfully scanned before the
6760        // actual scan since scanning mutates internal state and we want to atomically
6761        // install the package and its children.
6762        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6763            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6764                scanFlags |= SCAN_CHECK_ONLY;
6765            }
6766        } else {
6767            scanFlags &= ~SCAN_CHECK_ONLY;
6768        }
6769
6770        // Scan the parent
6771        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6772                scanFlags, currentTime, user);
6773
6774        // Scan the children
6775        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6776        for (int i = 0; i < childCount; i++) {
6777            PackageParser.Package childPackage = pkg.childPackages.get(i);
6778            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6779                    currentTime, user);
6780        }
6781
6782
6783        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6784            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6785        }
6786
6787        return scannedPkg;
6788    }
6789
6790    /**
6791     *  Scans a package and returns the newly parsed package.
6792     *  @throws PackageManagerException on a parse error.
6793     */
6794    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6795            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6796            throws PackageManagerException {
6797        PackageSetting ps = null;
6798        PackageSetting updatedPkg;
6799        // reader
6800        synchronized (mPackages) {
6801            // Look to see if we already know about this package.
6802            String oldName = mSettings.getRenamedPackage(pkg.packageName);
6803            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6804                // This package has been renamed to its original name.  Let's
6805                // use that.
6806                ps = mSettings.peekPackageLPr(oldName);
6807            }
6808            // If there was no original package, see one for the real package name.
6809            if (ps == null) {
6810                ps = mSettings.peekPackageLPr(pkg.packageName);
6811            }
6812            // Check to see if this package could be hiding/updating a system
6813            // package.  Must look for it either under the original or real
6814            // package name depending on our state.
6815            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6816            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6817
6818            // If this is a package we don't know about on the system partition, we
6819            // may need to remove disabled child packages on the system partition
6820            // or may need to not add child packages if the parent apk is updated
6821            // on the data partition and no longer defines this child package.
6822            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6823                // If this is a parent package for an updated system app and this system
6824                // app got an OTA update which no longer defines some of the child packages
6825                // we have to prune them from the disabled system packages.
6826                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6827                if (disabledPs != null) {
6828                    final int scannedChildCount = (pkg.childPackages != null)
6829                            ? pkg.childPackages.size() : 0;
6830                    final int disabledChildCount = disabledPs.childPackageNames != null
6831                            ? disabledPs.childPackageNames.size() : 0;
6832                    for (int i = 0; i < disabledChildCount; i++) {
6833                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6834                        boolean disabledPackageAvailable = false;
6835                        for (int j = 0; j < scannedChildCount; j++) {
6836                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6837                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6838                                disabledPackageAvailable = true;
6839                                break;
6840                            }
6841                         }
6842                         if (!disabledPackageAvailable) {
6843                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6844                         }
6845                    }
6846                }
6847            }
6848        }
6849
6850        boolean updatedPkgBetter = false;
6851        // First check if this is a system package that may involve an update
6852        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6853            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6854            // it needs to drop FLAG_PRIVILEGED.
6855            if (locationIsPrivileged(scanFile)) {
6856                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6857            } else {
6858                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6859            }
6860
6861            if (ps != null && !ps.codePath.equals(scanFile)) {
6862                // The path has changed from what was last scanned...  check the
6863                // version of the new path against what we have stored to determine
6864                // what to do.
6865                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6866                if (pkg.mVersionCode <= ps.versionCode) {
6867                    // The system package has been updated and the code path does not match
6868                    // Ignore entry. Skip it.
6869                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6870                            + " ignored: updated version " + ps.versionCode
6871                            + " better than this " + pkg.mVersionCode);
6872                    if (!updatedPkg.codePath.equals(scanFile)) {
6873                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6874                                + ps.name + " changing from " + updatedPkg.codePathString
6875                                + " to " + scanFile);
6876                        updatedPkg.codePath = scanFile;
6877                        updatedPkg.codePathString = scanFile.toString();
6878                        updatedPkg.resourcePath = scanFile;
6879                        updatedPkg.resourcePathString = scanFile.toString();
6880                    }
6881                    updatedPkg.pkg = pkg;
6882                    updatedPkg.versionCode = pkg.mVersionCode;
6883
6884                    // Update the disabled system child packages to point to the package too.
6885                    final int childCount = updatedPkg.childPackageNames != null
6886                            ? updatedPkg.childPackageNames.size() : 0;
6887                    for (int i = 0; i < childCount; i++) {
6888                        String childPackageName = updatedPkg.childPackageNames.get(i);
6889                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6890                                childPackageName);
6891                        if (updatedChildPkg != null) {
6892                            updatedChildPkg.pkg = pkg;
6893                            updatedChildPkg.versionCode = pkg.mVersionCode;
6894                        }
6895                    }
6896
6897                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6898                            + scanFile + " ignored: updated version " + ps.versionCode
6899                            + " better than this " + pkg.mVersionCode);
6900                } else {
6901                    // The current app on the system partition is better than
6902                    // what we have updated to on the data partition; switch
6903                    // back to the system partition version.
6904                    // At this point, its safely assumed that package installation for
6905                    // apps in system partition will go through. If not there won't be a working
6906                    // version of the app
6907                    // writer
6908                    synchronized (mPackages) {
6909                        // Just remove the loaded entries from package lists.
6910                        mPackages.remove(ps.name);
6911                    }
6912
6913                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6914                            + " reverting from " + ps.codePathString
6915                            + ": new version " + pkg.mVersionCode
6916                            + " better than installed " + ps.versionCode);
6917
6918                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6919                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6920                    synchronized (mInstallLock) {
6921                        args.cleanUpResourcesLI();
6922                    }
6923                    synchronized (mPackages) {
6924                        mSettings.enableSystemPackageLPw(ps.name);
6925                    }
6926                    updatedPkgBetter = true;
6927                }
6928            }
6929        }
6930
6931        if (updatedPkg != null) {
6932            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6933            // initially
6934            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6935
6936            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6937            // flag set initially
6938            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6939                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6940            }
6941        }
6942
6943        // Verify certificates against what was last scanned
6944        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6945
6946        /*
6947         * A new system app appeared, but we already had a non-system one of the
6948         * same name installed earlier.
6949         */
6950        boolean shouldHideSystemApp = false;
6951        if (updatedPkg == null && ps != null
6952                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6953            /*
6954             * Check to make sure the signatures match first. If they don't,
6955             * wipe the installed application and its data.
6956             */
6957            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6958                    != PackageManager.SIGNATURE_MATCH) {
6959                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6960                        + " signatures don't match existing userdata copy; removing");
6961                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6962                        "scanPackageInternalLI")) {
6963                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6964                }
6965                ps = null;
6966            } else {
6967                /*
6968                 * If the newly-added system app is an older version than the
6969                 * already installed version, hide it. It will be scanned later
6970                 * and re-added like an update.
6971                 */
6972                if (pkg.mVersionCode <= ps.versionCode) {
6973                    shouldHideSystemApp = true;
6974                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6975                            + " but new version " + pkg.mVersionCode + " better than installed "
6976                            + ps.versionCode + "; hiding system");
6977                } else {
6978                    /*
6979                     * The newly found system app is a newer version that the
6980                     * one previously installed. Simply remove the
6981                     * already-installed application and replace it with our own
6982                     * while keeping the application data.
6983                     */
6984                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6985                            + " reverting from " + ps.codePathString + ": new version "
6986                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6987                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6988                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6989                    synchronized (mInstallLock) {
6990                        args.cleanUpResourcesLI();
6991                    }
6992                }
6993            }
6994        }
6995
6996        // The apk is forward locked (not public) if its code and resources
6997        // are kept in different files. (except for app in either system or
6998        // vendor path).
6999        // TODO grab this value from PackageSettings
7000        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7001            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7002                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7003            }
7004        }
7005
7006        // TODO: extend to support forward-locked splits
7007        String resourcePath = null;
7008        String baseResourcePath = null;
7009        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7010            if (ps != null && ps.resourcePathString != null) {
7011                resourcePath = ps.resourcePathString;
7012                baseResourcePath = ps.resourcePathString;
7013            } else {
7014                // Should not happen at all. Just log an error.
7015                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7016            }
7017        } else {
7018            resourcePath = pkg.codePath;
7019            baseResourcePath = pkg.baseCodePath;
7020        }
7021
7022        // Set application objects path explicitly.
7023        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7024        pkg.setApplicationInfoCodePath(pkg.codePath);
7025        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7026        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7027        pkg.setApplicationInfoResourcePath(resourcePath);
7028        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7029        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7030
7031        // Note that we invoke the following method only if we are about to unpack an application
7032        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7033                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7034
7035        /*
7036         * If the system app should be overridden by a previously installed
7037         * data, hide the system app now and let the /data/app scan pick it up
7038         * again.
7039         */
7040        if (shouldHideSystemApp) {
7041            synchronized (mPackages) {
7042                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7043            }
7044        }
7045
7046        return scannedPkg;
7047    }
7048
7049    private static String fixProcessName(String defProcessName,
7050            String processName, int uid) {
7051        if (processName == null) {
7052            return defProcessName;
7053        }
7054        return processName;
7055    }
7056
7057    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7058            throws PackageManagerException {
7059        if (pkgSetting.signatures.mSignatures != null) {
7060            // Already existing package. Make sure signatures match
7061            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7062                    == PackageManager.SIGNATURE_MATCH;
7063            if (!match) {
7064                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7065                        == PackageManager.SIGNATURE_MATCH;
7066            }
7067            if (!match) {
7068                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7069                        == PackageManager.SIGNATURE_MATCH;
7070            }
7071            if (!match) {
7072                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7073                        + pkg.packageName + " signatures do not match the "
7074                        + "previously installed version; ignoring!");
7075            }
7076        }
7077
7078        // Check for shared user signatures
7079        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7080            // Already existing package. Make sure signatures match
7081            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7082                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7083            if (!match) {
7084                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7085                        == PackageManager.SIGNATURE_MATCH;
7086            }
7087            if (!match) {
7088                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7089                        == PackageManager.SIGNATURE_MATCH;
7090            }
7091            if (!match) {
7092                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7093                        "Package " + pkg.packageName
7094                        + " has no signatures that match those in shared user "
7095                        + pkgSetting.sharedUser.name + "; ignoring!");
7096            }
7097        }
7098    }
7099
7100    /**
7101     * Enforces that only the system UID or root's UID can call a method exposed
7102     * via Binder.
7103     *
7104     * @param message used as message if SecurityException is thrown
7105     * @throws SecurityException if the caller is not system or root
7106     */
7107    private static final void enforceSystemOrRoot(String message) {
7108        final int uid = Binder.getCallingUid();
7109        if (uid != Process.SYSTEM_UID && uid != 0) {
7110            throw new SecurityException(message);
7111        }
7112    }
7113
7114    @Override
7115    public void performFstrimIfNeeded() {
7116        enforceSystemOrRoot("Only the system can request fstrim");
7117
7118        // Before everything else, see whether we need to fstrim.
7119        try {
7120            IMountService ms = PackageHelper.getMountService();
7121            if (ms != null) {
7122                boolean doTrim = false;
7123                final long interval = android.provider.Settings.Global.getLong(
7124                        mContext.getContentResolver(),
7125                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7126                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7127                if (interval > 0) {
7128                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7129                    if (timeSinceLast > interval) {
7130                        doTrim = true;
7131                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7132                                + "; running immediately");
7133                    }
7134                }
7135                if (doTrim) {
7136                    if (!isFirstBoot()) {
7137                        try {
7138                            ActivityManagerNative.getDefault().showBootMessage(
7139                                    mContext.getResources().getString(
7140                                            R.string.android_upgrading_fstrim), true);
7141                        } catch (RemoteException e) {
7142                        }
7143                    }
7144                    ms.runMaintenance();
7145                }
7146            } else {
7147                Slog.e(TAG, "Mount service unavailable!");
7148            }
7149        } catch (RemoteException e) {
7150            // Can't happen; MountService is local
7151        }
7152    }
7153
7154    @Override
7155    public void updatePackagesIfNeeded() {
7156        enforceSystemOrRoot("Only the system can request package update");
7157
7158        // We need to re-extract after an OTA.
7159        boolean causeUpgrade = isUpgrade();
7160
7161        // First boot or factory reset.
7162        // Note: we also handle devices that are upgrading to N right now as if it is their
7163        //       first boot, as they do not have profile data.
7164        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7165
7166        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7167        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7168
7169        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7170            return;
7171        }
7172
7173        List<PackageParser.Package> pkgs;
7174        synchronized (mPackages) {
7175            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7176        }
7177
7178        final long startTime = System.nanoTime();
7179        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7180                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7181
7182        final int elapsedTimeSeconds =
7183                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7184
7185        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7186        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7187        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7188        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7189        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7190    }
7191
7192    /**
7193     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7194     * containing statistics about the invocation. The array consists of three elements,
7195     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7196     * and {@code numberOfPackagesFailed}.
7197     */
7198    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7199            String compilerFilter) {
7200
7201        int numberOfPackagesVisited = 0;
7202        int numberOfPackagesOptimized = 0;
7203        int numberOfPackagesSkipped = 0;
7204        int numberOfPackagesFailed = 0;
7205        final int numberOfPackagesToDexopt = pkgs.size();
7206
7207        for (PackageParser.Package pkg : pkgs) {
7208            numberOfPackagesVisited++;
7209
7210            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7211                if (DEBUG_DEXOPT) {
7212                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7213                }
7214                numberOfPackagesSkipped++;
7215                continue;
7216            }
7217
7218            if (DEBUG_DEXOPT) {
7219                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7220                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7221            }
7222
7223            if (showDialog) {
7224                try {
7225                    ActivityManagerNative.getDefault().showBootMessage(
7226                            mContext.getResources().getString(R.string.android_upgrading_apk,
7227                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7228                } catch (RemoteException e) {
7229                }
7230            }
7231
7232            // If the OTA updates a system app which was previously preopted to a non-preopted state
7233            // the app might end up being verified at runtime. That's because by default the apps
7234            // are verify-profile but for preopted apps there's no profile.
7235            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7236            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7237            // filter (by default interpret-only).
7238            // Note that at this stage unused apps are already filtered.
7239            if (isSystemApp(pkg) &&
7240                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7241                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7242                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7243            }
7244
7245            // checkProfiles is false to avoid merging profiles during boot which
7246            // might interfere with background compilation (b/28612421).
7247            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7248            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7249            // trade-off worth doing to save boot time work.
7250            int dexOptStatus = performDexOptTraced(pkg.packageName,
7251                    false /* checkProfiles */,
7252                    compilerFilter,
7253                    false /* force */);
7254            switch (dexOptStatus) {
7255                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7256                    numberOfPackagesOptimized++;
7257                    break;
7258                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7259                    numberOfPackagesSkipped++;
7260                    break;
7261                case PackageDexOptimizer.DEX_OPT_FAILED:
7262                    numberOfPackagesFailed++;
7263                    break;
7264                default:
7265                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7266                    break;
7267            }
7268        }
7269
7270        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7271                numberOfPackagesFailed };
7272    }
7273
7274    @Override
7275    public void notifyPackageUse(String packageName, int reason) {
7276        synchronized (mPackages) {
7277            PackageParser.Package p = mPackages.get(packageName);
7278            if (p == null) {
7279                return;
7280            }
7281            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7282        }
7283    }
7284
7285    // TODO: this is not used nor needed. Delete it.
7286    @Override
7287    public boolean performDexOptIfNeeded(String packageName) {
7288        int dexOptStatus = performDexOptTraced(packageName,
7289                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7290        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7291    }
7292
7293    @Override
7294    public boolean performDexOpt(String packageName,
7295            boolean checkProfiles, int compileReason, boolean force) {
7296        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7297                getCompilerFilterForReason(compileReason), force);
7298        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7299    }
7300
7301    @Override
7302    public boolean performDexOptMode(String packageName,
7303            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7304        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7305                targetCompilerFilter, force);
7306        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7307    }
7308
7309    private int performDexOptTraced(String packageName,
7310                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7311        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7312        try {
7313            return performDexOptInternal(packageName, checkProfiles,
7314                    targetCompilerFilter, force);
7315        } finally {
7316            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7317        }
7318    }
7319
7320    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7321    // if the package can now be considered up to date for the given filter.
7322    private int performDexOptInternal(String packageName,
7323                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7324        PackageParser.Package p;
7325        synchronized (mPackages) {
7326            p = mPackages.get(packageName);
7327            if (p == null) {
7328                // Package could not be found. Report failure.
7329                return PackageDexOptimizer.DEX_OPT_FAILED;
7330            }
7331            mPackageUsage.maybeWriteAsync(mPackages);
7332            mCompilerStats.maybeWriteAsync();
7333        }
7334        long callingId = Binder.clearCallingIdentity();
7335        try {
7336            synchronized (mInstallLock) {
7337                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7338                        targetCompilerFilter, force);
7339            }
7340        } finally {
7341            Binder.restoreCallingIdentity(callingId);
7342        }
7343    }
7344
7345    public ArraySet<String> getOptimizablePackages() {
7346        ArraySet<String> pkgs = new ArraySet<String>();
7347        synchronized (mPackages) {
7348            for (PackageParser.Package p : mPackages.values()) {
7349                if (PackageDexOptimizer.canOptimizePackage(p)) {
7350                    pkgs.add(p.packageName);
7351                }
7352            }
7353        }
7354        return pkgs;
7355    }
7356
7357    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7358            boolean checkProfiles, String targetCompilerFilter,
7359            boolean force) {
7360        // Select the dex optimizer based on the force parameter.
7361        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7362        //       allocate an object here.
7363        PackageDexOptimizer pdo = force
7364                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7365                : mPackageDexOptimizer;
7366
7367        // Optimize all dependencies first. Note: we ignore the return value and march on
7368        // on errors.
7369        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7370        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7371        if (!deps.isEmpty()) {
7372            for (PackageParser.Package depPackage : deps) {
7373                // TODO: Analyze and investigate if we (should) profile libraries.
7374                // Currently this will do a full compilation of the library by default.
7375                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7376                        false /* checkProfiles */,
7377                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7378                        getOrCreateCompilerPackageStats(depPackage));
7379            }
7380        }
7381        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7382                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7383    }
7384
7385    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7386        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7387            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7388            Set<String> collectedNames = new HashSet<>();
7389            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7390
7391            retValue.remove(p);
7392
7393            return retValue;
7394        } else {
7395            return Collections.emptyList();
7396        }
7397    }
7398
7399    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7400            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7401        if (!collectedNames.contains(p.packageName)) {
7402            collectedNames.add(p.packageName);
7403            collected.add(p);
7404
7405            if (p.usesLibraries != null) {
7406                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7407            }
7408            if (p.usesOptionalLibraries != null) {
7409                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7410                        collectedNames);
7411            }
7412        }
7413    }
7414
7415    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7416            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7417        for (String libName : libs) {
7418            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7419            if (libPkg != null) {
7420                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7421            }
7422        }
7423    }
7424
7425    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7426        synchronized (mPackages) {
7427            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7428            if (lib != null && lib.apk != null) {
7429                return mPackages.get(lib.apk);
7430            }
7431        }
7432        return null;
7433    }
7434
7435    public void shutdown() {
7436        mPackageUsage.writeNow(mPackages);
7437        mCompilerStats.writeNow();
7438    }
7439
7440    @Override
7441    public void dumpProfiles(String packageName) {
7442        PackageParser.Package pkg;
7443        synchronized (mPackages) {
7444            pkg = mPackages.get(packageName);
7445            if (pkg == null) {
7446                throw new IllegalArgumentException("Unknown package: " + packageName);
7447            }
7448        }
7449        /* Only the shell, root, or the app user should be able to dump profiles. */
7450        int callingUid = Binder.getCallingUid();
7451        if (callingUid != Process.SHELL_UID &&
7452            callingUid != Process.ROOT_UID &&
7453            callingUid != pkg.applicationInfo.uid) {
7454            throw new SecurityException("dumpProfiles");
7455        }
7456
7457        synchronized (mInstallLock) {
7458            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7459            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7460            try {
7461                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7462                String gid = Integer.toString(sharedGid);
7463                String codePaths = TextUtils.join(";", allCodePaths);
7464                mInstaller.dumpProfiles(gid, packageName, codePaths);
7465            } catch (InstallerException e) {
7466                Slog.w(TAG, "Failed to dump profiles", e);
7467            }
7468            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7469        }
7470    }
7471
7472    @Override
7473    public void forceDexOpt(String packageName) {
7474        enforceSystemOrRoot("forceDexOpt");
7475
7476        PackageParser.Package pkg;
7477        synchronized (mPackages) {
7478            pkg = mPackages.get(packageName);
7479            if (pkg == null) {
7480                throw new IllegalArgumentException("Unknown package: " + packageName);
7481            }
7482        }
7483
7484        synchronized (mInstallLock) {
7485            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7486
7487            // Whoever is calling forceDexOpt wants a fully compiled package.
7488            // Don't use profiles since that may cause compilation to be skipped.
7489            final int res = performDexOptInternalWithDependenciesLI(pkg,
7490                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7491                    true /* force */);
7492
7493            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7494            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7495                throw new IllegalStateException("Failed to dexopt: " + res);
7496            }
7497        }
7498    }
7499
7500    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7501        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7502            Slog.w(TAG, "Unable to update from " + oldPkg.name
7503                    + " to " + newPkg.packageName
7504                    + ": old package not in system partition");
7505            return false;
7506        } else if (mPackages.get(oldPkg.name) != null) {
7507            Slog.w(TAG, "Unable to update from " + oldPkg.name
7508                    + " to " + newPkg.packageName
7509                    + ": old package still exists");
7510            return false;
7511        }
7512        return true;
7513    }
7514
7515    void removeCodePathLI(File codePath) {
7516        if (codePath.isDirectory()) {
7517            try {
7518                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7519            } catch (InstallerException e) {
7520                Slog.w(TAG, "Failed to remove code path", e);
7521            }
7522        } else {
7523            codePath.delete();
7524        }
7525    }
7526
7527    private int[] resolveUserIds(int userId) {
7528        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7529    }
7530
7531    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7532        if (pkg == null) {
7533            Slog.wtf(TAG, "Package was null!", new Throwable());
7534            return;
7535        }
7536        clearAppDataLeafLIF(pkg, userId, flags);
7537        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7538        for (int i = 0; i < childCount; i++) {
7539            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7540        }
7541    }
7542
7543    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7544        final PackageSetting ps;
7545        synchronized (mPackages) {
7546            ps = mSettings.mPackages.get(pkg.packageName);
7547        }
7548        for (int realUserId : resolveUserIds(userId)) {
7549            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7550            try {
7551                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7552                        ceDataInode);
7553            } catch (InstallerException e) {
7554                Slog.w(TAG, String.valueOf(e));
7555            }
7556        }
7557    }
7558
7559    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7560        if (pkg == null) {
7561            Slog.wtf(TAG, "Package was null!", new Throwable());
7562            return;
7563        }
7564        destroyAppDataLeafLIF(pkg, userId, flags);
7565        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7566        for (int i = 0; i < childCount; i++) {
7567            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7568        }
7569    }
7570
7571    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7572        final PackageSetting ps;
7573        synchronized (mPackages) {
7574            ps = mSettings.mPackages.get(pkg.packageName);
7575        }
7576        for (int realUserId : resolveUserIds(userId)) {
7577            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7578            try {
7579                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7580                        ceDataInode);
7581            } catch (InstallerException e) {
7582                Slog.w(TAG, String.valueOf(e));
7583            }
7584        }
7585    }
7586
7587    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7588        if (pkg == null) {
7589            Slog.wtf(TAG, "Package was null!", new Throwable());
7590            return;
7591        }
7592        destroyAppProfilesLeafLIF(pkg);
7593        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7594        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7595        for (int i = 0; i < childCount; i++) {
7596            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7597            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7598                    true /* removeBaseMarker */);
7599        }
7600    }
7601
7602    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7603            boolean removeBaseMarker) {
7604        if (pkg.isForwardLocked()) {
7605            return;
7606        }
7607
7608        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7609            try {
7610                path = PackageManagerServiceUtils.realpath(new File(path));
7611            } catch (IOException e) {
7612                // TODO: Should we return early here ?
7613                Slog.w(TAG, "Failed to get canonical path", e);
7614                continue;
7615            }
7616
7617            final String useMarker = path.replace('/', '@');
7618            for (int realUserId : resolveUserIds(userId)) {
7619                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7620                if (removeBaseMarker) {
7621                    File foreignUseMark = new File(profileDir, useMarker);
7622                    if (foreignUseMark.exists()) {
7623                        if (!foreignUseMark.delete()) {
7624                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7625                                    + pkg.packageName);
7626                        }
7627                    }
7628                }
7629
7630                File[] markers = profileDir.listFiles();
7631                if (markers != null) {
7632                    final String searchString = "@" + pkg.packageName + "@";
7633                    // We also delete all markers that contain the package name we're
7634                    // uninstalling. These are associated with secondary dex-files belonging
7635                    // to the package. Reconstructing the path of these dex files is messy
7636                    // in general.
7637                    for (File marker : markers) {
7638                        if (marker.getName().indexOf(searchString) > 0) {
7639                            if (!marker.delete()) {
7640                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7641                                    + pkg.packageName);
7642                            }
7643                        }
7644                    }
7645                }
7646            }
7647        }
7648    }
7649
7650    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7651        try {
7652            mInstaller.destroyAppProfiles(pkg.packageName);
7653        } catch (InstallerException e) {
7654            Slog.w(TAG, String.valueOf(e));
7655        }
7656    }
7657
7658    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7659        if (pkg == null) {
7660            Slog.wtf(TAG, "Package was null!", new Throwable());
7661            return;
7662        }
7663        clearAppProfilesLeafLIF(pkg);
7664        // We don't remove the base foreign use marker when clearing profiles because
7665        // we will rename it when the app is updated. Unlike the actual profile contents,
7666        // the foreign use marker is good across installs.
7667        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7668        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7669        for (int i = 0; i < childCount; i++) {
7670            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7671        }
7672    }
7673
7674    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7675        try {
7676            mInstaller.clearAppProfiles(pkg.packageName);
7677        } catch (InstallerException e) {
7678            Slog.w(TAG, String.valueOf(e));
7679        }
7680    }
7681
7682    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7683            long lastUpdateTime) {
7684        // Set parent install/update time
7685        PackageSetting ps = (PackageSetting) pkg.mExtras;
7686        if (ps != null) {
7687            ps.firstInstallTime = firstInstallTime;
7688            ps.lastUpdateTime = lastUpdateTime;
7689        }
7690        // Set children install/update time
7691        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7692        for (int i = 0; i < childCount; i++) {
7693            PackageParser.Package childPkg = pkg.childPackages.get(i);
7694            ps = (PackageSetting) childPkg.mExtras;
7695            if (ps != null) {
7696                ps.firstInstallTime = firstInstallTime;
7697                ps.lastUpdateTime = lastUpdateTime;
7698            }
7699        }
7700    }
7701
7702    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7703            PackageParser.Package changingLib) {
7704        if (file.path != null) {
7705            usesLibraryFiles.add(file.path);
7706            return;
7707        }
7708        PackageParser.Package p = mPackages.get(file.apk);
7709        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7710            // If we are doing this while in the middle of updating a library apk,
7711            // then we need to make sure to use that new apk for determining the
7712            // dependencies here.  (We haven't yet finished committing the new apk
7713            // to the package manager state.)
7714            if (p == null || p.packageName.equals(changingLib.packageName)) {
7715                p = changingLib;
7716            }
7717        }
7718        if (p != null) {
7719            usesLibraryFiles.addAll(p.getAllCodePaths());
7720        }
7721    }
7722
7723    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7724            PackageParser.Package changingLib) throws PackageManagerException {
7725        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7726            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7727            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7728            for (int i=0; i<N; i++) {
7729                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7730                if (file == null) {
7731                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7732                            "Package " + pkg.packageName + " requires unavailable shared library "
7733                            + pkg.usesLibraries.get(i) + "; failing!");
7734                }
7735                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7736            }
7737            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7738            for (int i=0; i<N; i++) {
7739                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7740                if (file == null) {
7741                    Slog.w(TAG, "Package " + pkg.packageName
7742                            + " desires unavailable shared library "
7743                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7744                } else {
7745                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7746                }
7747            }
7748            N = usesLibraryFiles.size();
7749            if (N > 0) {
7750                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7751            } else {
7752                pkg.usesLibraryFiles = null;
7753            }
7754        }
7755    }
7756
7757    private static boolean hasString(List<String> list, List<String> which) {
7758        if (list == null) {
7759            return false;
7760        }
7761        for (int i=list.size()-1; i>=0; i--) {
7762            for (int j=which.size()-1; j>=0; j--) {
7763                if (which.get(j).equals(list.get(i))) {
7764                    return true;
7765                }
7766            }
7767        }
7768        return false;
7769    }
7770
7771    private void updateAllSharedLibrariesLPw() {
7772        for (PackageParser.Package pkg : mPackages.values()) {
7773            try {
7774                updateSharedLibrariesLPw(pkg, null);
7775            } catch (PackageManagerException e) {
7776                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7777            }
7778        }
7779    }
7780
7781    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7782            PackageParser.Package changingPkg) {
7783        ArrayList<PackageParser.Package> res = null;
7784        for (PackageParser.Package pkg : mPackages.values()) {
7785            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7786                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7787                if (res == null) {
7788                    res = new ArrayList<PackageParser.Package>();
7789                }
7790                res.add(pkg);
7791                try {
7792                    updateSharedLibrariesLPw(pkg, changingPkg);
7793                } catch (PackageManagerException e) {
7794                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7795                }
7796            }
7797        }
7798        return res;
7799    }
7800
7801    /**
7802     * Derive the value of the {@code cpuAbiOverride} based on the provided
7803     * value and an optional stored value from the package settings.
7804     */
7805    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7806        String cpuAbiOverride = null;
7807
7808        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7809            cpuAbiOverride = null;
7810        } else if (abiOverride != null) {
7811            cpuAbiOverride = abiOverride;
7812        } else if (settings != null) {
7813            cpuAbiOverride = settings.cpuAbiOverrideString;
7814        }
7815
7816        return cpuAbiOverride;
7817    }
7818
7819    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7820            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7821                    throws PackageManagerException {
7822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7823        // If the package has children and this is the first dive in the function
7824        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7825        // whether all packages (parent and children) would be successfully scanned
7826        // before the actual scan since scanning mutates internal state and we want
7827        // to atomically install the package and its children.
7828        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7829            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7830                scanFlags |= SCAN_CHECK_ONLY;
7831            }
7832        } else {
7833            scanFlags &= ~SCAN_CHECK_ONLY;
7834        }
7835
7836        final PackageParser.Package scannedPkg;
7837        try {
7838            // Scan the parent
7839            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7840            // Scan the children
7841            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7842            for (int i = 0; i < childCount; i++) {
7843                PackageParser.Package childPkg = pkg.childPackages.get(i);
7844                scanPackageLI(childPkg, policyFlags,
7845                        scanFlags, currentTime, user);
7846            }
7847        } finally {
7848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7849        }
7850
7851        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7852            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7853        }
7854
7855        return scannedPkg;
7856    }
7857
7858    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7859            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7860        boolean success = false;
7861        try {
7862            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7863                    currentTime, user);
7864            success = true;
7865            return res;
7866        } finally {
7867            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7868                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7869                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7870                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7871                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7872            }
7873        }
7874    }
7875
7876    /**
7877     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7878     */
7879    private static boolean apkHasCode(String fileName) {
7880        StrictJarFile jarFile = null;
7881        try {
7882            jarFile = new StrictJarFile(fileName,
7883                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7884            return jarFile.findEntry("classes.dex") != null;
7885        } catch (IOException ignore) {
7886        } finally {
7887            try {
7888                if (jarFile != null) {
7889                    jarFile.close();
7890                }
7891            } catch (IOException ignore) {}
7892        }
7893        return false;
7894    }
7895
7896    /**
7897     * Enforces code policy for the package. This ensures that if an APK has
7898     * declared hasCode="true" in its manifest that the APK actually contains
7899     * code.
7900     *
7901     * @throws PackageManagerException If bytecode could not be found when it should exist
7902     */
7903    private static void enforceCodePolicy(PackageParser.Package pkg)
7904            throws PackageManagerException {
7905        final boolean shouldHaveCode =
7906                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7907        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7908            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7909                    "Package " + pkg.baseCodePath + " code is missing");
7910        }
7911
7912        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7913            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7914                final boolean splitShouldHaveCode =
7915                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7916                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7917                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7918                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7919                }
7920            }
7921        }
7922    }
7923
7924    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7925            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7926            throws PackageManagerException {
7927        final File scanFile = new File(pkg.codePath);
7928        if (pkg.applicationInfo.getCodePath() == null ||
7929                pkg.applicationInfo.getResourcePath() == null) {
7930            // Bail out. The resource and code paths haven't been set.
7931            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7932                    "Code and resource paths haven't been set correctly");
7933        }
7934
7935        // Apply policy
7936        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7937            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7938            if (pkg.applicationInfo.isDirectBootAware()) {
7939                // we're direct boot aware; set for all components
7940                for (PackageParser.Service s : pkg.services) {
7941                    s.info.encryptionAware = s.info.directBootAware = true;
7942                }
7943                for (PackageParser.Provider p : pkg.providers) {
7944                    p.info.encryptionAware = p.info.directBootAware = true;
7945                }
7946                for (PackageParser.Activity a : pkg.activities) {
7947                    a.info.encryptionAware = a.info.directBootAware = true;
7948                }
7949                for (PackageParser.Activity r : pkg.receivers) {
7950                    r.info.encryptionAware = r.info.directBootAware = true;
7951                }
7952            }
7953        } else {
7954            // Only allow system apps to be flagged as core apps.
7955            pkg.coreApp = false;
7956            // clear flags not applicable to regular apps
7957            pkg.applicationInfo.privateFlags &=
7958                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7959            pkg.applicationInfo.privateFlags &=
7960                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7961        }
7962        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7963
7964        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7965            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7966        }
7967
7968        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7969            enforceCodePolicy(pkg);
7970        }
7971
7972        if (mCustomResolverComponentName != null &&
7973                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7974            setUpCustomResolverActivity(pkg);
7975        }
7976
7977        if (pkg.packageName.equals("android")) {
7978            synchronized (mPackages) {
7979                if (mAndroidApplication != null) {
7980                    Slog.w(TAG, "*************************************************");
7981                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7982                    Slog.w(TAG, " file=" + scanFile);
7983                    Slog.w(TAG, "*************************************************");
7984                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7985                            "Core android package being redefined.  Skipping.");
7986                }
7987
7988                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7989                    // Set up information for our fall-back user intent resolution activity.
7990                    mPlatformPackage = pkg;
7991                    pkg.mVersionCode = mSdkVersion;
7992                    mAndroidApplication = pkg.applicationInfo;
7993
7994                    if (!mResolverReplaced) {
7995                        mResolveActivity.applicationInfo = mAndroidApplication;
7996                        mResolveActivity.name = ResolverActivity.class.getName();
7997                        mResolveActivity.packageName = mAndroidApplication.packageName;
7998                        mResolveActivity.processName = "system:ui";
7999                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8000                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8001                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8002                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8003                        mResolveActivity.exported = true;
8004                        mResolveActivity.enabled = true;
8005                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8006                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8007                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8008                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8009                                | ActivityInfo.CONFIG_ORIENTATION
8010                                | ActivityInfo.CONFIG_KEYBOARD
8011                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8012                        mResolveInfo.activityInfo = mResolveActivity;
8013                        mResolveInfo.priority = 0;
8014                        mResolveInfo.preferredOrder = 0;
8015                        mResolveInfo.match = 0;
8016                        mResolveComponentName = new ComponentName(
8017                                mAndroidApplication.packageName, mResolveActivity.name);
8018                    }
8019                }
8020            }
8021        }
8022
8023        if (DEBUG_PACKAGE_SCANNING) {
8024            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8025                Log.d(TAG, "Scanning package " + pkg.packageName);
8026        }
8027
8028        synchronized (mPackages) {
8029            if (mPackages.containsKey(pkg.packageName)
8030                    || mSharedLibraries.containsKey(pkg.packageName)) {
8031                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8032                        "Application package " + pkg.packageName
8033                                + " already installed.  Skipping duplicate.");
8034            }
8035
8036            // If we're only installing presumed-existing packages, require that the
8037            // scanned APK is both already known and at the path previously established
8038            // for it.  Previously unknown packages we pick up normally, but if we have an
8039            // a priori expectation about this package's install presence, enforce it.
8040            // With a singular exception for new system packages. When an OTA contains
8041            // a new system package, we allow the codepath to change from a system location
8042            // to the user-installed location. If we don't allow this change, any newer,
8043            // user-installed version of the application will be ignored.
8044            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8045                if (mExpectingBetter.containsKey(pkg.packageName)) {
8046                    logCriticalInfo(Log.WARN,
8047                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8048                } else {
8049                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8050                    if (known != null) {
8051                        if (DEBUG_PACKAGE_SCANNING) {
8052                            Log.d(TAG, "Examining " + pkg.codePath
8053                                    + " and requiring known paths " + known.codePathString
8054                                    + " & " + known.resourcePathString);
8055                        }
8056                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8057                                || !pkg.applicationInfo.getResourcePath().equals(
8058                                known.resourcePathString)) {
8059                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8060                                    "Application package " + pkg.packageName
8061                                            + " found at " + pkg.applicationInfo.getCodePath()
8062                                            + " but expected at " + known.codePathString
8063                                            + "; ignoring.");
8064                        }
8065                    }
8066                }
8067            }
8068        }
8069
8070        // Initialize package source and resource directories
8071        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8072        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8073
8074        SharedUserSetting suid = null;
8075        PackageSetting pkgSetting = null;
8076
8077        if (!isSystemApp(pkg)) {
8078            // Only system apps can use these features.
8079            pkg.mOriginalPackages = null;
8080            pkg.mRealPackage = null;
8081            pkg.mAdoptPermissions = null;
8082        }
8083
8084        // Getting the package setting may have a side-effect, so if we
8085        // are only checking if scan would succeed, stash a copy of the
8086        // old setting to restore at the end.
8087        PackageSetting nonMutatedPs = null;
8088
8089        // writer
8090        synchronized (mPackages) {
8091            if (pkg.mSharedUserId != null) {
8092                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8093                if (suid == null) {
8094                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8095                            "Creating application package " + pkg.packageName
8096                            + " for shared user failed");
8097                }
8098                if (DEBUG_PACKAGE_SCANNING) {
8099                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8100                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8101                                + "): packages=" + suid.packages);
8102                }
8103            }
8104
8105            // Check if we are renaming from an original package name.
8106            PackageSetting origPackage = null;
8107            String realName = null;
8108            if (pkg.mOriginalPackages != null) {
8109                // This package may need to be renamed to a previously
8110                // installed name.  Let's check on that...
8111                final String renamed = mSettings.getRenamedPackage(pkg.mRealPackage);
8112                if (pkg.mOriginalPackages.contains(renamed)) {
8113                    // This package had originally been installed as the
8114                    // original name, and we have already taken care of
8115                    // transitioning to the new one.  Just update the new
8116                    // one to continue using the old name.
8117                    realName = pkg.mRealPackage;
8118                    if (!pkg.packageName.equals(renamed)) {
8119                        // Callers into this function may have already taken
8120                        // care of renaming the package; only do it here if
8121                        // it is not already done.
8122                        pkg.setPackageName(renamed);
8123                    }
8124
8125                } else {
8126                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8127                        if ((origPackage = mSettings.peekPackageLPr(
8128                                pkg.mOriginalPackages.get(i))) != null) {
8129                            // We do have the package already installed under its
8130                            // original name...  should we use it?
8131                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8132                                // New package is not compatible with original.
8133                                origPackage = null;
8134                                continue;
8135                            } else if (origPackage.sharedUser != null) {
8136                                // Make sure uid is compatible between packages.
8137                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8138                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8139                                            + " to " + pkg.packageName + ": old uid "
8140                                            + origPackage.sharedUser.name
8141                                            + " differs from " + pkg.mSharedUserId);
8142                                    origPackage = null;
8143                                    continue;
8144                                }
8145                                // TODO: Add case when shared user id is added [b/28144775]
8146                            } else {
8147                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8148                                        + pkg.packageName + " to old name " + origPackage.name);
8149                            }
8150                            break;
8151                        }
8152                    }
8153                }
8154            }
8155
8156            if (mTransferedPackages.contains(pkg.packageName)) {
8157                Slog.w(TAG, "Package " + pkg.packageName
8158                        + " was transferred to another, but its .apk remains");
8159            }
8160
8161            // See comments in nonMutatedPs declaration
8162            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8163                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8164                if (foundPs != null) {
8165                    nonMutatedPs = new PackageSetting(foundPs);
8166                }
8167            }
8168
8169            // Just create the setting, don't add it yet. For already existing packages
8170            // the PkgSetting exists already and doesn't have to be created.
8171            pkgSetting = mSettings.getPackageWithBenefitsLPw(pkg, origPackage, realName, suid,
8172                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8173                    pkg.applicationInfo.primaryCpuAbi,
8174                    pkg.applicationInfo.secondaryCpuAbi,
8175                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8176                    user);
8177            if (pkgSetting == null) {
8178                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8179                        "Creating application package " + pkg.packageName + " failed");
8180            }
8181
8182            if (pkgSetting.origPackage != null) {
8183                // If we are first transitioning from an original package,
8184                // fix up the new package's name now.  We need to do this after
8185                // looking up the package under its new name, so getPackageLP
8186                // can take care of fiddling things correctly.
8187                pkg.setPackageName(origPackage.name);
8188
8189                // File a report about this.
8190                String msg = "New package " + pkgSetting.realName
8191                        + " renamed to replace old package " + pkgSetting.name;
8192                reportSettingsProblem(Log.WARN, msg);
8193
8194                // Make a note of it.
8195                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8196                    mTransferedPackages.add(origPackage.name);
8197                }
8198
8199                // No longer need to retain this.
8200                pkgSetting.origPackage = null;
8201            }
8202
8203            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8204                // Make a note of it.
8205                mTransferedPackages.add(pkg.packageName);
8206            }
8207
8208            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8209                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8210            }
8211
8212            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8213                // Check all shared libraries and map to their actual file path.
8214                // We only do this here for apps not on a system dir, because those
8215                // are the only ones that can fail an install due to this.  We
8216                // will take care of the system apps by updating all of their
8217                // library paths after the scan is done.
8218                updateSharedLibrariesLPw(pkg, null);
8219            }
8220
8221            if (mFoundPolicyFile) {
8222                SELinuxMMAC.assignSeinfoValue(pkg);
8223            }
8224
8225            pkg.applicationInfo.uid = pkgSetting.appId;
8226            pkg.mExtras = pkgSetting;
8227            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8228                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8229                    // We just determined the app is signed correctly, so bring
8230                    // over the latest parsed certs.
8231                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8232                } else {
8233                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8234                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8235                                "Package " + pkg.packageName + " upgrade keys do not match the "
8236                                + "previously installed version");
8237                    } else {
8238                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8239                        String msg = "System package " + pkg.packageName
8240                            + " signature changed; retaining data.";
8241                        reportSettingsProblem(Log.WARN, msg);
8242                    }
8243                }
8244            } else {
8245                try {
8246                    verifySignaturesLP(pkgSetting, pkg);
8247                    // We just determined the app is signed correctly, so bring
8248                    // over the latest parsed certs.
8249                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8250                } catch (PackageManagerException e) {
8251                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8252                        throw e;
8253                    }
8254                    // The signature has changed, but this package is in the system
8255                    // image...  let's recover!
8256                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8257                    // However...  if this package is part of a shared user, but it
8258                    // doesn't match the signature of the shared user, let's fail.
8259                    // What this means is that you can't change the signatures
8260                    // associated with an overall shared user, which doesn't seem all
8261                    // that unreasonable.
8262                    if (pkgSetting.sharedUser != null) {
8263                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8264                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8265                            throw new PackageManagerException(
8266                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8267                                            "Signature mismatch for shared user: "
8268                                            + pkgSetting.sharedUser);
8269                        }
8270                    }
8271                    // File a report about this.
8272                    String msg = "System package " + pkg.packageName
8273                        + " signature changed; retaining data.";
8274                    reportSettingsProblem(Log.WARN, msg);
8275                }
8276            }
8277            // Verify that this new package doesn't have any content providers
8278            // that conflict with existing packages.  Only do this if the
8279            // package isn't already installed, since we don't want to break
8280            // things that are installed.
8281            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8282                final int N = pkg.providers.size();
8283                int i;
8284                for (i=0; i<N; i++) {
8285                    PackageParser.Provider p = pkg.providers.get(i);
8286                    if (p.info.authority != null) {
8287                        String names[] = p.info.authority.split(";");
8288                        for (int j = 0; j < names.length; j++) {
8289                            if (mProvidersByAuthority.containsKey(names[j])) {
8290                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8291                                final String otherPackageName =
8292                                        ((other != null && other.getComponentName() != null) ?
8293                                                other.getComponentName().getPackageName() : "?");
8294                                throw new PackageManagerException(
8295                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8296                                                "Can't install because provider name " + names[j]
8297                                                + " (in package " + pkg.applicationInfo.packageName
8298                                                + ") is already used by " + otherPackageName);
8299                            }
8300                        }
8301                    }
8302                }
8303            }
8304
8305            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8306                // This package wants to adopt ownership of permissions from
8307                // another package.
8308                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8309                    final String origName = pkg.mAdoptPermissions.get(i);
8310                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8311                    if (orig != null) {
8312                        if (verifyPackageUpdateLPr(orig, pkg)) {
8313                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8314                                    + pkg.packageName);
8315                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8316                        }
8317                    }
8318                }
8319            }
8320        }
8321
8322        final String pkgName = pkg.packageName;
8323
8324        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8325        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8326        pkg.applicationInfo.processName = fixProcessName(
8327                pkg.applicationInfo.packageName,
8328                pkg.applicationInfo.processName,
8329                pkg.applicationInfo.uid);
8330
8331        if (pkg != mPlatformPackage) {
8332            // Get all of our default paths setup
8333            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8334        }
8335
8336        final String path = scanFile.getPath();
8337        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8338
8339        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8340            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8341            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /*extractLibs*/);
8342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8343
8344            // Some system apps still use directory structure for native libraries
8345            // in which case we might end up not detecting abi solely based on apk
8346            // structure. Try to detect abi based on directory structure.
8347            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8348                    pkg.applicationInfo.primaryCpuAbi == null) {
8349                setBundledAppAbisAndRoots(pkg, pkgSetting);
8350                setNativeLibraryPaths(pkg);
8351            }
8352
8353        } else {
8354            if ((scanFlags & SCAN_MOVE) != 0) {
8355                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8356                // but we already have this packages package info in the PackageSetting. We just
8357                // use that and derive the native library path based on the new codepath.
8358                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8359                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8360            }
8361
8362            // Set native library paths again. For moves, the path will be updated based on the
8363            // ABIs we've determined above. For non-moves, the path will be updated based on the
8364            // ABIs we determined during compilation, but the path will depend on the final
8365            // package path (after the rename away from the stage path).
8366            setNativeLibraryPaths(pkg);
8367        }
8368
8369        // This is a special case for the "system" package, where the ABI is
8370        // dictated by the zygote configuration (and init.rc). We should keep track
8371        // of this ABI so that we can deal with "normal" applications that run under
8372        // the same UID correctly.
8373        if (mPlatformPackage == pkg) {
8374            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8375                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8376        }
8377
8378        // If there's a mismatch between the abi-override in the package setting
8379        // and the abiOverride specified for the install. Warn about this because we
8380        // would've already compiled the app without taking the package setting into
8381        // account.
8382        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8383            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8384                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8385                        " for package " + pkg.packageName);
8386            }
8387        }
8388
8389        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8390        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8391        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8392
8393        // Copy the derived override back to the parsed package, so that we can
8394        // update the package settings accordingly.
8395        pkg.cpuAbiOverride = cpuAbiOverride;
8396
8397        if (DEBUG_ABI_SELECTION) {
8398            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8399                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8400                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8401        }
8402
8403        // Push the derived path down into PackageSettings so we know what to
8404        // clean up at uninstall time.
8405        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8406
8407        if (DEBUG_ABI_SELECTION) {
8408            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8409                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8410                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8411        }
8412
8413        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8414            // We don't do this here during boot because we can do it all
8415            // at once after scanning all existing packages.
8416            //
8417            // We also do this *before* we perform dexopt on this package, so that
8418            // we can avoid redundant dexopts, and also to make sure we've got the
8419            // code and package path correct.
8420            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8421                    pkg, true /* boot complete */);
8422        }
8423
8424        if (mFactoryTest && pkg.requestedPermissions.contains(
8425                android.Manifest.permission.FACTORY_TEST)) {
8426            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8427        }
8428
8429        if (isSystemApp(pkg)) {
8430            pkgSetting.isOrphaned = true;
8431        }
8432
8433        ArrayList<PackageParser.Package> clientLibPkgs = null;
8434
8435        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8436            if (nonMutatedPs != null) {
8437                synchronized (mPackages) {
8438                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8439                }
8440            }
8441            return pkg;
8442        }
8443
8444        // Only privileged apps and updated privileged apps can add child packages.
8445        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8446            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8447                throw new PackageManagerException("Only privileged apps and updated "
8448                        + "privileged apps can add child packages. Ignoring package "
8449                        + pkg.packageName);
8450            }
8451            final int childCount = pkg.childPackages.size();
8452            for (int i = 0; i < childCount; i++) {
8453                PackageParser.Package childPkg = pkg.childPackages.get(i);
8454                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8455                        childPkg.packageName)) {
8456                    throw new PackageManagerException("Cannot override a child package of "
8457                            + "another disabled system app. Ignoring package " + pkg.packageName);
8458                }
8459            }
8460        }
8461
8462        // writer
8463        synchronized (mPackages) {
8464            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8465                // Only system apps can add new shared libraries.
8466                if (pkg.libraryNames != null) {
8467                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8468                        String name = pkg.libraryNames.get(i);
8469                        boolean allowed = false;
8470                        if (pkg.isUpdatedSystemApp()) {
8471                            // New library entries can only be added through the
8472                            // system image.  This is important to get rid of a lot
8473                            // of nasty edge cases: for example if we allowed a non-
8474                            // system update of the app to add a library, then uninstalling
8475                            // the update would make the library go away, and assumptions
8476                            // we made such as through app install filtering would now
8477                            // have allowed apps on the device which aren't compatible
8478                            // with it.  Better to just have the restriction here, be
8479                            // conservative, and create many fewer cases that can negatively
8480                            // impact the user experience.
8481                            final PackageSetting sysPs = mSettings
8482                                    .getDisabledSystemPkgLPr(pkg.packageName);
8483                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8484                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8485                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8486                                        allowed = true;
8487                                        break;
8488                                    }
8489                                }
8490                            }
8491                        } else {
8492                            allowed = true;
8493                        }
8494                        if (allowed) {
8495                            if (!mSharedLibraries.containsKey(name)) {
8496                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8497                            } else if (!name.equals(pkg.packageName)) {
8498                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8499                                        + name + " already exists; skipping");
8500                            }
8501                        } else {
8502                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8503                                    + name + " that is not declared on system image; skipping");
8504                        }
8505                    }
8506                    if ((scanFlags & SCAN_BOOTING) == 0) {
8507                        // If we are not booting, we need to update any applications
8508                        // that are clients of our shared library.  If we are booting,
8509                        // this will all be done once the scan is complete.
8510                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8511                    }
8512                }
8513            }
8514        }
8515
8516        if ((scanFlags & SCAN_BOOTING) != 0) {
8517            // No apps can run during boot scan, so they don't need to be frozen
8518        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8519            // Caller asked to not kill app, so it's probably not frozen
8520        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8521            // Caller asked us to ignore frozen check for some reason; they
8522            // probably didn't know the package name
8523        } else {
8524            // We're doing major surgery on this package, so it better be frozen
8525            // right now to keep it from launching
8526            checkPackageFrozen(pkgName);
8527        }
8528
8529        // Also need to kill any apps that are dependent on the library.
8530        if (clientLibPkgs != null) {
8531            for (int i=0; i<clientLibPkgs.size(); i++) {
8532                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8533                killApplication(clientPkg.applicationInfo.packageName,
8534                        clientPkg.applicationInfo.uid, "update lib");
8535            }
8536        }
8537
8538        // Make sure we're not adding any bogus keyset info
8539        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8540        ksms.assertScannedPackageValid(pkg);
8541
8542        // writer
8543        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8544
8545        boolean createIdmapFailed = false;
8546        synchronized (mPackages) {
8547            // We don't expect installation to fail beyond this point
8548
8549            if (pkgSetting.pkg != null) {
8550                // Note that |user| might be null during the initial boot scan. If a codePath
8551                // for an app has changed during a boot scan, it's due to an app update that's
8552                // part of the system partition and marker changes must be applied to all users.
8553                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8554                    (user != null) ? user : UserHandle.ALL);
8555            }
8556
8557            // Add the new setting to mSettings
8558            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8559            // Add the new setting to mPackages
8560            mPackages.put(pkg.applicationInfo.packageName, pkg);
8561            // Make sure we don't accidentally delete its data.
8562            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8563            while (iter.hasNext()) {
8564                PackageCleanItem item = iter.next();
8565                if (pkgName.equals(item.packageName)) {
8566                    iter.remove();
8567                }
8568            }
8569
8570            // Take care of first install / last update times.
8571            if (currentTime != 0) {
8572                if (pkgSetting.firstInstallTime == 0) {
8573                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8574                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8575                    pkgSetting.lastUpdateTime = currentTime;
8576                }
8577            } else if (pkgSetting.firstInstallTime == 0) {
8578                // We need *something*.  Take time time stamp of the file.
8579                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8580            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8581                if (scanFileTime != pkgSetting.timeStamp) {
8582                    // A package on the system image has changed; consider this
8583                    // to be an update.
8584                    pkgSetting.lastUpdateTime = scanFileTime;
8585                }
8586            }
8587
8588            // Add the package's KeySets to the global KeySetManagerService
8589            ksms.addScannedPackageLPw(pkg);
8590
8591            int N = pkg.providers.size();
8592            StringBuilder r = null;
8593            int i;
8594            for (i=0; i<N; i++) {
8595                PackageParser.Provider p = pkg.providers.get(i);
8596                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8597                        p.info.processName, pkg.applicationInfo.uid);
8598                mProviders.addProvider(p);
8599                p.syncable = p.info.isSyncable;
8600                if (p.info.authority != null) {
8601                    String names[] = p.info.authority.split(";");
8602                    p.info.authority = null;
8603                    for (int j = 0; j < names.length; j++) {
8604                        if (j == 1 && p.syncable) {
8605                            // We only want the first authority for a provider to possibly be
8606                            // syncable, so if we already added this provider using a different
8607                            // authority clear the syncable flag. We copy the provider before
8608                            // changing it because the mProviders object contains a reference
8609                            // to a provider that we don't want to change.
8610                            // Only do this for the second authority since the resulting provider
8611                            // object can be the same for all future authorities for this provider.
8612                            p = new PackageParser.Provider(p);
8613                            p.syncable = false;
8614                        }
8615                        if (!mProvidersByAuthority.containsKey(names[j])) {
8616                            mProvidersByAuthority.put(names[j], p);
8617                            if (p.info.authority == null) {
8618                                p.info.authority = names[j];
8619                            } else {
8620                                p.info.authority = p.info.authority + ";" + names[j];
8621                            }
8622                            if (DEBUG_PACKAGE_SCANNING) {
8623                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8624                                    Log.d(TAG, "Registered content provider: " + names[j]
8625                                            + ", className = " + p.info.name + ", isSyncable = "
8626                                            + p.info.isSyncable);
8627                            }
8628                        } else {
8629                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8630                            Slog.w(TAG, "Skipping provider name " + names[j] +
8631                                    " (in package " + pkg.applicationInfo.packageName +
8632                                    "): name already used by "
8633                                    + ((other != null && other.getComponentName() != null)
8634                                            ? other.getComponentName().getPackageName() : "?"));
8635                        }
8636                    }
8637                }
8638                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8639                    if (r == null) {
8640                        r = new StringBuilder(256);
8641                    } else {
8642                        r.append(' ');
8643                    }
8644                    r.append(p.info.name);
8645                }
8646            }
8647            if (r != null) {
8648                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8649            }
8650
8651            N = pkg.services.size();
8652            r = null;
8653            for (i=0; i<N; i++) {
8654                PackageParser.Service s = pkg.services.get(i);
8655                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8656                        s.info.processName, pkg.applicationInfo.uid);
8657                mServices.addService(s);
8658                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8659                    if (r == null) {
8660                        r = new StringBuilder(256);
8661                    } else {
8662                        r.append(' ');
8663                    }
8664                    r.append(s.info.name);
8665                }
8666            }
8667            if (r != null) {
8668                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8669            }
8670
8671            N = pkg.receivers.size();
8672            r = null;
8673            for (i=0; i<N; i++) {
8674                PackageParser.Activity a = pkg.receivers.get(i);
8675                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8676                        a.info.processName, pkg.applicationInfo.uid);
8677                mReceivers.addActivity(a, "receiver");
8678                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8679                    if (r == null) {
8680                        r = new StringBuilder(256);
8681                    } else {
8682                        r.append(' ');
8683                    }
8684                    r.append(a.info.name);
8685                }
8686            }
8687            if (r != null) {
8688                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8689            }
8690
8691            N = pkg.activities.size();
8692            r = null;
8693            for (i=0; i<N; i++) {
8694                PackageParser.Activity a = pkg.activities.get(i);
8695                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8696                        a.info.processName, pkg.applicationInfo.uid);
8697                mActivities.addActivity(a, "activity");
8698                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8699                    if (r == null) {
8700                        r = new StringBuilder(256);
8701                    } else {
8702                        r.append(' ');
8703                    }
8704                    r.append(a.info.name);
8705                }
8706            }
8707            if (r != null) {
8708                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8709            }
8710
8711            N = pkg.permissionGroups.size();
8712            r = null;
8713            for (i=0; i<N; i++) {
8714                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8715                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8716                final String curPackageName = cur == null ? null : cur.info.packageName;
8717                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8718                if (cur == null || isPackageUpdate) {
8719                    mPermissionGroups.put(pg.info.name, pg);
8720                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8721                        if (r == null) {
8722                            r = new StringBuilder(256);
8723                        } else {
8724                            r.append(' ');
8725                        }
8726                        if (isPackageUpdate) {
8727                            r.append("UPD:");
8728                        }
8729                        r.append(pg.info.name);
8730                    }
8731                } else {
8732                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8733                            + pg.info.packageName + " ignored: original from "
8734                            + cur.info.packageName);
8735                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8736                        if (r == null) {
8737                            r = new StringBuilder(256);
8738                        } else {
8739                            r.append(' ');
8740                        }
8741                        r.append("DUP:");
8742                        r.append(pg.info.name);
8743                    }
8744                }
8745            }
8746            if (r != null) {
8747                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8748            }
8749
8750            N = pkg.permissions.size();
8751            r = null;
8752            for (i=0; i<N; i++) {
8753                PackageParser.Permission p = pkg.permissions.get(i);
8754
8755                // Assume by default that we did not install this permission into the system.
8756                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8757
8758                // Now that permission groups have a special meaning, we ignore permission
8759                // groups for legacy apps to prevent unexpected behavior. In particular,
8760                // permissions for one app being granted to someone just becase they happen
8761                // to be in a group defined by another app (before this had no implications).
8762                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8763                    p.group = mPermissionGroups.get(p.info.group);
8764                    // Warn for a permission in an unknown group.
8765                    if (p.info.group != null && p.group == null) {
8766                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8767                                + p.info.packageName + " in an unknown group " + p.info.group);
8768                    }
8769                }
8770
8771                ArrayMap<String, BasePermission> permissionMap =
8772                        p.tree ? mSettings.mPermissionTrees
8773                                : mSettings.mPermissions;
8774                BasePermission bp = permissionMap.get(p.info.name);
8775
8776                // Allow system apps to redefine non-system permissions
8777                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8778                    final boolean currentOwnerIsSystem = (bp.perm != null
8779                            && isSystemApp(bp.perm.owner));
8780                    if (isSystemApp(p.owner)) {
8781                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8782                            // It's a built-in permission and no owner, take ownership now
8783                            bp.packageSetting = pkgSetting;
8784                            bp.perm = p;
8785                            bp.uid = pkg.applicationInfo.uid;
8786                            bp.sourcePackage = p.info.packageName;
8787                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8788                        } else if (!currentOwnerIsSystem) {
8789                            String msg = "New decl " + p.owner + " of permission  "
8790                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8791                            reportSettingsProblem(Log.WARN, msg);
8792                            bp = null;
8793                        }
8794                    }
8795                }
8796
8797                if (bp == null) {
8798                    bp = new BasePermission(p.info.name, p.info.packageName,
8799                            BasePermission.TYPE_NORMAL);
8800                    permissionMap.put(p.info.name, bp);
8801                }
8802
8803                if (bp.perm == null) {
8804                    if (bp.sourcePackage == null
8805                            || bp.sourcePackage.equals(p.info.packageName)) {
8806                        BasePermission tree = findPermissionTreeLP(p.info.name);
8807                        if (tree == null
8808                                || tree.sourcePackage.equals(p.info.packageName)) {
8809                            bp.packageSetting = pkgSetting;
8810                            bp.perm = p;
8811                            bp.uid = pkg.applicationInfo.uid;
8812                            bp.sourcePackage = p.info.packageName;
8813                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8814                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8815                                if (r == null) {
8816                                    r = new StringBuilder(256);
8817                                } else {
8818                                    r.append(' ');
8819                                }
8820                                r.append(p.info.name);
8821                            }
8822                        } else {
8823                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8824                                    + p.info.packageName + " ignored: base tree "
8825                                    + tree.name + " is from package "
8826                                    + tree.sourcePackage);
8827                        }
8828                    } else {
8829                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8830                                + p.info.packageName + " ignored: original from "
8831                                + bp.sourcePackage);
8832                    }
8833                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8834                    if (r == null) {
8835                        r = new StringBuilder(256);
8836                    } else {
8837                        r.append(' ');
8838                    }
8839                    r.append("DUP:");
8840                    r.append(p.info.name);
8841                }
8842                if (bp.perm == p) {
8843                    bp.protectionLevel = p.info.protectionLevel;
8844                }
8845            }
8846
8847            if (r != null) {
8848                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8849            }
8850
8851            N = pkg.instrumentation.size();
8852            r = null;
8853            for (i=0; i<N; i++) {
8854                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8855                a.info.packageName = pkg.applicationInfo.packageName;
8856                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8857                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8858                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8859                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8860                a.info.dataDir = pkg.applicationInfo.dataDir;
8861                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8862                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8863
8864                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8865                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8866                mInstrumentation.put(a.getComponentName(), a);
8867                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8868                    if (r == null) {
8869                        r = new StringBuilder(256);
8870                    } else {
8871                        r.append(' ');
8872                    }
8873                    r.append(a.info.name);
8874                }
8875            }
8876            if (r != null) {
8877                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8878            }
8879
8880            if (pkg.protectedBroadcasts != null) {
8881                N = pkg.protectedBroadcasts.size();
8882                for (i=0; i<N; i++) {
8883                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8884                }
8885            }
8886
8887            pkgSetting.setTimeStamp(scanFileTime);
8888
8889            // Create idmap files for pairs of (packages, overlay packages).
8890            // Note: "android", ie framework-res.apk, is handled by native layers.
8891            if (pkg.mOverlayTarget != null) {
8892                // This is an overlay package.
8893                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8894                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8895                        mOverlays.put(pkg.mOverlayTarget,
8896                                new ArrayMap<String, PackageParser.Package>());
8897                    }
8898                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8899                    map.put(pkg.packageName, pkg);
8900                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8901                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8902                        createIdmapFailed = true;
8903                    }
8904                }
8905            } else if (mOverlays.containsKey(pkg.packageName) &&
8906                    !pkg.packageName.equals("android")) {
8907                // This is a regular package, with one or more known overlay packages.
8908                createIdmapsForPackageLI(pkg);
8909            }
8910        }
8911
8912        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8913
8914        if (createIdmapFailed) {
8915            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8916                    "scanPackageLI failed to createIdmap");
8917        }
8918        return pkg;
8919    }
8920
8921    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8922            PackageParser.Package update, UserHandle user) {
8923        if (existing.applicationInfo == null || update.applicationInfo == null) {
8924            // This isn't due to an app installation.
8925            return;
8926        }
8927
8928        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8929        final File newCodePath = new File(update.applicationInfo.getCodePath());
8930
8931        // The codePath hasn't changed, so there's nothing for us to do.
8932        if (Objects.equals(oldCodePath, newCodePath)) {
8933            return;
8934        }
8935
8936        File canonicalNewCodePath;
8937        try {
8938            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8939        } catch (IOException e) {
8940            Slog.w(TAG, "Failed to get canonical path.", e);
8941            return;
8942        }
8943
8944        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8945        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8946        // that the last component of the path (i.e, the name) doesn't need canonicalization
8947        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8948        // but may change in the future. Hopefully this function won't exist at that point.
8949        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8950                oldCodePath.getName());
8951
8952        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8953        // with "@".
8954        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8955        if (!oldMarkerPrefix.endsWith("@")) {
8956            oldMarkerPrefix += "@";
8957        }
8958        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8959        if (!newMarkerPrefix.endsWith("@")) {
8960            newMarkerPrefix += "@";
8961        }
8962
8963        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8964        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8965        for (String updatedPath : updatedPaths) {
8966            String updatedPathName = new File(updatedPath).getName();
8967            markerSuffixes.add(updatedPathName.replace('/', '@'));
8968        }
8969
8970        for (int userId : resolveUserIds(user.getIdentifier())) {
8971            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8972
8973            for (String markerSuffix : markerSuffixes) {
8974                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8975                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8976                if (oldForeignUseMark.exists()) {
8977                    try {
8978                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8979                                newForeignUseMark.getAbsolutePath());
8980                    } catch (ErrnoException e) {
8981                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8982                        oldForeignUseMark.delete();
8983                    }
8984                }
8985            }
8986        }
8987    }
8988
8989    /**
8990     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8991     * is derived purely on the basis of the contents of {@code scanFile} and
8992     * {@code cpuAbiOverride}.
8993     *
8994     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8995     */
8996    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8997                                 String cpuAbiOverride, boolean extractLibs)
8998            throws PackageManagerException {
8999        // TODO: We can probably be smarter about this stuff. For installed apps,
9000        // we can calculate this information at install time once and for all. For
9001        // system apps, we can probably assume that this information doesn't change
9002        // after the first boot scan. As things stand, we do lots of unnecessary work.
9003
9004        // Give ourselves some initial paths; we'll come back for another
9005        // pass once we've determined ABI below.
9006        setNativeLibraryPaths(pkg);
9007
9008        // We would never need to extract libs for forward-locked and external packages,
9009        // since the container service will do it for us. We shouldn't attempt to
9010        // extract libs from system app when it was not updated.
9011        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9012                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9013            extractLibs = false;
9014        }
9015
9016        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9017        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9018
9019        NativeLibraryHelper.Handle handle = null;
9020        try {
9021            handle = NativeLibraryHelper.Handle.create(pkg);
9022            // TODO(multiArch): This can be null for apps that didn't go through the
9023            // usual installation process. We can calculate it again, like we
9024            // do during install time.
9025            //
9026            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9027            // unnecessary.
9028            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9029
9030            // Null out the abis so that they can be recalculated.
9031            pkg.applicationInfo.primaryCpuAbi = null;
9032            pkg.applicationInfo.secondaryCpuAbi = null;
9033            if (isMultiArch(pkg.applicationInfo)) {
9034                // Warn if we've set an abiOverride for multi-lib packages..
9035                // By definition, we need to copy both 32 and 64 bit libraries for
9036                // such packages.
9037                if (pkg.cpuAbiOverride != null
9038                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9039                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9040                }
9041
9042                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9043                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9044                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9045                    if (extractLibs) {
9046                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9047                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9048                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9049                                useIsaSpecificSubdirs);
9050                    } else {
9051                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9052                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9053                    }
9054                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9055                }
9056
9057                maybeThrowExceptionForMultiArchCopy(
9058                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9059
9060                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9061                    if (extractLibs) {
9062                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9063                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9064                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9065                                useIsaSpecificSubdirs);
9066                    } else {
9067                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9068                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9069                    }
9070                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9071                }
9072
9073                maybeThrowExceptionForMultiArchCopy(
9074                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9075
9076                if (abi64 >= 0) {
9077                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9078                }
9079
9080                if (abi32 >= 0) {
9081                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9082                    if (abi64 >= 0) {
9083                        if (pkg.use32bitAbi) {
9084                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9085                            pkg.applicationInfo.primaryCpuAbi = abi;
9086                        } else {
9087                            pkg.applicationInfo.secondaryCpuAbi = abi;
9088                        }
9089                    } else {
9090                        pkg.applicationInfo.primaryCpuAbi = abi;
9091                    }
9092                }
9093
9094            } else {
9095                String[] abiList = (cpuAbiOverride != null) ?
9096                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9097
9098                // Enable gross and lame hacks for apps that are built with old
9099                // SDK tools. We must scan their APKs for renderscript bitcode and
9100                // not launch them if it's present. Don't bother checking on devices
9101                // that don't have 64 bit support.
9102                boolean needsRenderScriptOverride = false;
9103                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9104                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9105                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9106                    needsRenderScriptOverride = true;
9107                }
9108
9109                final int copyRet;
9110                if (extractLibs) {
9111                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9112                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9113                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9114                } else {
9115                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9116                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9117                }
9118                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9119
9120                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9121                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9122                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9123                }
9124
9125                if (copyRet >= 0) {
9126                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9127                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9128                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9129                } else if (needsRenderScriptOverride) {
9130                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9131                }
9132            }
9133        } catch (IOException ioe) {
9134            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9135        } finally {
9136            IoUtils.closeQuietly(handle);
9137        }
9138
9139        // Now that we've calculated the ABIs and determined if it's an internal app,
9140        // we will go ahead and populate the nativeLibraryPath.
9141        setNativeLibraryPaths(pkg);
9142    }
9143
9144    /**
9145     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9146     * i.e, so that all packages can be run inside a single process if required.
9147     *
9148     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9149     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9150     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9151     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9152     * updating a package that belongs to a shared user.
9153     *
9154     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9155     * adds unnecessary complexity.
9156     */
9157    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9158            PackageParser.Package scannedPackage, boolean bootComplete) {
9159        String requiredInstructionSet = null;
9160        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9161            requiredInstructionSet = VMRuntime.getInstructionSet(
9162                     scannedPackage.applicationInfo.primaryCpuAbi);
9163        }
9164
9165        PackageSetting requirer = null;
9166        for (PackageSetting ps : packagesForUser) {
9167            // If packagesForUser contains scannedPackage, we skip it. This will happen
9168            // when scannedPackage is an update of an existing package. Without this check,
9169            // we will never be able to change the ABI of any package belonging to a shared
9170            // user, even if it's compatible with other packages.
9171            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9172                if (ps.primaryCpuAbiString == null) {
9173                    continue;
9174                }
9175
9176                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9177                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9178                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9179                    // this but there's not much we can do.
9180                    String errorMessage = "Instruction set mismatch, "
9181                            + ((requirer == null) ? "[caller]" : requirer)
9182                            + " requires " + requiredInstructionSet + " whereas " + ps
9183                            + " requires " + instructionSet;
9184                    Slog.w(TAG, errorMessage);
9185                }
9186
9187                if (requiredInstructionSet == null) {
9188                    requiredInstructionSet = instructionSet;
9189                    requirer = ps;
9190                }
9191            }
9192        }
9193
9194        if (requiredInstructionSet != null) {
9195            String adjustedAbi;
9196            if (requirer != null) {
9197                // requirer != null implies that either scannedPackage was null or that scannedPackage
9198                // did not require an ABI, in which case we have to adjust scannedPackage to match
9199                // the ABI of the set (which is the same as requirer's ABI)
9200                adjustedAbi = requirer.primaryCpuAbiString;
9201                if (scannedPackage != null) {
9202                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9203                }
9204            } else {
9205                // requirer == null implies that we're updating all ABIs in the set to
9206                // match scannedPackage.
9207                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9208            }
9209
9210            for (PackageSetting ps : packagesForUser) {
9211                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9212                    if (ps.primaryCpuAbiString != null) {
9213                        continue;
9214                    }
9215
9216                    ps.primaryCpuAbiString = adjustedAbi;
9217                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9218                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9219                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9220                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9221                                + " (requirer="
9222                                + (requirer == null ? "null" : requirer.pkg.packageName)
9223                                + ", scannedPackage="
9224                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9225                                + ")");
9226                        try {
9227                            mInstaller.rmdex(ps.codePathString,
9228                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9229                        } catch (InstallerException ignored) {
9230                        }
9231                    }
9232                }
9233            }
9234        }
9235    }
9236
9237    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9238        synchronized (mPackages) {
9239            mResolverReplaced = true;
9240            // Set up information for custom user intent resolution activity.
9241            mResolveActivity.applicationInfo = pkg.applicationInfo;
9242            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9243            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9244            mResolveActivity.processName = pkg.applicationInfo.packageName;
9245            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9246            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9247                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9248            mResolveActivity.theme = 0;
9249            mResolveActivity.exported = true;
9250            mResolveActivity.enabled = true;
9251            mResolveInfo.activityInfo = mResolveActivity;
9252            mResolveInfo.priority = 0;
9253            mResolveInfo.preferredOrder = 0;
9254            mResolveInfo.match = 0;
9255            mResolveComponentName = mCustomResolverComponentName;
9256            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9257                    mResolveComponentName);
9258        }
9259    }
9260
9261    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9262        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9263
9264        // Set up information for ephemeral installer activity
9265        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9266        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9267        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9268        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9269        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9270        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9271                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9272        mEphemeralInstallerActivity.theme = 0;
9273        mEphemeralInstallerActivity.exported = true;
9274        mEphemeralInstallerActivity.enabled = true;
9275        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9276        mEphemeralInstallerInfo.priority = 0;
9277        mEphemeralInstallerInfo.preferredOrder = 1;
9278        mEphemeralInstallerInfo.isDefault = true;
9279        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9280                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9281
9282        if (DEBUG_EPHEMERAL) {
9283            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9284        }
9285    }
9286
9287    private static String calculateBundledApkRoot(final String codePathString) {
9288        final File codePath = new File(codePathString);
9289        final File codeRoot;
9290        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9291            codeRoot = Environment.getRootDirectory();
9292        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9293            codeRoot = Environment.getOemDirectory();
9294        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9295            codeRoot = Environment.getVendorDirectory();
9296        } else {
9297            // Unrecognized code path; take its top real segment as the apk root:
9298            // e.g. /something/app/blah.apk => /something
9299            try {
9300                File f = codePath.getCanonicalFile();
9301                File parent = f.getParentFile();    // non-null because codePath is a file
9302                File tmp;
9303                while ((tmp = parent.getParentFile()) != null) {
9304                    f = parent;
9305                    parent = tmp;
9306                }
9307                codeRoot = f;
9308                Slog.w(TAG, "Unrecognized code path "
9309                        + codePath + " - using " + codeRoot);
9310            } catch (IOException e) {
9311                // Can't canonicalize the code path -- shenanigans?
9312                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9313                return Environment.getRootDirectory().getPath();
9314            }
9315        }
9316        return codeRoot.getPath();
9317    }
9318
9319    /**
9320     * Derive and set the location of native libraries for the given package,
9321     * which varies depending on where and how the package was installed.
9322     */
9323    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9324        final ApplicationInfo info = pkg.applicationInfo;
9325        final String codePath = pkg.codePath;
9326        final File codeFile = new File(codePath);
9327        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9328        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9329
9330        info.nativeLibraryRootDir = null;
9331        info.nativeLibraryRootRequiresIsa = false;
9332        info.nativeLibraryDir = null;
9333        info.secondaryNativeLibraryDir = null;
9334
9335        if (isApkFile(codeFile)) {
9336            // Monolithic install
9337            if (bundledApp) {
9338                // If "/system/lib64/apkname" exists, assume that is the per-package
9339                // native library directory to use; otherwise use "/system/lib/apkname".
9340                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9341                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9342                        getPrimaryInstructionSet(info));
9343
9344                // This is a bundled system app so choose the path based on the ABI.
9345                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9346                // is just the default path.
9347                final String apkName = deriveCodePathName(codePath);
9348                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9349                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9350                        apkName).getAbsolutePath();
9351
9352                if (info.secondaryCpuAbi != null) {
9353                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9354                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9355                            secondaryLibDir, apkName).getAbsolutePath();
9356                }
9357            } else if (asecApp) {
9358                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9359                        .getAbsolutePath();
9360            } else {
9361                final String apkName = deriveCodePathName(codePath);
9362                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9363                        .getAbsolutePath();
9364            }
9365
9366            info.nativeLibraryRootRequiresIsa = false;
9367            info.nativeLibraryDir = info.nativeLibraryRootDir;
9368        } else {
9369            // Cluster install
9370            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9371            info.nativeLibraryRootRequiresIsa = true;
9372
9373            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9374                    getPrimaryInstructionSet(info)).getAbsolutePath();
9375
9376            if (info.secondaryCpuAbi != null) {
9377                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9378                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9379            }
9380        }
9381    }
9382
9383    /**
9384     * Calculate the abis and roots for a bundled app. These can uniquely
9385     * be determined from the contents of the system partition, i.e whether
9386     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9387     * of this information, and instead assume that the system was built
9388     * sensibly.
9389     */
9390    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9391                                           PackageSetting pkgSetting) {
9392        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9393
9394        // If "/system/lib64/apkname" exists, assume that is the per-package
9395        // native library directory to use; otherwise use "/system/lib/apkname".
9396        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9397        setBundledAppAbi(pkg, apkRoot, apkName);
9398        // pkgSetting might be null during rescan following uninstall of updates
9399        // to a bundled app, so accommodate that possibility.  The settings in
9400        // that case will be established later from the parsed package.
9401        //
9402        // If the settings aren't null, sync them up with what we've just derived.
9403        // note that apkRoot isn't stored in the package settings.
9404        if (pkgSetting != null) {
9405            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9406            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9407        }
9408    }
9409
9410    /**
9411     * Deduces the ABI of a bundled app and sets the relevant fields on the
9412     * parsed pkg object.
9413     *
9414     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9415     *        under which system libraries are installed.
9416     * @param apkName the name of the installed package.
9417     */
9418    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9419        final File codeFile = new File(pkg.codePath);
9420
9421        final boolean has64BitLibs;
9422        final boolean has32BitLibs;
9423        if (isApkFile(codeFile)) {
9424            // Monolithic install
9425            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9426            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9427        } else {
9428            // Cluster install
9429            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9430            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9431                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9432                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9433                has64BitLibs = (new File(rootDir, isa)).exists();
9434            } else {
9435                has64BitLibs = false;
9436            }
9437            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9438                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9439                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9440                has32BitLibs = (new File(rootDir, isa)).exists();
9441            } else {
9442                has32BitLibs = false;
9443            }
9444        }
9445
9446        if (has64BitLibs && !has32BitLibs) {
9447            // The package has 64 bit libs, but not 32 bit libs. Its primary
9448            // ABI should be 64 bit. We can safely assume here that the bundled
9449            // native libraries correspond to the most preferred ABI in the list.
9450
9451            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9452            pkg.applicationInfo.secondaryCpuAbi = null;
9453        } else if (has32BitLibs && !has64BitLibs) {
9454            // The package has 32 bit libs but not 64 bit libs. Its primary
9455            // ABI should be 32 bit.
9456
9457            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9458            pkg.applicationInfo.secondaryCpuAbi = null;
9459        } else if (has32BitLibs && has64BitLibs) {
9460            // The application has both 64 and 32 bit bundled libraries. We check
9461            // here that the app declares multiArch support, and warn if it doesn't.
9462            //
9463            // We will be lenient here and record both ABIs. The primary will be the
9464            // ABI that's higher on the list, i.e, a device that's configured to prefer
9465            // 64 bit apps will see a 64 bit primary ABI,
9466
9467            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9468                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9469            }
9470
9471            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9472                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9473                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9474            } else {
9475                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9476                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9477            }
9478        } else {
9479            pkg.applicationInfo.primaryCpuAbi = null;
9480            pkg.applicationInfo.secondaryCpuAbi = null;
9481        }
9482    }
9483
9484    private void killApplication(String pkgName, int appId, String reason) {
9485        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9486    }
9487
9488    private void killApplication(String pkgName, int appId, int userId, String reason) {
9489        // Request the ActivityManager to kill the process(only for existing packages)
9490        // so that we do not end up in a confused state while the user is still using the older
9491        // version of the application while the new one gets installed.
9492        final long token = Binder.clearCallingIdentity();
9493        try {
9494            IActivityManager am = ActivityManagerNative.getDefault();
9495            if (am != null) {
9496                try {
9497                    am.killApplication(pkgName, appId, userId, reason);
9498                } catch (RemoteException e) {
9499                }
9500            }
9501        } finally {
9502            Binder.restoreCallingIdentity(token);
9503        }
9504    }
9505
9506    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9507        // Remove the parent package setting
9508        PackageSetting ps = (PackageSetting) pkg.mExtras;
9509        if (ps != null) {
9510            removePackageLI(ps, chatty);
9511        }
9512        // Remove the child package setting
9513        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9514        for (int i = 0; i < childCount; i++) {
9515            PackageParser.Package childPkg = pkg.childPackages.get(i);
9516            ps = (PackageSetting) childPkg.mExtras;
9517            if (ps != null) {
9518                removePackageLI(ps, chatty);
9519            }
9520        }
9521    }
9522
9523    void removePackageLI(PackageSetting ps, boolean chatty) {
9524        if (DEBUG_INSTALL) {
9525            if (chatty)
9526                Log.d(TAG, "Removing package " + ps.name);
9527        }
9528
9529        // writer
9530        synchronized (mPackages) {
9531            mPackages.remove(ps.name);
9532            final PackageParser.Package pkg = ps.pkg;
9533            if (pkg != null) {
9534                cleanPackageDataStructuresLILPw(pkg, chatty);
9535            }
9536        }
9537    }
9538
9539    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9540        if (DEBUG_INSTALL) {
9541            if (chatty)
9542                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9543        }
9544
9545        // writer
9546        synchronized (mPackages) {
9547            // Remove the parent package
9548            mPackages.remove(pkg.applicationInfo.packageName);
9549            cleanPackageDataStructuresLILPw(pkg, chatty);
9550
9551            // Remove the child packages
9552            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9553            for (int i = 0; i < childCount; i++) {
9554                PackageParser.Package childPkg = pkg.childPackages.get(i);
9555                mPackages.remove(childPkg.applicationInfo.packageName);
9556                cleanPackageDataStructuresLILPw(childPkg, chatty);
9557            }
9558        }
9559    }
9560
9561    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9562        int N = pkg.providers.size();
9563        StringBuilder r = null;
9564        int i;
9565        for (i=0; i<N; i++) {
9566            PackageParser.Provider p = pkg.providers.get(i);
9567            mProviders.removeProvider(p);
9568            if (p.info.authority == null) {
9569
9570                /* There was another ContentProvider with this authority when
9571                 * this app was installed so this authority is null,
9572                 * Ignore it as we don't have to unregister the provider.
9573                 */
9574                continue;
9575            }
9576            String names[] = p.info.authority.split(";");
9577            for (int j = 0; j < names.length; j++) {
9578                if (mProvidersByAuthority.get(names[j]) == p) {
9579                    mProvidersByAuthority.remove(names[j]);
9580                    if (DEBUG_REMOVE) {
9581                        if (chatty)
9582                            Log.d(TAG, "Unregistered content provider: " + names[j]
9583                                    + ", className = " + p.info.name + ", isSyncable = "
9584                                    + p.info.isSyncable);
9585                    }
9586                }
9587            }
9588            if (DEBUG_REMOVE && chatty) {
9589                if (r == null) {
9590                    r = new StringBuilder(256);
9591                } else {
9592                    r.append(' ');
9593                }
9594                r.append(p.info.name);
9595            }
9596        }
9597        if (r != null) {
9598            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9599        }
9600
9601        N = pkg.services.size();
9602        r = null;
9603        for (i=0; i<N; i++) {
9604            PackageParser.Service s = pkg.services.get(i);
9605            mServices.removeService(s);
9606            if (chatty) {
9607                if (r == null) {
9608                    r = new StringBuilder(256);
9609                } else {
9610                    r.append(' ');
9611                }
9612                r.append(s.info.name);
9613            }
9614        }
9615        if (r != null) {
9616            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9617        }
9618
9619        N = pkg.receivers.size();
9620        r = null;
9621        for (i=0; i<N; i++) {
9622            PackageParser.Activity a = pkg.receivers.get(i);
9623            mReceivers.removeActivity(a, "receiver");
9624            if (DEBUG_REMOVE && chatty) {
9625                if (r == null) {
9626                    r = new StringBuilder(256);
9627                } else {
9628                    r.append(' ');
9629                }
9630                r.append(a.info.name);
9631            }
9632        }
9633        if (r != null) {
9634            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9635        }
9636
9637        N = pkg.activities.size();
9638        r = null;
9639        for (i=0; i<N; i++) {
9640            PackageParser.Activity a = pkg.activities.get(i);
9641            mActivities.removeActivity(a, "activity");
9642            if (DEBUG_REMOVE && chatty) {
9643                if (r == null) {
9644                    r = new StringBuilder(256);
9645                } else {
9646                    r.append(' ');
9647                }
9648                r.append(a.info.name);
9649            }
9650        }
9651        if (r != null) {
9652            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9653        }
9654
9655        N = pkg.permissions.size();
9656        r = null;
9657        for (i=0; i<N; i++) {
9658            PackageParser.Permission p = pkg.permissions.get(i);
9659            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9660            if (bp == null) {
9661                bp = mSettings.mPermissionTrees.get(p.info.name);
9662            }
9663            if (bp != null && bp.perm == p) {
9664                bp.perm = null;
9665                if (DEBUG_REMOVE && chatty) {
9666                    if (r == null) {
9667                        r = new StringBuilder(256);
9668                    } else {
9669                        r.append(' ');
9670                    }
9671                    r.append(p.info.name);
9672                }
9673            }
9674            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9675                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9676                if (appOpPkgs != null) {
9677                    appOpPkgs.remove(pkg.packageName);
9678                }
9679            }
9680        }
9681        if (r != null) {
9682            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9683        }
9684
9685        N = pkg.requestedPermissions.size();
9686        r = null;
9687        for (i=0; i<N; i++) {
9688            String perm = pkg.requestedPermissions.get(i);
9689            BasePermission bp = mSettings.mPermissions.get(perm);
9690            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9691                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9692                if (appOpPkgs != null) {
9693                    appOpPkgs.remove(pkg.packageName);
9694                    if (appOpPkgs.isEmpty()) {
9695                        mAppOpPermissionPackages.remove(perm);
9696                    }
9697                }
9698            }
9699        }
9700        if (r != null) {
9701            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9702        }
9703
9704        N = pkg.instrumentation.size();
9705        r = null;
9706        for (i=0; i<N; i++) {
9707            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9708            mInstrumentation.remove(a.getComponentName());
9709            if (DEBUG_REMOVE && chatty) {
9710                if (r == null) {
9711                    r = new StringBuilder(256);
9712                } else {
9713                    r.append(' ');
9714                }
9715                r.append(a.info.name);
9716            }
9717        }
9718        if (r != null) {
9719            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9720        }
9721
9722        r = null;
9723        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9724            // Only system apps can hold shared libraries.
9725            if (pkg.libraryNames != null) {
9726                for (i=0; i<pkg.libraryNames.size(); i++) {
9727                    String name = pkg.libraryNames.get(i);
9728                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9729                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9730                        mSharedLibraries.remove(name);
9731                        if (DEBUG_REMOVE && chatty) {
9732                            if (r == null) {
9733                                r = new StringBuilder(256);
9734                            } else {
9735                                r.append(' ');
9736                            }
9737                            r.append(name);
9738                        }
9739                    }
9740                }
9741            }
9742        }
9743        if (r != null) {
9744            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9745        }
9746    }
9747
9748    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9749        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9750            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9751                return true;
9752            }
9753        }
9754        return false;
9755    }
9756
9757    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9758    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9759    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9760
9761    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9762        // Update the parent permissions
9763        updatePermissionsLPw(pkg.packageName, pkg, flags);
9764        // Update the child permissions
9765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9766        for (int i = 0; i < childCount; i++) {
9767            PackageParser.Package childPkg = pkg.childPackages.get(i);
9768            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9769        }
9770    }
9771
9772    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9773            int flags) {
9774        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9775        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9776    }
9777
9778    private void updatePermissionsLPw(String changingPkg,
9779            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9780        // Make sure there are no dangling permission trees.
9781        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9782        while (it.hasNext()) {
9783            final BasePermission bp = it.next();
9784            if (bp.packageSetting == null) {
9785                // We may not yet have parsed the package, so just see if
9786                // we still know about its settings.
9787                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9788            }
9789            if (bp.packageSetting == null) {
9790                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9791                        + " from package " + bp.sourcePackage);
9792                it.remove();
9793            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9794                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9795                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9796                            + " from package " + bp.sourcePackage);
9797                    flags |= UPDATE_PERMISSIONS_ALL;
9798                    it.remove();
9799                }
9800            }
9801        }
9802
9803        // Make sure all dynamic permissions have been assigned to a package,
9804        // and make sure there are no dangling permissions.
9805        it = mSettings.mPermissions.values().iterator();
9806        while (it.hasNext()) {
9807            final BasePermission bp = it.next();
9808            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9809                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9810                        + bp.name + " pkg=" + bp.sourcePackage
9811                        + " info=" + bp.pendingInfo);
9812                if (bp.packageSetting == null && bp.pendingInfo != null) {
9813                    final BasePermission tree = findPermissionTreeLP(bp.name);
9814                    if (tree != null && tree.perm != null) {
9815                        bp.packageSetting = tree.packageSetting;
9816                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9817                                new PermissionInfo(bp.pendingInfo));
9818                        bp.perm.info.packageName = tree.perm.info.packageName;
9819                        bp.perm.info.name = bp.name;
9820                        bp.uid = tree.uid;
9821                    }
9822                }
9823            }
9824            if (bp.packageSetting == null) {
9825                // We may not yet have parsed the package, so just see if
9826                // we still know about its settings.
9827                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9828            }
9829            if (bp.packageSetting == null) {
9830                Slog.w(TAG, "Removing dangling permission: " + bp.name
9831                        + " from package " + bp.sourcePackage);
9832                it.remove();
9833            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9834                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9835                    Slog.i(TAG, "Removing old permission: " + bp.name
9836                            + " from package " + bp.sourcePackage);
9837                    flags |= UPDATE_PERMISSIONS_ALL;
9838                    it.remove();
9839                }
9840            }
9841        }
9842
9843        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9844        // Now update the permissions for all packages, in particular
9845        // replace the granted permissions of the system packages.
9846        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9847            for (PackageParser.Package pkg : mPackages.values()) {
9848                if (pkg != pkgInfo) {
9849                    // Only replace for packages on requested volume
9850                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9851                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9852                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9853                    grantPermissionsLPw(pkg, replace, changingPkg);
9854                }
9855            }
9856        }
9857
9858        if (pkgInfo != null) {
9859            // Only replace for packages on requested volume
9860            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9861            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9862                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9863            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9864        }
9865        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9866    }
9867
9868    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9869            String packageOfInterest) {
9870        // IMPORTANT: There are two types of permissions: install and runtime.
9871        // Install time permissions are granted when the app is installed to
9872        // all device users and users added in the future. Runtime permissions
9873        // are granted at runtime explicitly to specific users. Normal and signature
9874        // protected permissions are install time permissions. Dangerous permissions
9875        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9876        // otherwise they are runtime permissions. This function does not manage
9877        // runtime permissions except for the case an app targeting Lollipop MR1
9878        // being upgraded to target a newer SDK, in which case dangerous permissions
9879        // are transformed from install time to runtime ones.
9880
9881        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9882        if (ps == null) {
9883            return;
9884        }
9885
9886        PermissionsState permissionsState = ps.getPermissionsState();
9887        PermissionsState origPermissions = permissionsState;
9888
9889        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9890
9891        boolean runtimePermissionsRevoked = false;
9892        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9893
9894        boolean changedInstallPermission = false;
9895
9896        if (replace) {
9897            ps.installPermissionsFixed = false;
9898            if (!ps.isSharedUser()) {
9899                origPermissions = new PermissionsState(permissionsState);
9900                permissionsState.reset();
9901            } else {
9902                // We need to know only about runtime permission changes since the
9903                // calling code always writes the install permissions state but
9904                // the runtime ones are written only if changed. The only cases of
9905                // changed runtime permissions here are promotion of an install to
9906                // runtime and revocation of a runtime from a shared user.
9907                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9908                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9909                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9910                    runtimePermissionsRevoked = true;
9911                }
9912            }
9913        }
9914
9915        permissionsState.setGlobalGids(mGlobalGids);
9916
9917        final int N = pkg.requestedPermissions.size();
9918        for (int i=0; i<N; i++) {
9919            final String name = pkg.requestedPermissions.get(i);
9920            final BasePermission bp = mSettings.mPermissions.get(name);
9921
9922            if (DEBUG_INSTALL) {
9923                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9924            }
9925
9926            if (bp == null || bp.packageSetting == null) {
9927                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9928                    Slog.w(TAG, "Unknown permission " + name
9929                            + " in package " + pkg.packageName);
9930                }
9931                continue;
9932            }
9933
9934            final String perm = bp.name;
9935            boolean allowedSig = false;
9936            int grant = GRANT_DENIED;
9937
9938            // Keep track of app op permissions.
9939            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9940                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9941                if (pkgs == null) {
9942                    pkgs = new ArraySet<>();
9943                    mAppOpPermissionPackages.put(bp.name, pkgs);
9944                }
9945                pkgs.add(pkg.packageName);
9946            }
9947
9948            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9949            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9950                    >= Build.VERSION_CODES.M;
9951            switch (level) {
9952                case PermissionInfo.PROTECTION_NORMAL: {
9953                    // For all apps normal permissions are install time ones.
9954                    grant = GRANT_INSTALL;
9955                } break;
9956
9957                case PermissionInfo.PROTECTION_DANGEROUS: {
9958                    // If a permission review is required for legacy apps we represent
9959                    // their permissions as always granted runtime ones since we need
9960                    // to keep the review required permission flag per user while an
9961                    // install permission's state is shared across all users.
9962                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
9963                        // For legacy apps dangerous permissions are install time ones.
9964                        grant = GRANT_INSTALL;
9965                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9966                        // For legacy apps that became modern, install becomes runtime.
9967                        grant = GRANT_UPGRADE;
9968                    } else if (mPromoteSystemApps
9969                            && isSystemApp(ps)
9970                            && mExistingSystemPackages.contains(ps.name)) {
9971                        // For legacy system apps, install becomes runtime.
9972                        // We cannot check hasInstallPermission() for system apps since those
9973                        // permissions were granted implicitly and not persisted pre-M.
9974                        grant = GRANT_UPGRADE;
9975                    } else {
9976                        // For modern apps keep runtime permissions unchanged.
9977                        grant = GRANT_RUNTIME;
9978                    }
9979                } break;
9980
9981                case PermissionInfo.PROTECTION_SIGNATURE: {
9982                    // For all apps signature permissions are install time ones.
9983                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9984                    if (allowedSig) {
9985                        grant = GRANT_INSTALL;
9986                    }
9987                } break;
9988            }
9989
9990            if (DEBUG_INSTALL) {
9991                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9992            }
9993
9994            if (grant != GRANT_DENIED) {
9995                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9996                    // If this is an existing, non-system package, then
9997                    // we can't add any new permissions to it.
9998                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9999                        // Except...  if this is a permission that was added
10000                        // to the platform (note: need to only do this when
10001                        // updating the platform).
10002                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10003                            grant = GRANT_DENIED;
10004                        }
10005                    }
10006                }
10007
10008                switch (grant) {
10009                    case GRANT_INSTALL: {
10010                        // Revoke this as runtime permission to handle the case of
10011                        // a runtime permission being downgraded to an install one.
10012                        // Also in permission review mode we keep dangerous permissions
10013                        // for legacy apps
10014                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10015                            if (origPermissions.getRuntimePermissionState(
10016                                    bp.name, userId) != null) {
10017                                // Revoke the runtime permission and clear the flags.
10018                                origPermissions.revokeRuntimePermission(bp, userId);
10019                                origPermissions.updatePermissionFlags(bp, userId,
10020                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10021                                // If we revoked a permission permission, we have to write.
10022                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10023                                        changedRuntimePermissionUserIds, userId);
10024                            }
10025                        }
10026                        // Grant an install permission.
10027                        if (permissionsState.grantInstallPermission(bp) !=
10028                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10029                            changedInstallPermission = true;
10030                        }
10031                    } break;
10032
10033                    case GRANT_RUNTIME: {
10034                        // Grant previously granted runtime permissions.
10035                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10036                            PermissionState permissionState = origPermissions
10037                                    .getRuntimePermissionState(bp.name, userId);
10038                            int flags = permissionState != null
10039                                    ? permissionState.getFlags() : 0;
10040                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10041                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10042                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10043                                    // If we cannot put the permission as it was, we have to write.
10044                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10045                                            changedRuntimePermissionUserIds, userId);
10046                                }
10047                                // If the app supports runtime permissions no need for a review.
10048                                if (mPermissionReviewRequired
10049                                        && appSupportsRuntimePermissions
10050                                        && (flags & PackageManager
10051                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10052                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10053                                    // Since we changed the flags, we have to write.
10054                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10055                                            changedRuntimePermissionUserIds, userId);
10056                                }
10057                            } else if (mPermissionReviewRequired
10058                                    && !appSupportsRuntimePermissions) {
10059                                // For legacy apps that need a permission review, every new
10060                                // runtime permission is granted but it is pending a review.
10061                                // We also need to review only platform defined runtime
10062                                // permissions as these are the only ones the platform knows
10063                                // how to disable the API to simulate revocation as legacy
10064                                // apps don't expect to run with revoked permissions.
10065                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10066                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10067                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10068                                        // We changed the flags, hence have to write.
10069                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10070                                                changedRuntimePermissionUserIds, userId);
10071                                    }
10072                                }
10073                                if (permissionsState.grantRuntimePermission(bp, userId)
10074                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10075                                    // We changed the permission, hence have to write.
10076                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10077                                            changedRuntimePermissionUserIds, userId);
10078                                }
10079                            }
10080                            // Propagate the permission flags.
10081                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10082                        }
10083                    } break;
10084
10085                    case GRANT_UPGRADE: {
10086                        // Grant runtime permissions for a previously held install permission.
10087                        PermissionState permissionState = origPermissions
10088                                .getInstallPermissionState(bp.name);
10089                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10090
10091                        if (origPermissions.revokeInstallPermission(bp)
10092                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10093                            // We will be transferring the permission flags, so clear them.
10094                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10095                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10096                            changedInstallPermission = true;
10097                        }
10098
10099                        // If the permission is not to be promoted to runtime we ignore it and
10100                        // also its other flags as they are not applicable to install permissions.
10101                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10102                            for (int userId : currentUserIds) {
10103                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10104                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10105                                    // Transfer the permission flags.
10106                                    permissionsState.updatePermissionFlags(bp, userId,
10107                                            flags, flags);
10108                                    // If we granted the permission, we have to write.
10109                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10110                                            changedRuntimePermissionUserIds, userId);
10111                                }
10112                            }
10113                        }
10114                    } break;
10115
10116                    default: {
10117                        if (packageOfInterest == null
10118                                || packageOfInterest.equals(pkg.packageName)) {
10119                            Slog.w(TAG, "Not granting permission " + perm
10120                                    + " to package " + pkg.packageName
10121                                    + " because it was previously installed without");
10122                        }
10123                    } break;
10124                }
10125            } else {
10126                if (permissionsState.revokeInstallPermission(bp) !=
10127                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10128                    // Also drop the permission flags.
10129                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10130                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10131                    changedInstallPermission = true;
10132                    Slog.i(TAG, "Un-granting permission " + perm
10133                            + " from package " + pkg.packageName
10134                            + " (protectionLevel=" + bp.protectionLevel
10135                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10136                            + ")");
10137                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10138                    // Don't print warning for app op permissions, since it is fine for them
10139                    // not to be granted, there is a UI for the user to decide.
10140                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10141                        Slog.w(TAG, "Not granting permission " + perm
10142                                + " to package " + pkg.packageName
10143                                + " (protectionLevel=" + bp.protectionLevel
10144                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10145                                + ")");
10146                    }
10147                }
10148            }
10149        }
10150
10151        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10152                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10153            // This is the first that we have heard about this package, so the
10154            // permissions we have now selected are fixed until explicitly
10155            // changed.
10156            ps.installPermissionsFixed = true;
10157        }
10158
10159        // Persist the runtime permissions state for users with changes. If permissions
10160        // were revoked because no app in the shared user declares them we have to
10161        // write synchronously to avoid losing runtime permissions state.
10162        for (int userId : changedRuntimePermissionUserIds) {
10163            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10164        }
10165    }
10166
10167    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10168        boolean allowed = false;
10169        final int NP = PackageParser.NEW_PERMISSIONS.length;
10170        for (int ip=0; ip<NP; ip++) {
10171            final PackageParser.NewPermissionInfo npi
10172                    = PackageParser.NEW_PERMISSIONS[ip];
10173            if (npi.name.equals(perm)
10174                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10175                allowed = true;
10176                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10177                        + pkg.packageName);
10178                break;
10179            }
10180        }
10181        return allowed;
10182    }
10183
10184    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10185            BasePermission bp, PermissionsState origPermissions) {
10186        boolean allowed;
10187        allowed = (compareSignatures(
10188                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10189                        == PackageManager.SIGNATURE_MATCH)
10190                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10191                        == PackageManager.SIGNATURE_MATCH);
10192        if (!allowed && (bp.protectionLevel
10193                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10194            if (isSystemApp(pkg)) {
10195                // For updated system applications, a system permission
10196                // is granted only if it had been defined by the original application.
10197                if (pkg.isUpdatedSystemApp()) {
10198                    final PackageSetting sysPs = mSettings
10199                            .getDisabledSystemPkgLPr(pkg.packageName);
10200                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10201                        // If the original was granted this permission, we take
10202                        // that grant decision as read and propagate it to the
10203                        // update.
10204                        if (sysPs.isPrivileged()) {
10205                            allowed = true;
10206                        }
10207                    } else {
10208                        // The system apk may have been updated with an older
10209                        // version of the one on the data partition, but which
10210                        // granted a new system permission that it didn't have
10211                        // before.  In this case we do want to allow the app to
10212                        // now get the new permission if the ancestral apk is
10213                        // privileged to get it.
10214                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10215                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10216                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10217                                    allowed = true;
10218                                    break;
10219                                }
10220                            }
10221                        }
10222                        // Also if a privileged parent package on the system image or any of
10223                        // its children requested a privileged permission, the updated child
10224                        // packages can also get the permission.
10225                        if (pkg.parentPackage != null) {
10226                            final PackageSetting disabledSysParentPs = mSettings
10227                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10228                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10229                                    && disabledSysParentPs.isPrivileged()) {
10230                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10231                                    allowed = true;
10232                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10233                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10234                                    for (int i = 0; i < count; i++) {
10235                                        PackageParser.Package disabledSysChildPkg =
10236                                                disabledSysParentPs.pkg.childPackages.get(i);
10237                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10238                                                perm)) {
10239                                            allowed = true;
10240                                            break;
10241                                        }
10242                                    }
10243                                }
10244                            }
10245                        }
10246                    }
10247                } else {
10248                    allowed = isPrivilegedApp(pkg);
10249                }
10250            }
10251        }
10252        if (!allowed) {
10253            if (!allowed && (bp.protectionLevel
10254                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10255                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10256                // If this was a previously normal/dangerous permission that got moved
10257                // to a system permission as part of the runtime permission redesign, then
10258                // we still want to blindly grant it to old apps.
10259                allowed = true;
10260            }
10261            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10262                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10263                // If this permission is to be granted to the system installer and
10264                // this app is an installer, then it gets the permission.
10265                allowed = true;
10266            }
10267            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10268                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10269                // If this permission is to be granted to the system verifier and
10270                // this app is a verifier, then it gets the permission.
10271                allowed = true;
10272            }
10273            if (!allowed && (bp.protectionLevel
10274                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10275                    && isSystemApp(pkg)) {
10276                // Any pre-installed system app is allowed to get this permission.
10277                allowed = true;
10278            }
10279            if (!allowed && (bp.protectionLevel
10280                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10281                // For development permissions, a development permission
10282                // is granted only if it was already granted.
10283                allowed = origPermissions.hasInstallPermission(perm);
10284            }
10285            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10286                    && pkg.packageName.equals(mSetupWizardPackage)) {
10287                // If this permission is to be granted to the system setup wizard and
10288                // this app is a setup wizard, then it gets the permission.
10289                allowed = true;
10290            }
10291        }
10292        return allowed;
10293    }
10294
10295    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10296        final int permCount = pkg.requestedPermissions.size();
10297        for (int j = 0; j < permCount; j++) {
10298            String requestedPermission = pkg.requestedPermissions.get(j);
10299            if (permission.equals(requestedPermission)) {
10300                return true;
10301            }
10302        }
10303        return false;
10304    }
10305
10306    final class ActivityIntentResolver
10307            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10308        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10309                boolean defaultOnly, int userId) {
10310            if (!sUserManager.exists(userId)) return null;
10311            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10312            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10313        }
10314
10315        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10316                int userId) {
10317            if (!sUserManager.exists(userId)) return null;
10318            mFlags = flags;
10319            return super.queryIntent(intent, resolvedType,
10320                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10321        }
10322
10323        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10324                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10325            if (!sUserManager.exists(userId)) return null;
10326            if (packageActivities == null) {
10327                return null;
10328            }
10329            mFlags = flags;
10330            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10331            final int N = packageActivities.size();
10332            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10333                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10334
10335            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10336            for (int i = 0; i < N; ++i) {
10337                intentFilters = packageActivities.get(i).intents;
10338                if (intentFilters != null && intentFilters.size() > 0) {
10339                    PackageParser.ActivityIntentInfo[] array =
10340                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10341                    intentFilters.toArray(array);
10342                    listCut.add(array);
10343                }
10344            }
10345            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10346        }
10347
10348        /**
10349         * Finds a privileged activity that matches the specified activity names.
10350         */
10351        private PackageParser.Activity findMatchingActivity(
10352                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10353            for (PackageParser.Activity sysActivity : activityList) {
10354                if (sysActivity.info.name.equals(activityInfo.name)) {
10355                    return sysActivity;
10356                }
10357                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10358                    return sysActivity;
10359                }
10360                if (sysActivity.info.targetActivity != null) {
10361                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10362                        return sysActivity;
10363                    }
10364                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10365                        return sysActivity;
10366                    }
10367                }
10368            }
10369            return null;
10370        }
10371
10372        public class IterGenerator<E> {
10373            public Iterator<E> generate(ActivityIntentInfo info) {
10374                return null;
10375            }
10376        }
10377
10378        public class ActionIterGenerator extends IterGenerator<String> {
10379            @Override
10380            public Iterator<String> generate(ActivityIntentInfo info) {
10381                return info.actionsIterator();
10382            }
10383        }
10384
10385        public class CategoriesIterGenerator extends IterGenerator<String> {
10386            @Override
10387            public Iterator<String> generate(ActivityIntentInfo info) {
10388                return info.categoriesIterator();
10389            }
10390        }
10391
10392        public class SchemesIterGenerator extends IterGenerator<String> {
10393            @Override
10394            public Iterator<String> generate(ActivityIntentInfo info) {
10395                return info.schemesIterator();
10396            }
10397        }
10398
10399        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10400            @Override
10401            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10402                return info.authoritiesIterator();
10403            }
10404        }
10405
10406        /**
10407         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10408         * MODIFIED. Do not pass in a list that should not be changed.
10409         */
10410        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10411                IterGenerator<T> generator, Iterator<T> searchIterator) {
10412            // loop through the set of actions; every one must be found in the intent filter
10413            while (searchIterator.hasNext()) {
10414                // we must have at least one filter in the list to consider a match
10415                if (intentList.size() == 0) {
10416                    break;
10417                }
10418
10419                final T searchAction = searchIterator.next();
10420
10421                // loop through the set of intent filters
10422                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10423                while (intentIter.hasNext()) {
10424                    final ActivityIntentInfo intentInfo = intentIter.next();
10425                    boolean selectionFound = false;
10426
10427                    // loop through the intent filter's selection criteria; at least one
10428                    // of them must match the searched criteria
10429                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10430                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10431                        final T intentSelection = intentSelectionIter.next();
10432                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10433                            selectionFound = true;
10434                            break;
10435                        }
10436                    }
10437
10438                    // the selection criteria wasn't found in this filter's set; this filter
10439                    // is not a potential match
10440                    if (!selectionFound) {
10441                        intentIter.remove();
10442                    }
10443                }
10444            }
10445        }
10446
10447        private boolean isProtectedAction(ActivityIntentInfo filter) {
10448            final Iterator<String> actionsIter = filter.actionsIterator();
10449            while (actionsIter != null && actionsIter.hasNext()) {
10450                final String filterAction = actionsIter.next();
10451                if (PROTECTED_ACTIONS.contains(filterAction)) {
10452                    return true;
10453                }
10454            }
10455            return false;
10456        }
10457
10458        /**
10459         * Adjusts the priority of the given intent filter according to policy.
10460         * <p>
10461         * <ul>
10462         * <li>The priority for non privileged applications is capped to '0'</li>
10463         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10464         * <li>The priority for unbundled updates to privileged applications is capped to the
10465         *      priority defined on the system partition</li>
10466         * </ul>
10467         * <p>
10468         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10469         * allowed to obtain any priority on any action.
10470         */
10471        private void adjustPriority(
10472                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10473            // nothing to do; priority is fine as-is
10474            if (intent.getPriority() <= 0) {
10475                return;
10476            }
10477
10478            final ActivityInfo activityInfo = intent.activity.info;
10479            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10480
10481            final boolean privilegedApp =
10482                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10483            if (!privilegedApp) {
10484                // non-privileged applications can never define a priority >0
10485                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10486                        + " package: " + applicationInfo.packageName
10487                        + " activity: " + intent.activity.className
10488                        + " origPrio: " + intent.getPriority());
10489                intent.setPriority(0);
10490                return;
10491            }
10492
10493            if (systemActivities == null) {
10494                // the system package is not disabled; we're parsing the system partition
10495                if (isProtectedAction(intent)) {
10496                    if (mDeferProtectedFilters) {
10497                        // We can't deal with these just yet. No component should ever obtain a
10498                        // >0 priority for a protected actions, with ONE exception -- the setup
10499                        // wizard. The setup wizard, however, cannot be known until we're able to
10500                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10501                        // until all intent filters have been processed. Chicken, meet egg.
10502                        // Let the filter temporarily have a high priority and rectify the
10503                        // priorities after all system packages have been scanned.
10504                        mProtectedFilters.add(intent);
10505                        if (DEBUG_FILTERS) {
10506                            Slog.i(TAG, "Protected action; save for later;"
10507                                    + " package: " + applicationInfo.packageName
10508                                    + " activity: " + intent.activity.className
10509                                    + " origPrio: " + intent.getPriority());
10510                        }
10511                        return;
10512                    } else {
10513                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10514                            Slog.i(TAG, "No setup wizard;"
10515                                + " All protected intents capped to priority 0");
10516                        }
10517                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10518                            if (DEBUG_FILTERS) {
10519                                Slog.i(TAG, "Found setup wizard;"
10520                                    + " allow priority " + intent.getPriority() + ";"
10521                                    + " package: " + intent.activity.info.packageName
10522                                    + " activity: " + intent.activity.className
10523                                    + " priority: " + intent.getPriority());
10524                            }
10525                            // setup wizard gets whatever it wants
10526                            return;
10527                        }
10528                        Slog.w(TAG, "Protected action; cap priority to 0;"
10529                                + " package: " + intent.activity.info.packageName
10530                                + " activity: " + intent.activity.className
10531                                + " origPrio: " + intent.getPriority());
10532                        intent.setPriority(0);
10533                        return;
10534                    }
10535                }
10536                // privileged apps on the system image get whatever priority they request
10537                return;
10538            }
10539
10540            // privileged app unbundled update ... try to find the same activity
10541            final PackageParser.Activity foundActivity =
10542                    findMatchingActivity(systemActivities, activityInfo);
10543            if (foundActivity == null) {
10544                // this is a new activity; it cannot obtain >0 priority
10545                if (DEBUG_FILTERS) {
10546                    Slog.i(TAG, "New activity; cap priority to 0;"
10547                            + " package: " + applicationInfo.packageName
10548                            + " activity: " + intent.activity.className
10549                            + " origPrio: " + intent.getPriority());
10550                }
10551                intent.setPriority(0);
10552                return;
10553            }
10554
10555            // found activity, now check for filter equivalence
10556
10557            // a shallow copy is enough; we modify the list, not its contents
10558            final List<ActivityIntentInfo> intentListCopy =
10559                    new ArrayList<>(foundActivity.intents);
10560            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10561
10562            // find matching action subsets
10563            final Iterator<String> actionsIterator = intent.actionsIterator();
10564            if (actionsIterator != null) {
10565                getIntentListSubset(
10566                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10567                if (intentListCopy.size() == 0) {
10568                    // no more intents to match; we're not equivalent
10569                    if (DEBUG_FILTERS) {
10570                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10571                                + " package: " + applicationInfo.packageName
10572                                + " activity: " + intent.activity.className
10573                                + " origPrio: " + intent.getPriority());
10574                    }
10575                    intent.setPriority(0);
10576                    return;
10577                }
10578            }
10579
10580            // find matching category subsets
10581            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10582            if (categoriesIterator != null) {
10583                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10584                        categoriesIterator);
10585                if (intentListCopy.size() == 0) {
10586                    // no more intents to match; we're not equivalent
10587                    if (DEBUG_FILTERS) {
10588                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10589                                + " package: " + applicationInfo.packageName
10590                                + " activity: " + intent.activity.className
10591                                + " origPrio: " + intent.getPriority());
10592                    }
10593                    intent.setPriority(0);
10594                    return;
10595                }
10596            }
10597
10598            // find matching schemes subsets
10599            final Iterator<String> schemesIterator = intent.schemesIterator();
10600            if (schemesIterator != null) {
10601                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10602                        schemesIterator);
10603                if (intentListCopy.size() == 0) {
10604                    // no more intents to match; we're not equivalent
10605                    if (DEBUG_FILTERS) {
10606                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10607                                + " package: " + applicationInfo.packageName
10608                                + " activity: " + intent.activity.className
10609                                + " origPrio: " + intent.getPriority());
10610                    }
10611                    intent.setPriority(0);
10612                    return;
10613                }
10614            }
10615
10616            // find matching authorities subsets
10617            final Iterator<IntentFilter.AuthorityEntry>
10618                    authoritiesIterator = intent.authoritiesIterator();
10619            if (authoritiesIterator != null) {
10620                getIntentListSubset(intentListCopy,
10621                        new AuthoritiesIterGenerator(),
10622                        authoritiesIterator);
10623                if (intentListCopy.size() == 0) {
10624                    // no more intents to match; we're not equivalent
10625                    if (DEBUG_FILTERS) {
10626                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10627                                + " package: " + applicationInfo.packageName
10628                                + " activity: " + intent.activity.className
10629                                + " origPrio: " + intent.getPriority());
10630                    }
10631                    intent.setPriority(0);
10632                    return;
10633                }
10634            }
10635
10636            // we found matching filter(s); app gets the max priority of all intents
10637            int cappedPriority = 0;
10638            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10639                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10640            }
10641            if (intent.getPriority() > cappedPriority) {
10642                if (DEBUG_FILTERS) {
10643                    Slog.i(TAG, "Found matching filter(s);"
10644                            + " cap priority to " + cappedPriority + ";"
10645                            + " package: " + applicationInfo.packageName
10646                            + " activity: " + intent.activity.className
10647                            + " origPrio: " + intent.getPriority());
10648                }
10649                intent.setPriority(cappedPriority);
10650                return;
10651            }
10652            // all this for nothing; the requested priority was <= what was on the system
10653        }
10654
10655        public final void addActivity(PackageParser.Activity a, String type) {
10656            mActivities.put(a.getComponentName(), a);
10657            if (DEBUG_SHOW_INFO)
10658                Log.v(
10659                TAG, "  " + type + " " +
10660                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10661            if (DEBUG_SHOW_INFO)
10662                Log.v(TAG, "    Class=" + a.info.name);
10663            final int NI = a.intents.size();
10664            for (int j=0; j<NI; j++) {
10665                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10666                if ("activity".equals(type)) {
10667                    final PackageSetting ps =
10668                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10669                    final List<PackageParser.Activity> systemActivities =
10670                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10671                    adjustPriority(systemActivities, intent);
10672                }
10673                if (DEBUG_SHOW_INFO) {
10674                    Log.v(TAG, "    IntentFilter:");
10675                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10676                }
10677                if (!intent.debugCheck()) {
10678                    Log.w(TAG, "==> For Activity " + a.info.name);
10679                }
10680                addFilter(intent);
10681            }
10682        }
10683
10684        public final void removeActivity(PackageParser.Activity a, String type) {
10685            mActivities.remove(a.getComponentName());
10686            if (DEBUG_SHOW_INFO) {
10687                Log.v(TAG, "  " + type + " "
10688                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10689                                : a.info.name) + ":");
10690                Log.v(TAG, "    Class=" + a.info.name);
10691            }
10692            final int NI = a.intents.size();
10693            for (int j=0; j<NI; j++) {
10694                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10695                if (DEBUG_SHOW_INFO) {
10696                    Log.v(TAG, "    IntentFilter:");
10697                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10698                }
10699                removeFilter(intent);
10700            }
10701        }
10702
10703        @Override
10704        protected boolean allowFilterResult(
10705                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10706            ActivityInfo filterAi = filter.activity.info;
10707            for (int i=dest.size()-1; i>=0; i--) {
10708                ActivityInfo destAi = dest.get(i).activityInfo;
10709                if (destAi.name == filterAi.name
10710                        && destAi.packageName == filterAi.packageName) {
10711                    return false;
10712                }
10713            }
10714            return true;
10715        }
10716
10717        @Override
10718        protected ActivityIntentInfo[] newArray(int size) {
10719            return new ActivityIntentInfo[size];
10720        }
10721
10722        @Override
10723        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10724            if (!sUserManager.exists(userId)) return true;
10725            PackageParser.Package p = filter.activity.owner;
10726            if (p != null) {
10727                PackageSetting ps = (PackageSetting)p.mExtras;
10728                if (ps != null) {
10729                    // System apps are never considered stopped for purposes of
10730                    // filtering, because there may be no way for the user to
10731                    // actually re-launch them.
10732                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10733                            && ps.getStopped(userId);
10734                }
10735            }
10736            return false;
10737        }
10738
10739        @Override
10740        protected boolean isPackageForFilter(String packageName,
10741                PackageParser.ActivityIntentInfo info) {
10742            return packageName.equals(info.activity.owner.packageName);
10743        }
10744
10745        @Override
10746        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10747                int match, int userId) {
10748            if (!sUserManager.exists(userId)) return null;
10749            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10750                return null;
10751            }
10752            final PackageParser.Activity activity = info.activity;
10753            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10754            if (ps == null) {
10755                return null;
10756            }
10757            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10758                    ps.readUserState(userId), userId);
10759            if (ai == null) {
10760                return null;
10761            }
10762            final ResolveInfo res = new ResolveInfo();
10763            res.activityInfo = ai;
10764            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10765                res.filter = info;
10766            }
10767            if (info != null) {
10768                res.handleAllWebDataURI = info.handleAllWebDataURI();
10769            }
10770            res.priority = info.getPriority();
10771            res.preferredOrder = activity.owner.mPreferredOrder;
10772            //System.out.println("Result: " + res.activityInfo.className +
10773            //                   " = " + res.priority);
10774            res.match = match;
10775            res.isDefault = info.hasDefault;
10776            res.labelRes = info.labelRes;
10777            res.nonLocalizedLabel = info.nonLocalizedLabel;
10778            if (userNeedsBadging(userId)) {
10779                res.noResourceId = true;
10780            } else {
10781                res.icon = info.icon;
10782            }
10783            res.iconResourceId = info.icon;
10784            res.system = res.activityInfo.applicationInfo.isSystemApp();
10785            return res;
10786        }
10787
10788        @Override
10789        protected void sortResults(List<ResolveInfo> results) {
10790            Collections.sort(results, mResolvePrioritySorter);
10791        }
10792
10793        @Override
10794        protected void dumpFilter(PrintWriter out, String prefix,
10795                PackageParser.ActivityIntentInfo filter) {
10796            out.print(prefix); out.print(
10797                    Integer.toHexString(System.identityHashCode(filter.activity)));
10798                    out.print(' ');
10799                    filter.activity.printComponentShortName(out);
10800                    out.print(" filter ");
10801                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10802        }
10803
10804        @Override
10805        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10806            return filter.activity;
10807        }
10808
10809        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10810            PackageParser.Activity activity = (PackageParser.Activity)label;
10811            out.print(prefix); out.print(
10812                    Integer.toHexString(System.identityHashCode(activity)));
10813                    out.print(' ');
10814                    activity.printComponentShortName(out);
10815            if (count > 1) {
10816                out.print(" ("); out.print(count); out.print(" filters)");
10817            }
10818            out.println();
10819        }
10820
10821        // Keys are String (activity class name), values are Activity.
10822        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10823                = new ArrayMap<ComponentName, PackageParser.Activity>();
10824        private int mFlags;
10825    }
10826
10827    private final class ServiceIntentResolver
10828            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10829        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10830                boolean defaultOnly, int userId) {
10831            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10832            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10833        }
10834
10835        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10836                int userId) {
10837            if (!sUserManager.exists(userId)) return null;
10838            mFlags = flags;
10839            return super.queryIntent(intent, resolvedType,
10840                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10841        }
10842
10843        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10844                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10845            if (!sUserManager.exists(userId)) return null;
10846            if (packageServices == null) {
10847                return null;
10848            }
10849            mFlags = flags;
10850            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10851            final int N = packageServices.size();
10852            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10853                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10854
10855            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10856            for (int i = 0; i < N; ++i) {
10857                intentFilters = packageServices.get(i).intents;
10858                if (intentFilters != null && intentFilters.size() > 0) {
10859                    PackageParser.ServiceIntentInfo[] array =
10860                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10861                    intentFilters.toArray(array);
10862                    listCut.add(array);
10863                }
10864            }
10865            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10866        }
10867
10868        public final void addService(PackageParser.Service s) {
10869            mServices.put(s.getComponentName(), s);
10870            if (DEBUG_SHOW_INFO) {
10871                Log.v(TAG, "  "
10872                        + (s.info.nonLocalizedLabel != null
10873                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10874                Log.v(TAG, "    Class=" + s.info.name);
10875            }
10876            final int NI = s.intents.size();
10877            int j;
10878            for (j=0; j<NI; j++) {
10879                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10880                if (DEBUG_SHOW_INFO) {
10881                    Log.v(TAG, "    IntentFilter:");
10882                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10883                }
10884                if (!intent.debugCheck()) {
10885                    Log.w(TAG, "==> For Service " + s.info.name);
10886                }
10887                addFilter(intent);
10888            }
10889        }
10890
10891        public final void removeService(PackageParser.Service s) {
10892            mServices.remove(s.getComponentName());
10893            if (DEBUG_SHOW_INFO) {
10894                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10895                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10896                Log.v(TAG, "    Class=" + s.info.name);
10897            }
10898            final int NI = s.intents.size();
10899            int j;
10900            for (j=0; j<NI; j++) {
10901                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10902                if (DEBUG_SHOW_INFO) {
10903                    Log.v(TAG, "    IntentFilter:");
10904                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10905                }
10906                removeFilter(intent);
10907            }
10908        }
10909
10910        @Override
10911        protected boolean allowFilterResult(
10912                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10913            ServiceInfo filterSi = filter.service.info;
10914            for (int i=dest.size()-1; i>=0; i--) {
10915                ServiceInfo destAi = dest.get(i).serviceInfo;
10916                if (destAi.name == filterSi.name
10917                        && destAi.packageName == filterSi.packageName) {
10918                    return false;
10919                }
10920            }
10921            return true;
10922        }
10923
10924        @Override
10925        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10926            return new PackageParser.ServiceIntentInfo[size];
10927        }
10928
10929        @Override
10930        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10931            if (!sUserManager.exists(userId)) return true;
10932            PackageParser.Package p = filter.service.owner;
10933            if (p != null) {
10934                PackageSetting ps = (PackageSetting)p.mExtras;
10935                if (ps != null) {
10936                    // System apps are never considered stopped for purposes of
10937                    // filtering, because there may be no way for the user to
10938                    // actually re-launch them.
10939                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10940                            && ps.getStopped(userId);
10941                }
10942            }
10943            return false;
10944        }
10945
10946        @Override
10947        protected boolean isPackageForFilter(String packageName,
10948                PackageParser.ServiceIntentInfo info) {
10949            return packageName.equals(info.service.owner.packageName);
10950        }
10951
10952        @Override
10953        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10954                int match, int userId) {
10955            if (!sUserManager.exists(userId)) return null;
10956            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10957            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10958                return null;
10959            }
10960            final PackageParser.Service service = info.service;
10961            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10962            if (ps == null) {
10963                return null;
10964            }
10965            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10966                    ps.readUserState(userId), userId);
10967            if (si == null) {
10968                return null;
10969            }
10970            final ResolveInfo res = new ResolveInfo();
10971            res.serviceInfo = si;
10972            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10973                res.filter = filter;
10974            }
10975            res.priority = info.getPriority();
10976            res.preferredOrder = service.owner.mPreferredOrder;
10977            res.match = match;
10978            res.isDefault = info.hasDefault;
10979            res.labelRes = info.labelRes;
10980            res.nonLocalizedLabel = info.nonLocalizedLabel;
10981            res.icon = info.icon;
10982            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10983            return res;
10984        }
10985
10986        @Override
10987        protected void sortResults(List<ResolveInfo> results) {
10988            Collections.sort(results, mResolvePrioritySorter);
10989        }
10990
10991        @Override
10992        protected void dumpFilter(PrintWriter out, String prefix,
10993                PackageParser.ServiceIntentInfo filter) {
10994            out.print(prefix); out.print(
10995                    Integer.toHexString(System.identityHashCode(filter.service)));
10996                    out.print(' ');
10997                    filter.service.printComponentShortName(out);
10998                    out.print(" filter ");
10999                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11000        }
11001
11002        @Override
11003        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11004            return filter.service;
11005        }
11006
11007        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11008            PackageParser.Service service = (PackageParser.Service)label;
11009            out.print(prefix); out.print(
11010                    Integer.toHexString(System.identityHashCode(service)));
11011                    out.print(' ');
11012                    service.printComponentShortName(out);
11013            if (count > 1) {
11014                out.print(" ("); out.print(count); out.print(" filters)");
11015            }
11016            out.println();
11017        }
11018
11019//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11020//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11021//            final List<ResolveInfo> retList = Lists.newArrayList();
11022//            while (i.hasNext()) {
11023//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11024//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11025//                    retList.add(resolveInfo);
11026//                }
11027//            }
11028//            return retList;
11029//        }
11030
11031        // Keys are String (activity class name), values are Activity.
11032        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11033                = new ArrayMap<ComponentName, PackageParser.Service>();
11034        private int mFlags;
11035    };
11036
11037    private final class ProviderIntentResolver
11038            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11039        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11040                boolean defaultOnly, int userId) {
11041            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11042            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11043        }
11044
11045        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11046                int userId) {
11047            if (!sUserManager.exists(userId))
11048                return null;
11049            mFlags = flags;
11050            return super.queryIntent(intent, resolvedType,
11051                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11052        }
11053
11054        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11055                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11056            if (!sUserManager.exists(userId))
11057                return null;
11058            if (packageProviders == null) {
11059                return null;
11060            }
11061            mFlags = flags;
11062            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11063            final int N = packageProviders.size();
11064            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11065                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11066
11067            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11068            for (int i = 0; i < N; ++i) {
11069                intentFilters = packageProviders.get(i).intents;
11070                if (intentFilters != null && intentFilters.size() > 0) {
11071                    PackageParser.ProviderIntentInfo[] array =
11072                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11073                    intentFilters.toArray(array);
11074                    listCut.add(array);
11075                }
11076            }
11077            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11078        }
11079
11080        public final void addProvider(PackageParser.Provider p) {
11081            if (mProviders.containsKey(p.getComponentName())) {
11082                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11083                return;
11084            }
11085
11086            mProviders.put(p.getComponentName(), p);
11087            if (DEBUG_SHOW_INFO) {
11088                Log.v(TAG, "  "
11089                        + (p.info.nonLocalizedLabel != null
11090                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11091                Log.v(TAG, "    Class=" + p.info.name);
11092            }
11093            final int NI = p.intents.size();
11094            int j;
11095            for (j = 0; j < NI; j++) {
11096                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11097                if (DEBUG_SHOW_INFO) {
11098                    Log.v(TAG, "    IntentFilter:");
11099                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11100                }
11101                if (!intent.debugCheck()) {
11102                    Log.w(TAG, "==> For Provider " + p.info.name);
11103                }
11104                addFilter(intent);
11105            }
11106        }
11107
11108        public final void removeProvider(PackageParser.Provider p) {
11109            mProviders.remove(p.getComponentName());
11110            if (DEBUG_SHOW_INFO) {
11111                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11112                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11113                Log.v(TAG, "    Class=" + p.info.name);
11114            }
11115            final int NI = p.intents.size();
11116            int j;
11117            for (j = 0; j < NI; j++) {
11118                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11119                if (DEBUG_SHOW_INFO) {
11120                    Log.v(TAG, "    IntentFilter:");
11121                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11122                }
11123                removeFilter(intent);
11124            }
11125        }
11126
11127        @Override
11128        protected boolean allowFilterResult(
11129                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11130            ProviderInfo filterPi = filter.provider.info;
11131            for (int i = dest.size() - 1; i >= 0; i--) {
11132                ProviderInfo destPi = dest.get(i).providerInfo;
11133                if (destPi.name == filterPi.name
11134                        && destPi.packageName == filterPi.packageName) {
11135                    return false;
11136                }
11137            }
11138            return true;
11139        }
11140
11141        @Override
11142        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11143            return new PackageParser.ProviderIntentInfo[size];
11144        }
11145
11146        @Override
11147        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11148            if (!sUserManager.exists(userId))
11149                return true;
11150            PackageParser.Package p = filter.provider.owner;
11151            if (p != null) {
11152                PackageSetting ps = (PackageSetting) p.mExtras;
11153                if (ps != null) {
11154                    // System apps are never considered stopped for purposes of
11155                    // filtering, because there may be no way for the user to
11156                    // actually re-launch them.
11157                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11158                            && ps.getStopped(userId);
11159                }
11160            }
11161            return false;
11162        }
11163
11164        @Override
11165        protected boolean isPackageForFilter(String packageName,
11166                PackageParser.ProviderIntentInfo info) {
11167            return packageName.equals(info.provider.owner.packageName);
11168        }
11169
11170        @Override
11171        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11172                int match, int userId) {
11173            if (!sUserManager.exists(userId))
11174                return null;
11175            final PackageParser.ProviderIntentInfo info = filter;
11176            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11177                return null;
11178            }
11179            final PackageParser.Provider provider = info.provider;
11180            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11181            if (ps == null) {
11182                return null;
11183            }
11184            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11185                    ps.readUserState(userId), userId);
11186            if (pi == null) {
11187                return null;
11188            }
11189            final ResolveInfo res = new ResolveInfo();
11190            res.providerInfo = pi;
11191            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11192                res.filter = filter;
11193            }
11194            res.priority = info.getPriority();
11195            res.preferredOrder = provider.owner.mPreferredOrder;
11196            res.match = match;
11197            res.isDefault = info.hasDefault;
11198            res.labelRes = info.labelRes;
11199            res.nonLocalizedLabel = info.nonLocalizedLabel;
11200            res.icon = info.icon;
11201            res.system = res.providerInfo.applicationInfo.isSystemApp();
11202            return res;
11203        }
11204
11205        @Override
11206        protected void sortResults(List<ResolveInfo> results) {
11207            Collections.sort(results, mResolvePrioritySorter);
11208        }
11209
11210        @Override
11211        protected void dumpFilter(PrintWriter out, String prefix,
11212                PackageParser.ProviderIntentInfo filter) {
11213            out.print(prefix);
11214            out.print(
11215                    Integer.toHexString(System.identityHashCode(filter.provider)));
11216            out.print(' ');
11217            filter.provider.printComponentShortName(out);
11218            out.print(" filter ");
11219            out.println(Integer.toHexString(System.identityHashCode(filter)));
11220        }
11221
11222        @Override
11223        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11224            return filter.provider;
11225        }
11226
11227        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11228            PackageParser.Provider provider = (PackageParser.Provider)label;
11229            out.print(prefix); out.print(
11230                    Integer.toHexString(System.identityHashCode(provider)));
11231                    out.print(' ');
11232                    provider.printComponentShortName(out);
11233            if (count > 1) {
11234                out.print(" ("); out.print(count); out.print(" filters)");
11235            }
11236            out.println();
11237        }
11238
11239        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11240                = new ArrayMap<ComponentName, PackageParser.Provider>();
11241        private int mFlags;
11242    }
11243
11244    private static final class EphemeralIntentResolver
11245            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11246        @Override
11247        protected EphemeralResolveIntentInfo[] newArray(int size) {
11248            return new EphemeralResolveIntentInfo[size];
11249        }
11250
11251        @Override
11252        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11253            return true;
11254        }
11255
11256        @Override
11257        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11258                int userId) {
11259            if (!sUserManager.exists(userId)) {
11260                return null;
11261            }
11262            return info.getEphemeralResolveInfo();
11263        }
11264    }
11265
11266    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11267            new Comparator<ResolveInfo>() {
11268        public int compare(ResolveInfo r1, ResolveInfo r2) {
11269            int v1 = r1.priority;
11270            int v2 = r2.priority;
11271            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11272            if (v1 != v2) {
11273                return (v1 > v2) ? -1 : 1;
11274            }
11275            v1 = r1.preferredOrder;
11276            v2 = r2.preferredOrder;
11277            if (v1 != v2) {
11278                return (v1 > v2) ? -1 : 1;
11279            }
11280            if (r1.isDefault != r2.isDefault) {
11281                return r1.isDefault ? -1 : 1;
11282            }
11283            v1 = r1.match;
11284            v2 = r2.match;
11285            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11286            if (v1 != v2) {
11287                return (v1 > v2) ? -1 : 1;
11288            }
11289            if (r1.system != r2.system) {
11290                return r1.system ? -1 : 1;
11291            }
11292            if (r1.activityInfo != null) {
11293                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11294            }
11295            if (r1.serviceInfo != null) {
11296                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11297            }
11298            if (r1.providerInfo != null) {
11299                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11300            }
11301            return 0;
11302        }
11303    };
11304
11305    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11306            new Comparator<ProviderInfo>() {
11307        public int compare(ProviderInfo p1, ProviderInfo p2) {
11308            final int v1 = p1.initOrder;
11309            final int v2 = p2.initOrder;
11310            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11311        }
11312    };
11313
11314    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11315            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11316            final int[] userIds) {
11317        mHandler.post(new Runnable() {
11318            @Override
11319            public void run() {
11320                try {
11321                    final IActivityManager am = ActivityManagerNative.getDefault();
11322                    if (am == null) return;
11323                    final int[] resolvedUserIds;
11324                    if (userIds == null) {
11325                        resolvedUserIds = am.getRunningUserIds();
11326                    } else {
11327                        resolvedUserIds = userIds;
11328                    }
11329                    for (int id : resolvedUserIds) {
11330                        final Intent intent = new Intent(action,
11331                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11332                        if (extras != null) {
11333                            intent.putExtras(extras);
11334                        }
11335                        if (targetPkg != null) {
11336                            intent.setPackage(targetPkg);
11337                        }
11338                        // Modify the UID when posting to other users
11339                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11340                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11341                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11342                            intent.putExtra(Intent.EXTRA_UID, uid);
11343                        }
11344                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11345                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11346                        if (DEBUG_BROADCASTS) {
11347                            RuntimeException here = new RuntimeException("here");
11348                            here.fillInStackTrace();
11349                            Slog.d(TAG, "Sending to user " + id + ": "
11350                                    + intent.toShortString(false, true, false, false)
11351                                    + " " + intent.getExtras(), here);
11352                        }
11353                        am.broadcastIntent(null, intent, null, finishedReceiver,
11354                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11355                                null, finishedReceiver != null, false, id);
11356                    }
11357                } catch (RemoteException ex) {
11358                }
11359            }
11360        });
11361    }
11362
11363    /**
11364     * Check if the external storage media is available. This is true if there
11365     * is a mounted external storage medium or if the external storage is
11366     * emulated.
11367     */
11368    private boolean isExternalMediaAvailable() {
11369        return mMediaMounted || Environment.isExternalStorageEmulated();
11370    }
11371
11372    @Override
11373    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11374        // writer
11375        synchronized (mPackages) {
11376            if (!isExternalMediaAvailable()) {
11377                // If the external storage is no longer mounted at this point,
11378                // the caller may not have been able to delete all of this
11379                // packages files and can not delete any more.  Bail.
11380                return null;
11381            }
11382            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11383            if (lastPackage != null) {
11384                pkgs.remove(lastPackage);
11385            }
11386            if (pkgs.size() > 0) {
11387                return pkgs.get(0);
11388            }
11389        }
11390        return null;
11391    }
11392
11393    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11394        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11395                userId, andCode ? 1 : 0, packageName);
11396        if (mSystemReady) {
11397            msg.sendToTarget();
11398        } else {
11399            if (mPostSystemReadyMessages == null) {
11400                mPostSystemReadyMessages = new ArrayList<>();
11401            }
11402            mPostSystemReadyMessages.add(msg);
11403        }
11404    }
11405
11406    void startCleaningPackages() {
11407        // reader
11408        if (!isExternalMediaAvailable()) {
11409            return;
11410        }
11411        synchronized (mPackages) {
11412            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11413                return;
11414            }
11415        }
11416        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11417        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11418        IActivityManager am = ActivityManagerNative.getDefault();
11419        if (am != null) {
11420            try {
11421                am.startService(null, intent, null, mContext.getOpPackageName(),
11422                        UserHandle.USER_SYSTEM);
11423            } catch (RemoteException e) {
11424            }
11425        }
11426    }
11427
11428    @Override
11429    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11430            int installFlags, String installerPackageName, int userId) {
11431        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11432
11433        final int callingUid = Binder.getCallingUid();
11434        enforceCrossUserPermission(callingUid, userId,
11435                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11436
11437        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11438            try {
11439                if (observer != null) {
11440                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11441                }
11442            } catch (RemoteException re) {
11443            }
11444            return;
11445        }
11446
11447        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11448            installFlags |= PackageManager.INSTALL_FROM_ADB;
11449
11450        } else {
11451            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11452            // about installerPackageName.
11453
11454            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11455            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11456        }
11457
11458        UserHandle user;
11459        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11460            user = UserHandle.ALL;
11461        } else {
11462            user = new UserHandle(userId);
11463        }
11464
11465        // Only system components can circumvent runtime permissions when installing.
11466        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11467                && mContext.checkCallingOrSelfPermission(Manifest.permission
11468                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11469            throw new SecurityException("You need the "
11470                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11471                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11472        }
11473
11474        final File originFile = new File(originPath);
11475        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11476
11477        final Message msg = mHandler.obtainMessage(INIT_COPY);
11478        final VerificationInfo verificationInfo = new VerificationInfo(
11479                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11480        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11481                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11482                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11483                null /*certificates*/);
11484        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11485        msg.obj = params;
11486
11487        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11488                System.identityHashCode(msg.obj));
11489        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11490                System.identityHashCode(msg.obj));
11491
11492        mHandler.sendMessage(msg);
11493    }
11494
11495    void installStage(String packageName, File stagedDir, String stagedCid,
11496            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11497            String installerPackageName, int installerUid, UserHandle user,
11498            Certificate[][] certificates) {
11499        if (DEBUG_EPHEMERAL) {
11500            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11501                Slog.d(TAG, "Ephemeral install of " + packageName);
11502            }
11503        }
11504        final VerificationInfo verificationInfo = new VerificationInfo(
11505                sessionParams.originatingUri, sessionParams.referrerUri,
11506                sessionParams.originatingUid, installerUid);
11507
11508        final OriginInfo origin;
11509        if (stagedDir != null) {
11510            origin = OriginInfo.fromStagedFile(stagedDir);
11511        } else {
11512            origin = OriginInfo.fromStagedContainer(stagedCid);
11513        }
11514
11515        final Message msg = mHandler.obtainMessage(INIT_COPY);
11516        final InstallParams params = new InstallParams(origin, null, observer,
11517                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11518                verificationInfo, user, sessionParams.abiOverride,
11519                sessionParams.grantedRuntimePermissions, certificates);
11520        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11521        msg.obj = params;
11522
11523        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11524                System.identityHashCode(msg.obj));
11525        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11526                System.identityHashCode(msg.obj));
11527
11528        mHandler.sendMessage(msg);
11529    }
11530
11531    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11532            int userId) {
11533        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11534        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11535    }
11536
11537    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11538            int appId, int userId) {
11539        Bundle extras = new Bundle(1);
11540        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11541
11542        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11543                packageName, extras, 0, null, null, new int[] {userId});
11544        try {
11545            IActivityManager am = ActivityManagerNative.getDefault();
11546            if (isSystem && am.isUserRunning(userId, 0)) {
11547                // The just-installed/enabled app is bundled on the system, so presumed
11548                // to be able to run automatically without needing an explicit launch.
11549                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11550                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11551                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11552                        .setPackage(packageName);
11553                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11554                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11555            }
11556        } catch (RemoteException e) {
11557            // shouldn't happen
11558            Slog.w(TAG, "Unable to bootstrap installed package", e);
11559        }
11560    }
11561
11562    @Override
11563    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11564            int userId) {
11565        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11566        PackageSetting pkgSetting;
11567        final int uid = Binder.getCallingUid();
11568        enforceCrossUserPermission(uid, userId,
11569                true /* requireFullPermission */, true /* checkShell */,
11570                "setApplicationHiddenSetting for user " + userId);
11571
11572        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11573            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11574            return false;
11575        }
11576
11577        long callingId = Binder.clearCallingIdentity();
11578        try {
11579            boolean sendAdded = false;
11580            boolean sendRemoved = false;
11581            // writer
11582            synchronized (mPackages) {
11583                pkgSetting = mSettings.mPackages.get(packageName);
11584                if (pkgSetting == null) {
11585                    return false;
11586                }
11587                // Do not allow "android" is being disabled
11588                if ("android".equals(packageName)) {
11589                    Slog.w(TAG, "Cannot hide package: android");
11590                    return false;
11591                }
11592                // Only allow protected packages to hide themselves.
11593                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11594                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11595                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11596                    return false;
11597                }
11598
11599                if (pkgSetting.getHidden(userId) != hidden) {
11600                    pkgSetting.setHidden(hidden, userId);
11601                    mSettings.writePackageRestrictionsLPr(userId);
11602                    if (hidden) {
11603                        sendRemoved = true;
11604                    } else {
11605                        sendAdded = true;
11606                    }
11607                }
11608            }
11609            if (sendAdded) {
11610                sendPackageAddedForUser(packageName, pkgSetting, userId);
11611                return true;
11612            }
11613            if (sendRemoved) {
11614                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11615                        "hiding pkg");
11616                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11617                return true;
11618            }
11619        } finally {
11620            Binder.restoreCallingIdentity(callingId);
11621        }
11622        return false;
11623    }
11624
11625    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11626            int userId) {
11627        final PackageRemovedInfo info = new PackageRemovedInfo();
11628        info.removedPackage = packageName;
11629        info.removedUsers = new int[] {userId};
11630        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11631        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11632    }
11633
11634    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11635        if (pkgList.length > 0) {
11636            Bundle extras = new Bundle(1);
11637            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11638
11639            sendPackageBroadcast(
11640                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11641                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11642                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11643                    new int[] {userId});
11644        }
11645    }
11646
11647    /**
11648     * Returns true if application is not found or there was an error. Otherwise it returns
11649     * the hidden state of the package for the given user.
11650     */
11651    @Override
11652    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11653        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11654        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11655                true /* requireFullPermission */, false /* checkShell */,
11656                "getApplicationHidden for user " + userId);
11657        PackageSetting pkgSetting;
11658        long callingId = Binder.clearCallingIdentity();
11659        try {
11660            // writer
11661            synchronized (mPackages) {
11662                pkgSetting = mSettings.mPackages.get(packageName);
11663                if (pkgSetting == null) {
11664                    return true;
11665                }
11666                return pkgSetting.getHidden(userId);
11667            }
11668        } finally {
11669            Binder.restoreCallingIdentity(callingId);
11670        }
11671    }
11672
11673    /**
11674     * @hide
11675     */
11676    @Override
11677    public int installExistingPackageAsUser(String packageName, int userId) {
11678        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11679                null);
11680        PackageSetting pkgSetting;
11681        final int uid = Binder.getCallingUid();
11682        enforceCrossUserPermission(uid, userId,
11683                true /* requireFullPermission */, true /* checkShell */,
11684                "installExistingPackage for user " + userId);
11685        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11686            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11687        }
11688
11689        long callingId = Binder.clearCallingIdentity();
11690        try {
11691            boolean installed = false;
11692
11693            // writer
11694            synchronized (mPackages) {
11695                pkgSetting = mSettings.mPackages.get(packageName);
11696                if (pkgSetting == null) {
11697                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11698                }
11699                if (!pkgSetting.getInstalled(userId)) {
11700                    pkgSetting.setInstalled(true, userId);
11701                    pkgSetting.setHidden(false, userId);
11702                    mSettings.writePackageRestrictionsLPr(userId);
11703                    installed = true;
11704                }
11705            }
11706
11707            if (installed) {
11708                if (pkgSetting.pkg != null) {
11709                    synchronized (mInstallLock) {
11710                        // We don't need to freeze for a brand new install
11711                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11712                    }
11713                }
11714                sendPackageAddedForUser(packageName, pkgSetting, userId);
11715            }
11716        } finally {
11717            Binder.restoreCallingIdentity(callingId);
11718        }
11719
11720        return PackageManager.INSTALL_SUCCEEDED;
11721    }
11722
11723    boolean isUserRestricted(int userId, String restrictionKey) {
11724        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11725        if (restrictions.getBoolean(restrictionKey, false)) {
11726            Log.w(TAG, "User is restricted: " + restrictionKey);
11727            return true;
11728        }
11729        return false;
11730    }
11731
11732    @Override
11733    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11734            int userId) {
11735        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11736        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11737                true /* requireFullPermission */, true /* checkShell */,
11738                "setPackagesSuspended for user " + userId);
11739
11740        if (ArrayUtils.isEmpty(packageNames)) {
11741            return packageNames;
11742        }
11743
11744        // List of package names for whom the suspended state has changed.
11745        List<String> changedPackages = new ArrayList<>(packageNames.length);
11746        // List of package names for whom the suspended state is not set as requested in this
11747        // method.
11748        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11749        long callingId = Binder.clearCallingIdentity();
11750        try {
11751            for (int i = 0; i < packageNames.length; i++) {
11752                String packageName = packageNames[i];
11753                boolean changed = false;
11754                final int appId;
11755                synchronized (mPackages) {
11756                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11757                    if (pkgSetting == null) {
11758                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11759                                + "\". Skipping suspending/un-suspending.");
11760                        unactionedPackages.add(packageName);
11761                        continue;
11762                    }
11763                    appId = pkgSetting.appId;
11764                    if (pkgSetting.getSuspended(userId) != suspended) {
11765                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11766                            unactionedPackages.add(packageName);
11767                            continue;
11768                        }
11769                        pkgSetting.setSuspended(suspended, userId);
11770                        mSettings.writePackageRestrictionsLPr(userId);
11771                        changed = true;
11772                        changedPackages.add(packageName);
11773                    }
11774                }
11775
11776                if (changed && suspended) {
11777                    killApplication(packageName, UserHandle.getUid(userId, appId),
11778                            "suspending package");
11779                }
11780            }
11781        } finally {
11782            Binder.restoreCallingIdentity(callingId);
11783        }
11784
11785        if (!changedPackages.isEmpty()) {
11786            sendPackagesSuspendedForUser(changedPackages.toArray(
11787                    new String[changedPackages.size()]), userId, suspended);
11788        }
11789
11790        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11791    }
11792
11793    @Override
11794    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11795        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11796                true /* requireFullPermission */, false /* checkShell */,
11797                "isPackageSuspendedForUser for user " + userId);
11798        synchronized (mPackages) {
11799            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11800            if (pkgSetting == null) {
11801                throw new IllegalArgumentException("Unknown target package: " + packageName);
11802            }
11803            return pkgSetting.getSuspended(userId);
11804        }
11805    }
11806
11807    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11808        if (isPackageDeviceAdmin(packageName, userId)) {
11809            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11810                    + "\": has an active device admin");
11811            return false;
11812        }
11813
11814        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11815        if (packageName.equals(activeLauncherPackageName)) {
11816            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11817                    + "\": contains the active launcher");
11818            return false;
11819        }
11820
11821        if (packageName.equals(mRequiredInstallerPackage)) {
11822            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11823                    + "\": required for package installation");
11824            return false;
11825        }
11826
11827        if (packageName.equals(mRequiredVerifierPackage)) {
11828            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11829                    + "\": required for package verification");
11830            return false;
11831        }
11832
11833        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11834            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11835                    + "\": is the default dialer");
11836            return false;
11837        }
11838
11839        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11840            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11841                    + "\": protected package");
11842            return false;
11843        }
11844
11845        return true;
11846    }
11847
11848    private String getActiveLauncherPackageName(int userId) {
11849        Intent intent = new Intent(Intent.ACTION_MAIN);
11850        intent.addCategory(Intent.CATEGORY_HOME);
11851        ResolveInfo resolveInfo = resolveIntent(
11852                intent,
11853                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11854                PackageManager.MATCH_DEFAULT_ONLY,
11855                userId);
11856
11857        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11858    }
11859
11860    private String getDefaultDialerPackageName(int userId) {
11861        synchronized (mPackages) {
11862            return mSettings.getDefaultDialerPackageNameLPw(userId);
11863        }
11864    }
11865
11866    @Override
11867    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11868        mContext.enforceCallingOrSelfPermission(
11869                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11870                "Only package verification agents can verify applications");
11871
11872        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11873        final PackageVerificationResponse response = new PackageVerificationResponse(
11874                verificationCode, Binder.getCallingUid());
11875        msg.arg1 = id;
11876        msg.obj = response;
11877        mHandler.sendMessage(msg);
11878    }
11879
11880    @Override
11881    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11882            long millisecondsToDelay) {
11883        mContext.enforceCallingOrSelfPermission(
11884                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11885                "Only package verification agents can extend verification timeouts");
11886
11887        final PackageVerificationState state = mPendingVerification.get(id);
11888        final PackageVerificationResponse response = new PackageVerificationResponse(
11889                verificationCodeAtTimeout, Binder.getCallingUid());
11890
11891        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11892            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11893        }
11894        if (millisecondsToDelay < 0) {
11895            millisecondsToDelay = 0;
11896        }
11897        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11898                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11899            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11900        }
11901
11902        if ((state != null) && !state.timeoutExtended()) {
11903            state.extendTimeout();
11904
11905            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11906            msg.arg1 = id;
11907            msg.obj = response;
11908            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11909        }
11910    }
11911
11912    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11913            int verificationCode, UserHandle user) {
11914        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11915        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11916        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11917        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11918        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11919
11920        mContext.sendBroadcastAsUser(intent, user,
11921                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11922    }
11923
11924    private ComponentName matchComponentForVerifier(String packageName,
11925            List<ResolveInfo> receivers) {
11926        ActivityInfo targetReceiver = null;
11927
11928        final int NR = receivers.size();
11929        for (int i = 0; i < NR; i++) {
11930            final ResolveInfo info = receivers.get(i);
11931            if (info.activityInfo == null) {
11932                continue;
11933            }
11934
11935            if (packageName.equals(info.activityInfo.packageName)) {
11936                targetReceiver = info.activityInfo;
11937                break;
11938            }
11939        }
11940
11941        if (targetReceiver == null) {
11942            return null;
11943        }
11944
11945        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11946    }
11947
11948    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11949            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11950        if (pkgInfo.verifiers.length == 0) {
11951            return null;
11952        }
11953
11954        final int N = pkgInfo.verifiers.length;
11955        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11956        for (int i = 0; i < N; i++) {
11957            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11958
11959            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11960                    receivers);
11961            if (comp == null) {
11962                continue;
11963            }
11964
11965            final int verifierUid = getUidForVerifier(verifierInfo);
11966            if (verifierUid == -1) {
11967                continue;
11968            }
11969
11970            if (DEBUG_VERIFY) {
11971                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11972                        + " with the correct signature");
11973            }
11974            sufficientVerifiers.add(comp);
11975            verificationState.addSufficientVerifier(verifierUid);
11976        }
11977
11978        return sufficientVerifiers;
11979    }
11980
11981    private int getUidForVerifier(VerifierInfo verifierInfo) {
11982        synchronized (mPackages) {
11983            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11984            if (pkg == null) {
11985                return -1;
11986            } else if (pkg.mSignatures.length != 1) {
11987                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11988                        + " has more than one signature; ignoring");
11989                return -1;
11990            }
11991
11992            /*
11993             * If the public key of the package's signature does not match
11994             * our expected public key, then this is a different package and
11995             * we should skip.
11996             */
11997
11998            final byte[] expectedPublicKey;
11999            try {
12000                final Signature verifierSig = pkg.mSignatures[0];
12001                final PublicKey publicKey = verifierSig.getPublicKey();
12002                expectedPublicKey = publicKey.getEncoded();
12003            } catch (CertificateException e) {
12004                return -1;
12005            }
12006
12007            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12008
12009            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12010                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12011                        + " does not have the expected public key; ignoring");
12012                return -1;
12013            }
12014
12015            return pkg.applicationInfo.uid;
12016        }
12017    }
12018
12019    @Override
12020    public void finishPackageInstall(int token, boolean didLaunch) {
12021        enforceSystemOrRoot("Only the system is allowed to finish installs");
12022
12023        if (DEBUG_INSTALL) {
12024            Slog.v(TAG, "BM finishing package install for " + token);
12025        }
12026        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12027
12028        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12029        mHandler.sendMessage(msg);
12030    }
12031
12032    /**
12033     * Get the verification agent timeout.
12034     *
12035     * @return verification timeout in milliseconds
12036     */
12037    private long getVerificationTimeout() {
12038        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12039                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12040                DEFAULT_VERIFICATION_TIMEOUT);
12041    }
12042
12043    /**
12044     * Get the default verification agent response code.
12045     *
12046     * @return default verification response code
12047     */
12048    private int getDefaultVerificationResponse() {
12049        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12050                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12051                DEFAULT_VERIFICATION_RESPONSE);
12052    }
12053
12054    /**
12055     * Check whether or not package verification has been enabled.
12056     *
12057     * @return true if verification should be performed
12058     */
12059    private boolean isVerificationEnabled(int userId, int installFlags) {
12060        if (!DEFAULT_VERIFY_ENABLE) {
12061            return false;
12062        }
12063        // Ephemeral apps don't get the full verification treatment
12064        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12065            if (DEBUG_EPHEMERAL) {
12066                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12067            }
12068            return false;
12069        }
12070
12071        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12072
12073        // Check if installing from ADB
12074        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12075            // Do not run verification in a test harness environment
12076            if (ActivityManager.isRunningInTestHarness()) {
12077                return false;
12078            }
12079            if (ensureVerifyAppsEnabled) {
12080                return true;
12081            }
12082            // Check if the developer does not want package verification for ADB installs
12083            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12084                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12085                return false;
12086            }
12087        }
12088
12089        if (ensureVerifyAppsEnabled) {
12090            return true;
12091        }
12092
12093        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12094                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12095    }
12096
12097    @Override
12098    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12099            throws RemoteException {
12100        mContext.enforceCallingOrSelfPermission(
12101                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12102                "Only intentfilter verification agents can verify applications");
12103
12104        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12105        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12106                Binder.getCallingUid(), verificationCode, failedDomains);
12107        msg.arg1 = id;
12108        msg.obj = response;
12109        mHandler.sendMessage(msg);
12110    }
12111
12112    @Override
12113    public int getIntentVerificationStatus(String packageName, int userId) {
12114        synchronized (mPackages) {
12115            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12116        }
12117    }
12118
12119    @Override
12120    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12121        mContext.enforceCallingOrSelfPermission(
12122                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12123
12124        boolean result = false;
12125        synchronized (mPackages) {
12126            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12127        }
12128        if (result) {
12129            scheduleWritePackageRestrictionsLocked(userId);
12130        }
12131        return result;
12132    }
12133
12134    @Override
12135    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12136            String packageName) {
12137        synchronized (mPackages) {
12138            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12139        }
12140    }
12141
12142    @Override
12143    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12144        if (TextUtils.isEmpty(packageName)) {
12145            return ParceledListSlice.emptyList();
12146        }
12147        synchronized (mPackages) {
12148            PackageParser.Package pkg = mPackages.get(packageName);
12149            if (pkg == null || pkg.activities == null) {
12150                return ParceledListSlice.emptyList();
12151            }
12152            final int count = pkg.activities.size();
12153            ArrayList<IntentFilter> result = new ArrayList<>();
12154            for (int n=0; n<count; n++) {
12155                PackageParser.Activity activity = pkg.activities.get(n);
12156                if (activity.intents != null && activity.intents.size() > 0) {
12157                    result.addAll(activity.intents);
12158                }
12159            }
12160            return new ParceledListSlice<>(result);
12161        }
12162    }
12163
12164    @Override
12165    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12166        mContext.enforceCallingOrSelfPermission(
12167                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12168
12169        synchronized (mPackages) {
12170            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12171            if (packageName != null) {
12172                result |= updateIntentVerificationStatus(packageName,
12173                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12174                        userId);
12175                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12176                        packageName, userId);
12177            }
12178            return result;
12179        }
12180    }
12181
12182    @Override
12183    public String getDefaultBrowserPackageName(int userId) {
12184        synchronized (mPackages) {
12185            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12186        }
12187    }
12188
12189    /**
12190     * Get the "allow unknown sources" setting.
12191     *
12192     * @return the current "allow unknown sources" setting
12193     */
12194    private int getUnknownSourcesSettings() {
12195        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12196                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12197                -1);
12198    }
12199
12200    @Override
12201    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12202        final int uid = Binder.getCallingUid();
12203        // writer
12204        synchronized (mPackages) {
12205            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12206            if (targetPackageSetting == null) {
12207                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12208            }
12209
12210            PackageSetting installerPackageSetting;
12211            if (installerPackageName != null) {
12212                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12213                if (installerPackageSetting == null) {
12214                    throw new IllegalArgumentException("Unknown installer package: "
12215                            + installerPackageName);
12216                }
12217            } else {
12218                installerPackageSetting = null;
12219            }
12220
12221            Signature[] callerSignature;
12222            Object obj = mSettings.getUserIdLPr(uid);
12223            if (obj != null) {
12224                if (obj instanceof SharedUserSetting) {
12225                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12226                } else if (obj instanceof PackageSetting) {
12227                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12228                } else {
12229                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12230                }
12231            } else {
12232                throw new SecurityException("Unknown calling UID: " + uid);
12233            }
12234
12235            // Verify: can't set installerPackageName to a package that is
12236            // not signed with the same cert as the caller.
12237            if (installerPackageSetting != null) {
12238                if (compareSignatures(callerSignature,
12239                        installerPackageSetting.signatures.mSignatures)
12240                        != PackageManager.SIGNATURE_MATCH) {
12241                    throw new SecurityException(
12242                            "Caller does not have same cert as new installer package "
12243                            + installerPackageName);
12244                }
12245            }
12246
12247            // Verify: if target already has an installer package, it must
12248            // be signed with the same cert as the caller.
12249            if (targetPackageSetting.installerPackageName != null) {
12250                PackageSetting setting = mSettings.mPackages.get(
12251                        targetPackageSetting.installerPackageName);
12252                // If the currently set package isn't valid, then it's always
12253                // okay to change it.
12254                if (setting != null) {
12255                    if (compareSignatures(callerSignature,
12256                            setting.signatures.mSignatures)
12257                            != PackageManager.SIGNATURE_MATCH) {
12258                        throw new SecurityException(
12259                                "Caller does not have same cert as old installer package "
12260                                + targetPackageSetting.installerPackageName);
12261                    }
12262                }
12263            }
12264
12265            // Okay!
12266            targetPackageSetting.installerPackageName = installerPackageName;
12267            if (installerPackageName != null) {
12268                mSettings.mInstallerPackages.add(installerPackageName);
12269            }
12270            scheduleWriteSettingsLocked();
12271        }
12272    }
12273
12274    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12275        // Queue up an async operation since the package installation may take a little while.
12276        mHandler.post(new Runnable() {
12277            public void run() {
12278                mHandler.removeCallbacks(this);
12279                 // Result object to be returned
12280                PackageInstalledInfo res = new PackageInstalledInfo();
12281                res.setReturnCode(currentStatus);
12282                res.uid = -1;
12283                res.pkg = null;
12284                res.removedInfo = null;
12285                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12286                    args.doPreInstall(res.returnCode);
12287                    synchronized (mInstallLock) {
12288                        installPackageTracedLI(args, res);
12289                    }
12290                    args.doPostInstall(res.returnCode, res.uid);
12291                }
12292
12293                // A restore should be performed at this point if (a) the install
12294                // succeeded, (b) the operation is not an update, and (c) the new
12295                // package has not opted out of backup participation.
12296                final boolean update = res.removedInfo != null
12297                        && res.removedInfo.removedPackage != null;
12298                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12299                boolean doRestore = !update
12300                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12301
12302                // Set up the post-install work request bookkeeping.  This will be used
12303                // and cleaned up by the post-install event handling regardless of whether
12304                // there's a restore pass performed.  Token values are >= 1.
12305                int token;
12306                if (mNextInstallToken < 0) mNextInstallToken = 1;
12307                token = mNextInstallToken++;
12308
12309                PostInstallData data = new PostInstallData(args, res);
12310                mRunningInstalls.put(token, data);
12311                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12312
12313                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12314                    // Pass responsibility to the Backup Manager.  It will perform a
12315                    // restore if appropriate, then pass responsibility back to the
12316                    // Package Manager to run the post-install observer callbacks
12317                    // and broadcasts.
12318                    IBackupManager bm = IBackupManager.Stub.asInterface(
12319                            ServiceManager.getService(Context.BACKUP_SERVICE));
12320                    if (bm != null) {
12321                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12322                                + " to BM for possible restore");
12323                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12324                        try {
12325                            // TODO: http://b/22388012
12326                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12327                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12328                            } else {
12329                                doRestore = false;
12330                            }
12331                        } catch (RemoteException e) {
12332                            // can't happen; the backup manager is local
12333                        } catch (Exception e) {
12334                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12335                            doRestore = false;
12336                        }
12337                    } else {
12338                        Slog.e(TAG, "Backup Manager not found!");
12339                        doRestore = false;
12340                    }
12341                }
12342
12343                if (!doRestore) {
12344                    // No restore possible, or the Backup Manager was mysteriously not
12345                    // available -- just fire the post-install work request directly.
12346                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12347
12348                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12349
12350                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12351                    mHandler.sendMessage(msg);
12352                }
12353            }
12354        });
12355    }
12356
12357    /**
12358     * Callback from PackageSettings whenever an app is first transitioned out of the
12359     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12360     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12361     * here whether the app is the target of an ongoing install, and only send the
12362     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12363     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12364     * handling.
12365     */
12366    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12367        // Serialize this with the rest of the install-process message chain.  In the
12368        // restore-at-install case, this Runnable will necessarily run before the
12369        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12370        // are coherent.  In the non-restore case, the app has already completed install
12371        // and been launched through some other means, so it is not in a problematic
12372        // state for observers to see the FIRST_LAUNCH signal.
12373        mHandler.post(new Runnable() {
12374            @Override
12375            public void run() {
12376                for (int i = 0; i < mRunningInstalls.size(); i++) {
12377                    final PostInstallData data = mRunningInstalls.valueAt(i);
12378                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12379                        continue;
12380                    }
12381                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12382                        // right package; but is it for the right user?
12383                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12384                            if (userId == data.res.newUsers[uIndex]) {
12385                                if (DEBUG_BACKUP) {
12386                                    Slog.i(TAG, "Package " + pkgName
12387                                            + " being restored so deferring FIRST_LAUNCH");
12388                                }
12389                                return;
12390                            }
12391                        }
12392                    }
12393                }
12394                // didn't find it, so not being restored
12395                if (DEBUG_BACKUP) {
12396                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12397                }
12398                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12399            }
12400        });
12401    }
12402
12403    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12404        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12405                installerPkg, null, userIds);
12406    }
12407
12408    private abstract class HandlerParams {
12409        private static final int MAX_RETRIES = 4;
12410
12411        /**
12412         * Number of times startCopy() has been attempted and had a non-fatal
12413         * error.
12414         */
12415        private int mRetries = 0;
12416
12417        /** User handle for the user requesting the information or installation. */
12418        private final UserHandle mUser;
12419        String traceMethod;
12420        int traceCookie;
12421
12422        HandlerParams(UserHandle user) {
12423            mUser = user;
12424        }
12425
12426        UserHandle getUser() {
12427            return mUser;
12428        }
12429
12430        HandlerParams setTraceMethod(String traceMethod) {
12431            this.traceMethod = traceMethod;
12432            return this;
12433        }
12434
12435        HandlerParams setTraceCookie(int traceCookie) {
12436            this.traceCookie = traceCookie;
12437            return this;
12438        }
12439
12440        final boolean startCopy() {
12441            boolean res;
12442            try {
12443                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12444
12445                if (++mRetries > MAX_RETRIES) {
12446                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12447                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12448                    handleServiceError();
12449                    return false;
12450                } else {
12451                    handleStartCopy();
12452                    res = true;
12453                }
12454            } catch (RemoteException e) {
12455                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12456                mHandler.sendEmptyMessage(MCS_RECONNECT);
12457                res = false;
12458            }
12459            handleReturnCode();
12460            return res;
12461        }
12462
12463        final void serviceError() {
12464            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12465            handleServiceError();
12466            handleReturnCode();
12467        }
12468
12469        abstract void handleStartCopy() throws RemoteException;
12470        abstract void handleServiceError();
12471        abstract void handleReturnCode();
12472    }
12473
12474    class MeasureParams extends HandlerParams {
12475        private final PackageStats mStats;
12476        private boolean mSuccess;
12477
12478        private final IPackageStatsObserver mObserver;
12479
12480        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12481            super(new UserHandle(stats.userHandle));
12482            mObserver = observer;
12483            mStats = stats;
12484        }
12485
12486        @Override
12487        public String toString() {
12488            return "MeasureParams{"
12489                + Integer.toHexString(System.identityHashCode(this))
12490                + " " + mStats.packageName + "}";
12491        }
12492
12493        @Override
12494        void handleStartCopy() throws RemoteException {
12495            synchronized (mInstallLock) {
12496                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12497            }
12498
12499            if (mSuccess) {
12500                boolean mounted = false;
12501                try {
12502                    final String status = Environment.getExternalStorageState();
12503                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12504                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12505                } catch (Exception e) {
12506                }
12507
12508                if (mounted) {
12509                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12510
12511                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12512                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12513
12514                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12515                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12516
12517                    // Always subtract cache size, since it's a subdirectory
12518                    mStats.externalDataSize -= mStats.externalCacheSize;
12519
12520                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12521                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12522
12523                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12524                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12525                }
12526            }
12527        }
12528
12529        @Override
12530        void handleReturnCode() {
12531            if (mObserver != null) {
12532                try {
12533                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12534                } catch (RemoteException e) {
12535                    Slog.i(TAG, "Observer no longer exists.");
12536                }
12537            }
12538        }
12539
12540        @Override
12541        void handleServiceError() {
12542            Slog.e(TAG, "Could not measure application " + mStats.packageName
12543                            + " external storage");
12544        }
12545    }
12546
12547    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12548            throws RemoteException {
12549        long result = 0;
12550        for (File path : paths) {
12551            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12552        }
12553        return result;
12554    }
12555
12556    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12557        for (File path : paths) {
12558            try {
12559                mcs.clearDirectory(path.getAbsolutePath());
12560            } catch (RemoteException e) {
12561            }
12562        }
12563    }
12564
12565    static class OriginInfo {
12566        /**
12567         * Location where install is coming from, before it has been
12568         * copied/renamed into place. This could be a single monolithic APK
12569         * file, or a cluster directory. This location may be untrusted.
12570         */
12571        final File file;
12572        final String cid;
12573
12574        /**
12575         * Flag indicating that {@link #file} or {@link #cid} has already been
12576         * staged, meaning downstream users don't need to defensively copy the
12577         * contents.
12578         */
12579        final boolean staged;
12580
12581        /**
12582         * Flag indicating that {@link #file} or {@link #cid} is an already
12583         * installed app that is being moved.
12584         */
12585        final boolean existing;
12586
12587        final String resolvedPath;
12588        final File resolvedFile;
12589
12590        static OriginInfo fromNothing() {
12591            return new OriginInfo(null, null, false, false);
12592        }
12593
12594        static OriginInfo fromUntrustedFile(File file) {
12595            return new OriginInfo(file, null, false, false);
12596        }
12597
12598        static OriginInfo fromExistingFile(File file) {
12599            return new OriginInfo(file, null, false, true);
12600        }
12601
12602        static OriginInfo fromStagedFile(File file) {
12603            return new OriginInfo(file, null, true, false);
12604        }
12605
12606        static OriginInfo fromStagedContainer(String cid) {
12607            return new OriginInfo(null, cid, true, false);
12608        }
12609
12610        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12611            this.file = file;
12612            this.cid = cid;
12613            this.staged = staged;
12614            this.existing = existing;
12615
12616            if (cid != null) {
12617                resolvedPath = PackageHelper.getSdDir(cid);
12618                resolvedFile = new File(resolvedPath);
12619            } else if (file != null) {
12620                resolvedPath = file.getAbsolutePath();
12621                resolvedFile = file;
12622            } else {
12623                resolvedPath = null;
12624                resolvedFile = null;
12625            }
12626        }
12627    }
12628
12629    static class MoveInfo {
12630        final int moveId;
12631        final String fromUuid;
12632        final String toUuid;
12633        final String packageName;
12634        final String dataAppName;
12635        final int appId;
12636        final String seinfo;
12637        final int targetSdkVersion;
12638
12639        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12640                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12641            this.moveId = moveId;
12642            this.fromUuid = fromUuid;
12643            this.toUuid = toUuid;
12644            this.packageName = packageName;
12645            this.dataAppName = dataAppName;
12646            this.appId = appId;
12647            this.seinfo = seinfo;
12648            this.targetSdkVersion = targetSdkVersion;
12649        }
12650    }
12651
12652    static class VerificationInfo {
12653        /** A constant used to indicate that a uid value is not present. */
12654        public static final int NO_UID = -1;
12655
12656        /** URI referencing where the package was downloaded from. */
12657        final Uri originatingUri;
12658
12659        /** HTTP referrer URI associated with the originatingURI. */
12660        final Uri referrer;
12661
12662        /** UID of the application that the install request originated from. */
12663        final int originatingUid;
12664
12665        /** UID of application requesting the install */
12666        final int installerUid;
12667
12668        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12669            this.originatingUri = originatingUri;
12670            this.referrer = referrer;
12671            this.originatingUid = originatingUid;
12672            this.installerUid = installerUid;
12673        }
12674    }
12675
12676    class InstallParams extends HandlerParams {
12677        final OriginInfo origin;
12678        final MoveInfo move;
12679        final IPackageInstallObserver2 observer;
12680        int installFlags;
12681        final String installerPackageName;
12682        final String volumeUuid;
12683        private InstallArgs mArgs;
12684        private int mRet;
12685        final String packageAbiOverride;
12686        final String[] grantedRuntimePermissions;
12687        final VerificationInfo verificationInfo;
12688        final Certificate[][] certificates;
12689
12690        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12691                int installFlags, String installerPackageName, String volumeUuid,
12692                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12693                String[] grantedPermissions, Certificate[][] certificates) {
12694            super(user);
12695            this.origin = origin;
12696            this.move = move;
12697            this.observer = observer;
12698            this.installFlags = installFlags;
12699            this.installerPackageName = installerPackageName;
12700            this.volumeUuid = volumeUuid;
12701            this.verificationInfo = verificationInfo;
12702            this.packageAbiOverride = packageAbiOverride;
12703            this.grantedRuntimePermissions = grantedPermissions;
12704            this.certificates = certificates;
12705        }
12706
12707        @Override
12708        public String toString() {
12709            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12710                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12711        }
12712
12713        private int installLocationPolicy(PackageInfoLite pkgLite) {
12714            String packageName = pkgLite.packageName;
12715            int installLocation = pkgLite.installLocation;
12716            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12717            // reader
12718            synchronized (mPackages) {
12719                // Currently installed package which the new package is attempting to replace or
12720                // null if no such package is installed.
12721                PackageParser.Package installedPkg = mPackages.get(packageName);
12722                // Package which currently owns the data which the new package will own if installed.
12723                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12724                // will be null whereas dataOwnerPkg will contain information about the package
12725                // which was uninstalled while keeping its data.
12726                PackageParser.Package dataOwnerPkg = installedPkg;
12727                if (dataOwnerPkg  == null) {
12728                    PackageSetting ps = mSettings.mPackages.get(packageName);
12729                    if (ps != null) {
12730                        dataOwnerPkg = ps.pkg;
12731                    }
12732                }
12733
12734                if (dataOwnerPkg != null) {
12735                    // If installed, the package will get access to data left on the device by its
12736                    // predecessor. As a security measure, this is permited only if this is not a
12737                    // version downgrade or if the predecessor package is marked as debuggable and
12738                    // a downgrade is explicitly requested.
12739                    //
12740                    // On debuggable platform builds, downgrades are permitted even for
12741                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12742                    // not offer security guarantees and thus it's OK to disable some security
12743                    // mechanisms to make debugging/testing easier on those builds. However, even on
12744                    // debuggable builds downgrades of packages are permitted only if requested via
12745                    // installFlags. This is because we aim to keep the behavior of debuggable
12746                    // platform builds as close as possible to the behavior of non-debuggable
12747                    // platform builds.
12748                    final boolean downgradeRequested =
12749                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12750                    final boolean packageDebuggable =
12751                                (dataOwnerPkg.applicationInfo.flags
12752                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12753                    final boolean downgradePermitted =
12754                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12755                    if (!downgradePermitted) {
12756                        try {
12757                            checkDowngrade(dataOwnerPkg, pkgLite);
12758                        } catch (PackageManagerException e) {
12759                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12760                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12761                        }
12762                    }
12763                }
12764
12765                if (installedPkg != null) {
12766                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12767                        // Check for updated system application.
12768                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12769                            if (onSd) {
12770                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12771                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12772                            }
12773                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12774                        } else {
12775                            if (onSd) {
12776                                // Install flag overrides everything.
12777                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12778                            }
12779                            // If current upgrade specifies particular preference
12780                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12781                                // Application explicitly specified internal.
12782                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12783                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12784                                // App explictly prefers external. Let policy decide
12785                            } else {
12786                                // Prefer previous location
12787                                if (isExternal(installedPkg)) {
12788                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12789                                }
12790                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12791                            }
12792                        }
12793                    } else {
12794                        // Invalid install. Return error code
12795                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12796                    }
12797                }
12798            }
12799            // All the special cases have been taken care of.
12800            // Return result based on recommended install location.
12801            if (onSd) {
12802                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12803            }
12804            return pkgLite.recommendedInstallLocation;
12805        }
12806
12807        /*
12808         * Invoke remote method to get package information and install
12809         * location values. Override install location based on default
12810         * policy if needed and then create install arguments based
12811         * on the install location.
12812         */
12813        public void handleStartCopy() throws RemoteException {
12814            int ret = PackageManager.INSTALL_SUCCEEDED;
12815
12816            // If we're already staged, we've firmly committed to an install location
12817            if (origin.staged) {
12818                if (origin.file != null) {
12819                    installFlags |= PackageManager.INSTALL_INTERNAL;
12820                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12821                } else if (origin.cid != null) {
12822                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12823                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12824                } else {
12825                    throw new IllegalStateException("Invalid stage location");
12826                }
12827            }
12828
12829            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12830            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12831            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12832            PackageInfoLite pkgLite = null;
12833
12834            if (onInt && onSd) {
12835                // Check if both bits are set.
12836                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12837                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12838            } else if (onSd && ephemeral) {
12839                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12840                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12841            } else {
12842                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12843                        packageAbiOverride);
12844
12845                if (DEBUG_EPHEMERAL && ephemeral) {
12846                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12847                }
12848
12849                /*
12850                 * If we have too little free space, try to free cache
12851                 * before giving up.
12852                 */
12853                if (!origin.staged && pkgLite.recommendedInstallLocation
12854                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12855                    // TODO: focus freeing disk space on the target device
12856                    final StorageManager storage = StorageManager.from(mContext);
12857                    final long lowThreshold = storage.getStorageLowBytes(
12858                            Environment.getDataDirectory());
12859
12860                    final long sizeBytes = mContainerService.calculateInstalledSize(
12861                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12862
12863                    try {
12864                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12865                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12866                                installFlags, packageAbiOverride);
12867                    } catch (InstallerException e) {
12868                        Slog.w(TAG, "Failed to free cache", e);
12869                    }
12870
12871                    /*
12872                     * The cache free must have deleted the file we
12873                     * downloaded to install.
12874                     *
12875                     * TODO: fix the "freeCache" call to not delete
12876                     *       the file we care about.
12877                     */
12878                    if (pkgLite.recommendedInstallLocation
12879                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12880                        pkgLite.recommendedInstallLocation
12881                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12882                    }
12883                }
12884            }
12885
12886            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12887                int loc = pkgLite.recommendedInstallLocation;
12888                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12889                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12890                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12891                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12892                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12893                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12894                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12895                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12896                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12897                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12898                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12899                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12900                } else {
12901                    // Override with defaults if needed.
12902                    loc = installLocationPolicy(pkgLite);
12903                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12904                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12905                    } else if (!onSd && !onInt) {
12906                        // Override install location with flags
12907                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12908                            // Set the flag to install on external media.
12909                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12910                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12911                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12912                            if (DEBUG_EPHEMERAL) {
12913                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12914                            }
12915                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12916                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12917                                    |PackageManager.INSTALL_INTERNAL);
12918                        } else {
12919                            // Make sure the flag for installing on external
12920                            // media is unset
12921                            installFlags |= PackageManager.INSTALL_INTERNAL;
12922                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12923                        }
12924                    }
12925                }
12926            }
12927
12928            final InstallArgs args = createInstallArgs(this);
12929            mArgs = args;
12930
12931            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12932                // TODO: http://b/22976637
12933                // Apps installed for "all" users use the device owner to verify the app
12934                UserHandle verifierUser = getUser();
12935                if (verifierUser == UserHandle.ALL) {
12936                    verifierUser = UserHandle.SYSTEM;
12937                }
12938
12939                /*
12940                 * Determine if we have any installed package verifiers. If we
12941                 * do, then we'll defer to them to verify the packages.
12942                 */
12943                final int requiredUid = mRequiredVerifierPackage == null ? -1
12944                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12945                                verifierUser.getIdentifier());
12946                if (!origin.existing && requiredUid != -1
12947                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12948                    final Intent verification = new Intent(
12949                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12950                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12951                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12952                            PACKAGE_MIME_TYPE);
12953                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12954
12955                    // Query all live verifiers based on current user state
12956                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12957                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12958
12959                    if (DEBUG_VERIFY) {
12960                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12961                                + verification.toString() + " with " + pkgLite.verifiers.length
12962                                + " optional verifiers");
12963                    }
12964
12965                    final int verificationId = mPendingVerificationToken++;
12966
12967                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12968
12969                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12970                            installerPackageName);
12971
12972                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12973                            installFlags);
12974
12975                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12976                            pkgLite.packageName);
12977
12978                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12979                            pkgLite.versionCode);
12980
12981                    if (verificationInfo != null) {
12982                        if (verificationInfo.originatingUri != null) {
12983                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12984                                    verificationInfo.originatingUri);
12985                        }
12986                        if (verificationInfo.referrer != null) {
12987                            verification.putExtra(Intent.EXTRA_REFERRER,
12988                                    verificationInfo.referrer);
12989                        }
12990                        if (verificationInfo.originatingUid >= 0) {
12991                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12992                                    verificationInfo.originatingUid);
12993                        }
12994                        if (verificationInfo.installerUid >= 0) {
12995                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12996                                    verificationInfo.installerUid);
12997                        }
12998                    }
12999
13000                    final PackageVerificationState verificationState = new PackageVerificationState(
13001                            requiredUid, args);
13002
13003                    mPendingVerification.append(verificationId, verificationState);
13004
13005                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13006                            receivers, verificationState);
13007
13008                    /*
13009                     * If any sufficient verifiers were listed in the package
13010                     * manifest, attempt to ask them.
13011                     */
13012                    if (sufficientVerifiers != null) {
13013                        final int N = sufficientVerifiers.size();
13014                        if (N == 0) {
13015                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13016                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13017                        } else {
13018                            for (int i = 0; i < N; i++) {
13019                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13020
13021                                final Intent sufficientIntent = new Intent(verification);
13022                                sufficientIntent.setComponent(verifierComponent);
13023                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13024                            }
13025                        }
13026                    }
13027
13028                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13029                            mRequiredVerifierPackage, receivers);
13030                    if (ret == PackageManager.INSTALL_SUCCEEDED
13031                            && mRequiredVerifierPackage != null) {
13032                        Trace.asyncTraceBegin(
13033                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13034                        /*
13035                         * Send the intent to the required verification agent,
13036                         * but only start the verification timeout after the
13037                         * target BroadcastReceivers have run.
13038                         */
13039                        verification.setComponent(requiredVerifierComponent);
13040                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13041                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13042                                new BroadcastReceiver() {
13043                                    @Override
13044                                    public void onReceive(Context context, Intent intent) {
13045                                        final Message msg = mHandler
13046                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13047                                        msg.arg1 = verificationId;
13048                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13049                                    }
13050                                }, null, 0, null, null);
13051
13052                        /*
13053                         * We don't want the copy to proceed until verification
13054                         * succeeds, so null out this field.
13055                         */
13056                        mArgs = null;
13057                    }
13058                } else {
13059                    /*
13060                     * No package verification is enabled, so immediately start
13061                     * the remote call to initiate copy using temporary file.
13062                     */
13063                    ret = args.copyApk(mContainerService, true);
13064                }
13065            }
13066
13067            mRet = ret;
13068        }
13069
13070        @Override
13071        void handleReturnCode() {
13072            // If mArgs is null, then MCS couldn't be reached. When it
13073            // reconnects, it will try again to install. At that point, this
13074            // will succeed.
13075            if (mArgs != null) {
13076                processPendingInstall(mArgs, mRet);
13077            }
13078        }
13079
13080        @Override
13081        void handleServiceError() {
13082            mArgs = createInstallArgs(this);
13083            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13084        }
13085
13086        public boolean isForwardLocked() {
13087            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13088        }
13089    }
13090
13091    /**
13092     * Used during creation of InstallArgs
13093     *
13094     * @param installFlags package installation flags
13095     * @return true if should be installed on external storage
13096     */
13097    private static boolean installOnExternalAsec(int installFlags) {
13098        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13099            return false;
13100        }
13101        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13102            return true;
13103        }
13104        return false;
13105    }
13106
13107    /**
13108     * Used during creation of InstallArgs
13109     *
13110     * @param installFlags package installation flags
13111     * @return true if should be installed as forward locked
13112     */
13113    private static boolean installForwardLocked(int installFlags) {
13114        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13115    }
13116
13117    private InstallArgs createInstallArgs(InstallParams params) {
13118        if (params.move != null) {
13119            return new MoveInstallArgs(params);
13120        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13121            return new AsecInstallArgs(params);
13122        } else {
13123            return new FileInstallArgs(params);
13124        }
13125    }
13126
13127    /**
13128     * Create args that describe an existing installed package. Typically used
13129     * when cleaning up old installs, or used as a move source.
13130     */
13131    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13132            String resourcePath, String[] instructionSets) {
13133        final boolean isInAsec;
13134        if (installOnExternalAsec(installFlags)) {
13135            /* Apps on SD card are always in ASEC containers. */
13136            isInAsec = true;
13137        } else if (installForwardLocked(installFlags)
13138                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13139            /*
13140             * Forward-locked apps are only in ASEC containers if they're the
13141             * new style
13142             */
13143            isInAsec = true;
13144        } else {
13145            isInAsec = false;
13146        }
13147
13148        if (isInAsec) {
13149            return new AsecInstallArgs(codePath, instructionSets,
13150                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13151        } else {
13152            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13153        }
13154    }
13155
13156    static abstract class InstallArgs {
13157        /** @see InstallParams#origin */
13158        final OriginInfo origin;
13159        /** @see InstallParams#move */
13160        final MoveInfo move;
13161
13162        final IPackageInstallObserver2 observer;
13163        // Always refers to PackageManager flags only
13164        final int installFlags;
13165        final String installerPackageName;
13166        final String volumeUuid;
13167        final UserHandle user;
13168        final String abiOverride;
13169        final String[] installGrantPermissions;
13170        /** If non-null, drop an async trace when the install completes */
13171        final String traceMethod;
13172        final int traceCookie;
13173        final Certificate[][] certificates;
13174
13175        // The list of instruction sets supported by this app. This is currently
13176        // only used during the rmdex() phase to clean up resources. We can get rid of this
13177        // if we move dex files under the common app path.
13178        /* nullable */ String[] instructionSets;
13179
13180        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13181                int installFlags, String installerPackageName, String volumeUuid,
13182                UserHandle user, String[] instructionSets,
13183                String abiOverride, String[] installGrantPermissions,
13184                String traceMethod, int traceCookie, Certificate[][] certificates) {
13185            this.origin = origin;
13186            this.move = move;
13187            this.installFlags = installFlags;
13188            this.observer = observer;
13189            this.installerPackageName = installerPackageName;
13190            this.volumeUuid = volumeUuid;
13191            this.user = user;
13192            this.instructionSets = instructionSets;
13193            this.abiOverride = abiOverride;
13194            this.installGrantPermissions = installGrantPermissions;
13195            this.traceMethod = traceMethod;
13196            this.traceCookie = traceCookie;
13197            this.certificates = certificates;
13198        }
13199
13200        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13201        abstract int doPreInstall(int status);
13202
13203        /**
13204         * Rename package into final resting place. All paths on the given
13205         * scanned package should be updated to reflect the rename.
13206         */
13207        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13208        abstract int doPostInstall(int status, int uid);
13209
13210        /** @see PackageSettingBase#codePathString */
13211        abstract String getCodePath();
13212        /** @see PackageSettingBase#resourcePathString */
13213        abstract String getResourcePath();
13214
13215        // Need installer lock especially for dex file removal.
13216        abstract void cleanUpResourcesLI();
13217        abstract boolean doPostDeleteLI(boolean delete);
13218
13219        /**
13220         * Called before the source arguments are copied. This is used mostly
13221         * for MoveParams when it needs to read the source file to put it in the
13222         * destination.
13223         */
13224        int doPreCopy() {
13225            return PackageManager.INSTALL_SUCCEEDED;
13226        }
13227
13228        /**
13229         * Called after the source arguments are copied. This is used mostly for
13230         * MoveParams when it needs to read the source file to put it in the
13231         * destination.
13232         */
13233        int doPostCopy(int uid) {
13234            return PackageManager.INSTALL_SUCCEEDED;
13235        }
13236
13237        protected boolean isFwdLocked() {
13238            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13239        }
13240
13241        protected boolean isExternalAsec() {
13242            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13243        }
13244
13245        protected boolean isEphemeral() {
13246            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13247        }
13248
13249        UserHandle getUser() {
13250            return user;
13251        }
13252    }
13253
13254    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13255        if (!allCodePaths.isEmpty()) {
13256            if (instructionSets == null) {
13257                throw new IllegalStateException("instructionSet == null");
13258            }
13259            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13260            for (String codePath : allCodePaths) {
13261                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13262                    try {
13263                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13264                    } catch (InstallerException ignored) {
13265                    }
13266                }
13267            }
13268        }
13269    }
13270
13271    /**
13272     * Logic to handle installation of non-ASEC applications, including copying
13273     * and renaming logic.
13274     */
13275    class FileInstallArgs extends InstallArgs {
13276        private File codeFile;
13277        private File resourceFile;
13278
13279        // Example topology:
13280        // /data/app/com.example/base.apk
13281        // /data/app/com.example/split_foo.apk
13282        // /data/app/com.example/lib/arm/libfoo.so
13283        // /data/app/com.example/lib/arm64/libfoo.so
13284        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13285
13286        /** New install */
13287        FileInstallArgs(InstallParams params) {
13288            super(params.origin, params.move, params.observer, params.installFlags,
13289                    params.installerPackageName, params.volumeUuid,
13290                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13291                    params.grantedRuntimePermissions,
13292                    params.traceMethod, params.traceCookie, params.certificates);
13293            if (isFwdLocked()) {
13294                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13295            }
13296        }
13297
13298        /** Existing install */
13299        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13300            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13301                    null, null, null, 0, null /*certificates*/);
13302            this.codeFile = (codePath != null) ? new File(codePath) : null;
13303            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13304        }
13305
13306        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13307            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13308            try {
13309                return doCopyApk(imcs, temp);
13310            } finally {
13311                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13312            }
13313        }
13314
13315        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13316            if (origin.staged) {
13317                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13318                codeFile = origin.file;
13319                resourceFile = origin.file;
13320                return PackageManager.INSTALL_SUCCEEDED;
13321            }
13322
13323            try {
13324                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13325                final File tempDir =
13326                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13327                codeFile = tempDir;
13328                resourceFile = tempDir;
13329            } catch (IOException e) {
13330                Slog.w(TAG, "Failed to create copy file: " + e);
13331                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13332            }
13333
13334            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13335                @Override
13336                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13337                    if (!FileUtils.isValidExtFilename(name)) {
13338                        throw new IllegalArgumentException("Invalid filename: " + name);
13339                    }
13340                    try {
13341                        final File file = new File(codeFile, name);
13342                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13343                                O_RDWR | O_CREAT, 0644);
13344                        Os.chmod(file.getAbsolutePath(), 0644);
13345                        return new ParcelFileDescriptor(fd);
13346                    } catch (ErrnoException e) {
13347                        throw new RemoteException("Failed to open: " + e.getMessage());
13348                    }
13349                }
13350            };
13351
13352            int ret = PackageManager.INSTALL_SUCCEEDED;
13353            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13354            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13355                Slog.e(TAG, "Failed to copy package");
13356                return ret;
13357            }
13358
13359            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13360            NativeLibraryHelper.Handle handle = null;
13361            try {
13362                handle = NativeLibraryHelper.Handle.create(codeFile);
13363                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13364                        abiOverride);
13365            } catch (IOException e) {
13366                Slog.e(TAG, "Copying native libraries failed", e);
13367                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13368            } finally {
13369                IoUtils.closeQuietly(handle);
13370            }
13371
13372            return ret;
13373        }
13374
13375        int doPreInstall(int status) {
13376            if (status != PackageManager.INSTALL_SUCCEEDED) {
13377                cleanUp();
13378            }
13379            return status;
13380        }
13381
13382        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13383            if (status != PackageManager.INSTALL_SUCCEEDED) {
13384                cleanUp();
13385                return false;
13386            }
13387
13388            final File targetDir = codeFile.getParentFile();
13389            final File beforeCodeFile = codeFile;
13390            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13391
13392            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13393            try {
13394                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13395            } catch (ErrnoException e) {
13396                Slog.w(TAG, "Failed to rename", e);
13397                return false;
13398            }
13399
13400            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13401                Slog.w(TAG, "Failed to restorecon");
13402                return false;
13403            }
13404
13405            // Reflect the rename internally
13406            codeFile = afterCodeFile;
13407            resourceFile = afterCodeFile;
13408
13409            // Reflect the rename in scanned details
13410            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13411            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13412                    afterCodeFile, pkg.baseCodePath));
13413            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13414                    afterCodeFile, pkg.splitCodePaths));
13415
13416            // Reflect the rename in app info
13417            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13418            pkg.setApplicationInfoCodePath(pkg.codePath);
13419            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13420            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13421            pkg.setApplicationInfoResourcePath(pkg.codePath);
13422            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13423            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13424
13425            return true;
13426        }
13427
13428        int doPostInstall(int status, int uid) {
13429            if (status != PackageManager.INSTALL_SUCCEEDED) {
13430                cleanUp();
13431            }
13432            return status;
13433        }
13434
13435        @Override
13436        String getCodePath() {
13437            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13438        }
13439
13440        @Override
13441        String getResourcePath() {
13442            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13443        }
13444
13445        private boolean cleanUp() {
13446            if (codeFile == null || !codeFile.exists()) {
13447                return false;
13448            }
13449
13450            removeCodePathLI(codeFile);
13451
13452            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13453                resourceFile.delete();
13454            }
13455
13456            return true;
13457        }
13458
13459        void cleanUpResourcesLI() {
13460            // Try enumerating all code paths before deleting
13461            List<String> allCodePaths = Collections.EMPTY_LIST;
13462            if (codeFile != null && codeFile.exists()) {
13463                try {
13464                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13465                    allCodePaths = pkg.getAllCodePaths();
13466                } catch (PackageParserException e) {
13467                    // Ignored; we tried our best
13468                }
13469            }
13470
13471            cleanUp();
13472            removeDexFiles(allCodePaths, instructionSets);
13473        }
13474
13475        boolean doPostDeleteLI(boolean delete) {
13476            // XXX err, shouldn't we respect the delete flag?
13477            cleanUpResourcesLI();
13478            return true;
13479        }
13480    }
13481
13482    private boolean isAsecExternal(String cid) {
13483        final String asecPath = PackageHelper.getSdFilesystem(cid);
13484        return !asecPath.startsWith(mAsecInternalPath);
13485    }
13486
13487    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13488            PackageManagerException {
13489        if (copyRet < 0) {
13490            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13491                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13492                throw new PackageManagerException(copyRet, message);
13493            }
13494        }
13495    }
13496
13497    /**
13498     * Extract the MountService "container ID" from the full code path of an
13499     * .apk.
13500     */
13501    static String cidFromCodePath(String fullCodePath) {
13502        int eidx = fullCodePath.lastIndexOf("/");
13503        String subStr1 = fullCodePath.substring(0, eidx);
13504        int sidx = subStr1.lastIndexOf("/");
13505        return subStr1.substring(sidx+1, eidx);
13506    }
13507
13508    /**
13509     * Logic to handle installation of ASEC applications, including copying and
13510     * renaming logic.
13511     */
13512    class AsecInstallArgs extends InstallArgs {
13513        static final String RES_FILE_NAME = "pkg.apk";
13514        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13515
13516        String cid;
13517        String packagePath;
13518        String resourcePath;
13519
13520        /** New install */
13521        AsecInstallArgs(InstallParams params) {
13522            super(params.origin, params.move, params.observer, params.installFlags,
13523                    params.installerPackageName, params.volumeUuid,
13524                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13525                    params.grantedRuntimePermissions,
13526                    params.traceMethod, params.traceCookie, params.certificates);
13527        }
13528
13529        /** Existing install */
13530        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13531                        boolean isExternal, boolean isForwardLocked) {
13532            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13533              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13534                    instructionSets, null, null, null, 0, null /*certificates*/);
13535            // Hackily pretend we're still looking at a full code path
13536            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13537                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13538            }
13539
13540            // Extract cid from fullCodePath
13541            int eidx = fullCodePath.lastIndexOf("/");
13542            String subStr1 = fullCodePath.substring(0, eidx);
13543            int sidx = subStr1.lastIndexOf("/");
13544            cid = subStr1.substring(sidx+1, eidx);
13545            setMountPath(subStr1);
13546        }
13547
13548        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13549            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13550              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13551                    instructionSets, null, null, null, 0, null /*certificates*/);
13552            this.cid = cid;
13553            setMountPath(PackageHelper.getSdDir(cid));
13554        }
13555
13556        void createCopyFile() {
13557            cid = mInstallerService.allocateExternalStageCidLegacy();
13558        }
13559
13560        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13561            if (origin.staged && origin.cid != null) {
13562                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13563                cid = origin.cid;
13564                setMountPath(PackageHelper.getSdDir(cid));
13565                return PackageManager.INSTALL_SUCCEEDED;
13566            }
13567
13568            if (temp) {
13569                createCopyFile();
13570            } else {
13571                /*
13572                 * Pre-emptively destroy the container since it's destroyed if
13573                 * copying fails due to it existing anyway.
13574                 */
13575                PackageHelper.destroySdDir(cid);
13576            }
13577
13578            final String newMountPath = imcs.copyPackageToContainer(
13579                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13580                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13581
13582            if (newMountPath != null) {
13583                setMountPath(newMountPath);
13584                return PackageManager.INSTALL_SUCCEEDED;
13585            } else {
13586                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13587            }
13588        }
13589
13590        @Override
13591        String getCodePath() {
13592            return packagePath;
13593        }
13594
13595        @Override
13596        String getResourcePath() {
13597            return resourcePath;
13598        }
13599
13600        int doPreInstall(int status) {
13601            if (status != PackageManager.INSTALL_SUCCEEDED) {
13602                // Destroy container
13603                PackageHelper.destroySdDir(cid);
13604            } else {
13605                boolean mounted = PackageHelper.isContainerMounted(cid);
13606                if (!mounted) {
13607                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13608                            Process.SYSTEM_UID);
13609                    if (newMountPath != null) {
13610                        setMountPath(newMountPath);
13611                    } else {
13612                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13613                    }
13614                }
13615            }
13616            return status;
13617        }
13618
13619        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13620            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13621            String newMountPath = null;
13622            if (PackageHelper.isContainerMounted(cid)) {
13623                // Unmount the container
13624                if (!PackageHelper.unMountSdDir(cid)) {
13625                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13626                    return false;
13627                }
13628            }
13629            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13630                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13631                        " which might be stale. Will try to clean up.");
13632                // Clean up the stale container and proceed to recreate.
13633                if (!PackageHelper.destroySdDir(newCacheId)) {
13634                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13635                    return false;
13636                }
13637                // Successfully cleaned up stale container. Try to rename again.
13638                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13639                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13640                            + " inspite of cleaning it up.");
13641                    return false;
13642                }
13643            }
13644            if (!PackageHelper.isContainerMounted(newCacheId)) {
13645                Slog.w(TAG, "Mounting container " + newCacheId);
13646                newMountPath = PackageHelper.mountSdDir(newCacheId,
13647                        getEncryptKey(), Process.SYSTEM_UID);
13648            } else {
13649                newMountPath = PackageHelper.getSdDir(newCacheId);
13650            }
13651            if (newMountPath == null) {
13652                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13653                return false;
13654            }
13655            Log.i(TAG, "Succesfully renamed " + cid +
13656                    " to " + newCacheId +
13657                    " at new path: " + newMountPath);
13658            cid = newCacheId;
13659
13660            final File beforeCodeFile = new File(packagePath);
13661            setMountPath(newMountPath);
13662            final File afterCodeFile = new File(packagePath);
13663
13664            // Reflect the rename in scanned details
13665            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13666            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13667                    afterCodeFile, pkg.baseCodePath));
13668            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13669                    afterCodeFile, pkg.splitCodePaths));
13670
13671            // Reflect the rename in app info
13672            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13673            pkg.setApplicationInfoCodePath(pkg.codePath);
13674            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13675            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13676            pkg.setApplicationInfoResourcePath(pkg.codePath);
13677            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13678            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13679
13680            return true;
13681        }
13682
13683        private void setMountPath(String mountPath) {
13684            final File mountFile = new File(mountPath);
13685
13686            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13687            if (monolithicFile.exists()) {
13688                packagePath = monolithicFile.getAbsolutePath();
13689                if (isFwdLocked()) {
13690                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13691                } else {
13692                    resourcePath = packagePath;
13693                }
13694            } else {
13695                packagePath = mountFile.getAbsolutePath();
13696                resourcePath = packagePath;
13697            }
13698        }
13699
13700        int doPostInstall(int status, int uid) {
13701            if (status != PackageManager.INSTALL_SUCCEEDED) {
13702                cleanUp();
13703            } else {
13704                final int groupOwner;
13705                final String protectedFile;
13706                if (isFwdLocked()) {
13707                    groupOwner = UserHandle.getSharedAppGid(uid);
13708                    protectedFile = RES_FILE_NAME;
13709                } else {
13710                    groupOwner = -1;
13711                    protectedFile = null;
13712                }
13713
13714                if (uid < Process.FIRST_APPLICATION_UID
13715                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13716                    Slog.e(TAG, "Failed to finalize " + cid);
13717                    PackageHelper.destroySdDir(cid);
13718                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13719                }
13720
13721                boolean mounted = PackageHelper.isContainerMounted(cid);
13722                if (!mounted) {
13723                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13724                }
13725            }
13726            return status;
13727        }
13728
13729        private void cleanUp() {
13730            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13731
13732            // Destroy secure container
13733            PackageHelper.destroySdDir(cid);
13734        }
13735
13736        private List<String> getAllCodePaths() {
13737            final File codeFile = new File(getCodePath());
13738            if (codeFile != null && codeFile.exists()) {
13739                try {
13740                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13741                    return pkg.getAllCodePaths();
13742                } catch (PackageParserException e) {
13743                    // Ignored; we tried our best
13744                }
13745            }
13746            return Collections.EMPTY_LIST;
13747        }
13748
13749        void cleanUpResourcesLI() {
13750            // Enumerate all code paths before deleting
13751            cleanUpResourcesLI(getAllCodePaths());
13752        }
13753
13754        private void cleanUpResourcesLI(List<String> allCodePaths) {
13755            cleanUp();
13756            removeDexFiles(allCodePaths, instructionSets);
13757        }
13758
13759        String getPackageName() {
13760            return getAsecPackageName(cid);
13761        }
13762
13763        boolean doPostDeleteLI(boolean delete) {
13764            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13765            final List<String> allCodePaths = getAllCodePaths();
13766            boolean mounted = PackageHelper.isContainerMounted(cid);
13767            if (mounted) {
13768                // Unmount first
13769                if (PackageHelper.unMountSdDir(cid)) {
13770                    mounted = false;
13771                }
13772            }
13773            if (!mounted && delete) {
13774                cleanUpResourcesLI(allCodePaths);
13775            }
13776            return !mounted;
13777        }
13778
13779        @Override
13780        int doPreCopy() {
13781            if (isFwdLocked()) {
13782                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13783                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13784                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13785                }
13786            }
13787
13788            return PackageManager.INSTALL_SUCCEEDED;
13789        }
13790
13791        @Override
13792        int doPostCopy(int uid) {
13793            if (isFwdLocked()) {
13794                if (uid < Process.FIRST_APPLICATION_UID
13795                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13796                                RES_FILE_NAME)) {
13797                    Slog.e(TAG, "Failed to finalize " + cid);
13798                    PackageHelper.destroySdDir(cid);
13799                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13800                }
13801            }
13802
13803            return PackageManager.INSTALL_SUCCEEDED;
13804        }
13805    }
13806
13807    /**
13808     * Logic to handle movement of existing installed applications.
13809     */
13810    class MoveInstallArgs extends InstallArgs {
13811        private File codeFile;
13812        private File resourceFile;
13813
13814        /** New install */
13815        MoveInstallArgs(InstallParams params) {
13816            super(params.origin, params.move, params.observer, params.installFlags,
13817                    params.installerPackageName, params.volumeUuid,
13818                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13819                    params.grantedRuntimePermissions,
13820                    params.traceMethod, params.traceCookie, params.certificates);
13821        }
13822
13823        int copyApk(IMediaContainerService imcs, boolean temp) {
13824            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13825                    + move.fromUuid + " to " + move.toUuid);
13826            synchronized (mInstaller) {
13827                try {
13828                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13829                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13830                } catch (InstallerException e) {
13831                    Slog.w(TAG, "Failed to move app", e);
13832                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13833                }
13834            }
13835
13836            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13837            resourceFile = codeFile;
13838            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13839
13840            return PackageManager.INSTALL_SUCCEEDED;
13841        }
13842
13843        int doPreInstall(int status) {
13844            if (status != PackageManager.INSTALL_SUCCEEDED) {
13845                cleanUp(move.toUuid);
13846            }
13847            return status;
13848        }
13849
13850        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13851            if (status != PackageManager.INSTALL_SUCCEEDED) {
13852                cleanUp(move.toUuid);
13853                return false;
13854            }
13855
13856            // Reflect the move in app info
13857            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13858            pkg.setApplicationInfoCodePath(pkg.codePath);
13859            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13860            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13861            pkg.setApplicationInfoResourcePath(pkg.codePath);
13862            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13863            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13864
13865            return true;
13866        }
13867
13868        int doPostInstall(int status, int uid) {
13869            if (status == PackageManager.INSTALL_SUCCEEDED) {
13870                cleanUp(move.fromUuid);
13871            } else {
13872                cleanUp(move.toUuid);
13873            }
13874            return status;
13875        }
13876
13877        @Override
13878        String getCodePath() {
13879            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13880        }
13881
13882        @Override
13883        String getResourcePath() {
13884            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13885        }
13886
13887        private boolean cleanUp(String volumeUuid) {
13888            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13889                    move.dataAppName);
13890            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13891            final int[] userIds = sUserManager.getUserIds();
13892            synchronized (mInstallLock) {
13893                // Clean up both app data and code
13894                // All package moves are frozen until finished
13895                for (int userId : userIds) {
13896                    try {
13897                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13898                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13899                    } catch (InstallerException e) {
13900                        Slog.w(TAG, String.valueOf(e));
13901                    }
13902                }
13903                removeCodePathLI(codeFile);
13904            }
13905            return true;
13906        }
13907
13908        void cleanUpResourcesLI() {
13909            throw new UnsupportedOperationException();
13910        }
13911
13912        boolean doPostDeleteLI(boolean delete) {
13913            throw new UnsupportedOperationException();
13914        }
13915    }
13916
13917    static String getAsecPackageName(String packageCid) {
13918        int idx = packageCid.lastIndexOf("-");
13919        if (idx == -1) {
13920            return packageCid;
13921        }
13922        return packageCid.substring(0, idx);
13923    }
13924
13925    // Utility method used to create code paths based on package name and available index.
13926    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13927        String idxStr = "";
13928        int idx = 1;
13929        // Fall back to default value of idx=1 if prefix is not
13930        // part of oldCodePath
13931        if (oldCodePath != null) {
13932            String subStr = oldCodePath;
13933            // Drop the suffix right away
13934            if (suffix != null && subStr.endsWith(suffix)) {
13935                subStr = subStr.substring(0, subStr.length() - suffix.length());
13936            }
13937            // If oldCodePath already contains prefix find out the
13938            // ending index to either increment or decrement.
13939            int sidx = subStr.lastIndexOf(prefix);
13940            if (sidx != -1) {
13941                subStr = subStr.substring(sidx + prefix.length());
13942                if (subStr != null) {
13943                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13944                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13945                    }
13946                    try {
13947                        idx = Integer.parseInt(subStr);
13948                        if (idx <= 1) {
13949                            idx++;
13950                        } else {
13951                            idx--;
13952                        }
13953                    } catch(NumberFormatException e) {
13954                    }
13955                }
13956            }
13957        }
13958        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13959        return prefix + idxStr;
13960    }
13961
13962    private File getNextCodePath(File targetDir, String packageName) {
13963        int suffix = 1;
13964        File result;
13965        do {
13966            result = new File(targetDir, packageName + "-" + suffix);
13967            suffix++;
13968        } while (result.exists());
13969        return result;
13970    }
13971
13972    // Utility method that returns the relative package path with respect
13973    // to the installation directory. Like say for /data/data/com.test-1.apk
13974    // string com.test-1 is returned.
13975    static String deriveCodePathName(String codePath) {
13976        if (codePath == null) {
13977            return null;
13978        }
13979        final File codeFile = new File(codePath);
13980        final String name = codeFile.getName();
13981        if (codeFile.isDirectory()) {
13982            return name;
13983        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13984            final int lastDot = name.lastIndexOf('.');
13985            return name.substring(0, lastDot);
13986        } else {
13987            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13988            return null;
13989        }
13990    }
13991
13992    static class PackageInstalledInfo {
13993        String name;
13994        int uid;
13995        // The set of users that originally had this package installed.
13996        int[] origUsers;
13997        // The set of users that now have this package installed.
13998        int[] newUsers;
13999        PackageParser.Package pkg;
14000        int returnCode;
14001        String returnMsg;
14002        PackageRemovedInfo removedInfo;
14003        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14004
14005        public void setError(int code, String msg) {
14006            setReturnCode(code);
14007            setReturnMessage(msg);
14008            Slog.w(TAG, msg);
14009        }
14010
14011        public void setError(String msg, PackageParserException e) {
14012            setReturnCode(e.error);
14013            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14014            Slog.w(TAG, msg, e);
14015        }
14016
14017        public void setError(String msg, PackageManagerException e) {
14018            returnCode = e.error;
14019            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14020            Slog.w(TAG, msg, e);
14021        }
14022
14023        public void setReturnCode(int returnCode) {
14024            this.returnCode = returnCode;
14025            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14026            for (int i = 0; i < childCount; i++) {
14027                addedChildPackages.valueAt(i).returnCode = returnCode;
14028            }
14029        }
14030
14031        private void setReturnMessage(String returnMsg) {
14032            this.returnMsg = returnMsg;
14033            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14034            for (int i = 0; i < childCount; i++) {
14035                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14036            }
14037        }
14038
14039        // In some error cases we want to convey more info back to the observer
14040        String origPackage;
14041        String origPermission;
14042    }
14043
14044    /*
14045     * Install a non-existing package.
14046     */
14047    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14048            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14049            PackageInstalledInfo res) {
14050        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14051
14052        // Remember this for later, in case we need to rollback this install
14053        String pkgName = pkg.packageName;
14054
14055        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14056
14057        synchronized(mPackages) {
14058            final String renamedPackage = mSettings.getRenamedPackage(pkgName);
14059            if (renamedPackage != null) {
14060                // A package with the same name is already installed, though
14061                // it has been renamed to an older name.  The package we
14062                // are trying to install should be installed as an update to
14063                // the existing one, but that has not been requested, so bail.
14064                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14065                        + " without first uninstalling package running as "
14066                        + renamedPackage);
14067                return;
14068            }
14069            if (mPackages.containsKey(pkgName)) {
14070                // Don't allow installation over an existing package with the same name.
14071                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14072                        + " without first uninstalling.");
14073                return;
14074            }
14075        }
14076
14077        try {
14078            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14079                    System.currentTimeMillis(), user);
14080
14081            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14082
14083            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14084                prepareAppDataAfterInstallLIF(newPackage);
14085
14086            } else {
14087                // Remove package from internal structures, but keep around any
14088                // data that might have already existed
14089                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14090                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14091            }
14092        } catch (PackageManagerException e) {
14093            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14094        }
14095
14096        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14097    }
14098
14099    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14100        // Can't rotate keys during boot or if sharedUser.
14101        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14102                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14103            return false;
14104        }
14105        // app is using upgradeKeySets; make sure all are valid
14106        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14107        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14108        for (int i = 0; i < upgradeKeySets.length; i++) {
14109            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14110                Slog.wtf(TAG, "Package "
14111                         + (oldPs.name != null ? oldPs.name : "<null>")
14112                         + " contains upgrade-key-set reference to unknown key-set: "
14113                         + upgradeKeySets[i]
14114                         + " reverting to signatures check.");
14115                return false;
14116            }
14117        }
14118        return true;
14119    }
14120
14121    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14122        // Upgrade keysets are being used.  Determine if new package has a superset of the
14123        // required keys.
14124        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14125        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14126        for (int i = 0; i < upgradeKeySets.length; i++) {
14127            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14128            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14129                return true;
14130            }
14131        }
14132        return false;
14133    }
14134
14135    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14136        try (DigestInputStream digestStream =
14137                new DigestInputStream(new FileInputStream(file), digest)) {
14138            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14139        }
14140    }
14141
14142    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14143            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14144        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14145
14146        final PackageParser.Package oldPackage;
14147        final String pkgName = pkg.packageName;
14148        final int[] allUsers;
14149        final int[] installedUsers;
14150
14151        synchronized(mPackages) {
14152            oldPackage = mPackages.get(pkgName);
14153            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14154
14155            // don't allow upgrade to target a release SDK from a pre-release SDK
14156            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14157                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14158            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14159                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14160            if (oldTargetsPreRelease
14161                    && !newTargetsPreRelease
14162                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14163                Slog.w(TAG, "Can't install package targeting released sdk");
14164                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14165                return;
14166            }
14167
14168            // don't allow an upgrade from full to ephemeral
14169            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14170            if (isEphemeral && !oldIsEphemeral) {
14171                // can't downgrade from full to ephemeral
14172                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14173                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14174                return;
14175            }
14176
14177            // verify signatures are valid
14178            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14179            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14180                if (!checkUpgradeKeySetLP(ps, pkg)) {
14181                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14182                            "New package not signed by keys specified by upgrade-keysets: "
14183                                    + pkgName);
14184                    return;
14185                }
14186            } else {
14187                // default to original signature matching
14188                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14189                        != PackageManager.SIGNATURE_MATCH) {
14190                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14191                            "New package has a different signature: " + pkgName);
14192                    return;
14193                }
14194            }
14195
14196            // don't allow a system upgrade unless the upgrade hash matches
14197            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14198                byte[] digestBytes = null;
14199                try {
14200                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14201                    updateDigest(digest, new File(pkg.baseCodePath));
14202                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14203                        for (String path : pkg.splitCodePaths) {
14204                            updateDigest(digest, new File(path));
14205                        }
14206                    }
14207                    digestBytes = digest.digest();
14208                } catch (NoSuchAlgorithmException | IOException e) {
14209                    res.setError(INSTALL_FAILED_INVALID_APK,
14210                            "Could not compute hash: " + pkgName);
14211                    return;
14212                }
14213                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14214                    res.setError(INSTALL_FAILED_INVALID_APK,
14215                            "New package fails restrict-update check: " + pkgName);
14216                    return;
14217                }
14218                // retain upgrade restriction
14219                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14220            }
14221
14222            // Check for shared user id changes
14223            String invalidPackageName =
14224                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14225            if (invalidPackageName != null) {
14226                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14227                        "Package " + invalidPackageName + " tried to change user "
14228                                + oldPackage.mSharedUserId);
14229                return;
14230            }
14231
14232            // In case of rollback, remember per-user/profile install state
14233            allUsers = sUserManager.getUserIds();
14234            installedUsers = ps.queryInstalledUsers(allUsers, true);
14235        }
14236
14237        // Update what is removed
14238        res.removedInfo = new PackageRemovedInfo();
14239        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14240        res.removedInfo.removedPackage = oldPackage.packageName;
14241        res.removedInfo.isUpdate = true;
14242        res.removedInfo.origUsers = installedUsers;
14243        final int childCount = (oldPackage.childPackages != null)
14244                ? oldPackage.childPackages.size() : 0;
14245        for (int i = 0; i < childCount; i++) {
14246            boolean childPackageUpdated = false;
14247            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14248            if (res.addedChildPackages != null) {
14249                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14250                if (childRes != null) {
14251                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14252                    childRes.removedInfo.removedPackage = childPkg.packageName;
14253                    childRes.removedInfo.isUpdate = true;
14254                    childPackageUpdated = true;
14255                }
14256            }
14257            if (!childPackageUpdated) {
14258                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14259                childRemovedRes.removedPackage = childPkg.packageName;
14260                childRemovedRes.isUpdate = false;
14261                childRemovedRes.dataRemoved = true;
14262                synchronized (mPackages) {
14263                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14264                    if (childPs != null) {
14265                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14266                    }
14267                }
14268                if (res.removedInfo.removedChildPackages == null) {
14269                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14270                }
14271                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14272            }
14273        }
14274
14275        boolean sysPkg = (isSystemApp(oldPackage));
14276        if (sysPkg) {
14277            // Set the system/privileged flags as needed
14278            final boolean privileged =
14279                    (oldPackage.applicationInfo.privateFlags
14280                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14281            final int systemPolicyFlags = policyFlags
14282                    | PackageParser.PARSE_IS_SYSTEM
14283                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14284
14285            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14286                    user, allUsers, installerPackageName, res);
14287        } else {
14288            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14289                    user, allUsers, installerPackageName, res);
14290        }
14291    }
14292
14293    public List<String> getPreviousCodePaths(String packageName) {
14294        final PackageSetting ps = mSettings.mPackages.get(packageName);
14295        final List<String> result = new ArrayList<String>();
14296        if (ps != null && ps.oldCodePaths != null) {
14297            result.addAll(ps.oldCodePaths);
14298        }
14299        return result;
14300    }
14301
14302    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14303            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14304            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14305        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14306                + deletedPackage);
14307
14308        String pkgName = deletedPackage.packageName;
14309        boolean deletedPkg = true;
14310        boolean addedPkg = false;
14311        boolean updatedSettings = false;
14312        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14313        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14314                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14315
14316        final long origUpdateTime = (pkg.mExtras != null)
14317                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14318
14319        // First delete the existing package while retaining the data directory
14320        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14321                res.removedInfo, true, pkg)) {
14322            // If the existing package wasn't successfully deleted
14323            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14324            deletedPkg = false;
14325        } else {
14326            // Successfully deleted the old package; proceed with replace.
14327
14328            // If deleted package lived in a container, give users a chance to
14329            // relinquish resources before killing.
14330            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14331                if (DEBUG_INSTALL) {
14332                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14333                }
14334                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14335                final ArrayList<String> pkgList = new ArrayList<String>(1);
14336                pkgList.add(deletedPackage.applicationInfo.packageName);
14337                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14338            }
14339
14340            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14341                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14342            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14343
14344            try {
14345                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14346                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14347                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14348
14349                // Update the in-memory copy of the previous code paths.
14350                PackageSetting ps = mSettings.mPackages.get(pkgName);
14351                if (!killApp) {
14352                    if (ps.oldCodePaths == null) {
14353                        ps.oldCodePaths = new ArraySet<>();
14354                    }
14355                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14356                    if (deletedPackage.splitCodePaths != null) {
14357                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14358                    }
14359                } else {
14360                    ps.oldCodePaths = null;
14361                }
14362                if (ps.childPackageNames != null) {
14363                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14364                        final String childPkgName = ps.childPackageNames.get(i);
14365                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14366                        childPs.oldCodePaths = ps.oldCodePaths;
14367                    }
14368                }
14369                prepareAppDataAfterInstallLIF(newPackage);
14370                addedPkg = true;
14371            } catch (PackageManagerException e) {
14372                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14373            }
14374        }
14375
14376        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14377            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14378
14379            // Revert all internal state mutations and added folders for the failed install
14380            if (addedPkg) {
14381                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14382                        res.removedInfo, true, null);
14383            }
14384
14385            // Restore the old package
14386            if (deletedPkg) {
14387                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14388                File restoreFile = new File(deletedPackage.codePath);
14389                // Parse old package
14390                boolean oldExternal = isExternal(deletedPackage);
14391                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14392                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14393                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14394                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14395                try {
14396                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14397                            null);
14398                } catch (PackageManagerException e) {
14399                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14400                            + e.getMessage());
14401                    return;
14402                }
14403
14404                synchronized (mPackages) {
14405                    // Ensure the installer package name up to date
14406                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14407
14408                    // Update permissions for restored package
14409                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14410
14411                    mSettings.writeLPr();
14412                }
14413
14414                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14415            }
14416        } else {
14417            synchronized (mPackages) {
14418                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14419                if (ps != null) {
14420                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14421                    if (res.removedInfo.removedChildPackages != null) {
14422                        final int childCount = res.removedInfo.removedChildPackages.size();
14423                        // Iterate in reverse as we may modify the collection
14424                        for (int i = childCount - 1; i >= 0; i--) {
14425                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14426                            if (res.addedChildPackages.containsKey(childPackageName)) {
14427                                res.removedInfo.removedChildPackages.removeAt(i);
14428                            } else {
14429                                PackageRemovedInfo childInfo = res.removedInfo
14430                                        .removedChildPackages.valueAt(i);
14431                                childInfo.removedForAllUsers = mPackages.get(
14432                                        childInfo.removedPackage) == null;
14433                            }
14434                        }
14435                    }
14436                }
14437            }
14438        }
14439    }
14440
14441    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14442            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14443            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14444        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14445                + ", old=" + deletedPackage);
14446
14447        final boolean disabledSystem;
14448
14449        // Remove existing system package
14450        removePackageLI(deletedPackage, true);
14451
14452        synchronized (mPackages) {
14453            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14454        }
14455        if (!disabledSystem) {
14456            // We didn't need to disable the .apk as a current system package,
14457            // which means we are replacing another update that is already
14458            // installed.  We need to make sure to delete the older one's .apk.
14459            res.removedInfo.args = createInstallArgsForExisting(0,
14460                    deletedPackage.applicationInfo.getCodePath(),
14461                    deletedPackage.applicationInfo.getResourcePath(),
14462                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14463        } else {
14464            res.removedInfo.args = null;
14465        }
14466
14467        // Successfully disabled the old package. Now proceed with re-installation
14468        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14469                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14470        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14471
14472        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14473        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14474                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14475
14476        PackageParser.Package newPackage = null;
14477        try {
14478            // Add the package to the internal data structures
14479            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14480
14481            // Set the update and install times
14482            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14483            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14484                    System.currentTimeMillis());
14485
14486            // Update the package dynamic state if succeeded
14487            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14488                // Now that the install succeeded make sure we remove data
14489                // directories for any child package the update removed.
14490                final int deletedChildCount = (deletedPackage.childPackages != null)
14491                        ? deletedPackage.childPackages.size() : 0;
14492                final int newChildCount = (newPackage.childPackages != null)
14493                        ? newPackage.childPackages.size() : 0;
14494                for (int i = 0; i < deletedChildCount; i++) {
14495                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14496                    boolean childPackageDeleted = true;
14497                    for (int j = 0; j < newChildCount; j++) {
14498                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14499                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14500                            childPackageDeleted = false;
14501                            break;
14502                        }
14503                    }
14504                    if (childPackageDeleted) {
14505                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14506                                deletedChildPkg.packageName);
14507                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14508                            PackageRemovedInfo removedChildRes = res.removedInfo
14509                                    .removedChildPackages.get(deletedChildPkg.packageName);
14510                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14511                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14512                        }
14513                    }
14514                }
14515
14516                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14517                prepareAppDataAfterInstallLIF(newPackage);
14518            }
14519        } catch (PackageManagerException e) {
14520            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14521            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14522        }
14523
14524        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14525            // Re installation failed. Restore old information
14526            // Remove new pkg information
14527            if (newPackage != null) {
14528                removeInstalledPackageLI(newPackage, true);
14529            }
14530            // Add back the old system package
14531            try {
14532                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14533            } catch (PackageManagerException e) {
14534                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14535            }
14536
14537            synchronized (mPackages) {
14538                if (disabledSystem) {
14539                    enableSystemPackageLPw(deletedPackage);
14540                }
14541
14542                // Ensure the installer package name up to date
14543                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14544
14545                // Update permissions for restored package
14546                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14547
14548                mSettings.writeLPr();
14549            }
14550
14551            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14552                    + " after failed upgrade");
14553        }
14554    }
14555
14556    /**
14557     * Checks whether the parent or any of the child packages have a change shared
14558     * user. For a package to be a valid update the shred users of the parent and
14559     * the children should match. We may later support changing child shared users.
14560     * @param oldPkg The updated package.
14561     * @param newPkg The update package.
14562     * @return The shared user that change between the versions.
14563     */
14564    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14565            PackageParser.Package newPkg) {
14566        // Check parent shared user
14567        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14568            return newPkg.packageName;
14569        }
14570        // Check child shared users
14571        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14572        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14573        for (int i = 0; i < newChildCount; i++) {
14574            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14575            // If this child was present, did it have the same shared user?
14576            for (int j = 0; j < oldChildCount; j++) {
14577                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14578                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14579                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14580                    return newChildPkg.packageName;
14581                }
14582            }
14583        }
14584        return null;
14585    }
14586
14587    private void removeNativeBinariesLI(PackageSetting ps) {
14588        // Remove the lib path for the parent package
14589        if (ps != null) {
14590            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14591            // Remove the lib path for the child packages
14592            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14593            for (int i = 0; i < childCount; i++) {
14594                PackageSetting childPs = null;
14595                synchronized (mPackages) {
14596                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14597                }
14598                if (childPs != null) {
14599                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14600                            .legacyNativeLibraryPathString);
14601                }
14602            }
14603        }
14604    }
14605
14606    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14607        // Enable the parent package
14608        mSettings.enableSystemPackageLPw(pkg.packageName);
14609        // Enable the child packages
14610        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14611        for (int i = 0; i < childCount; i++) {
14612            PackageParser.Package childPkg = pkg.childPackages.get(i);
14613            mSettings.enableSystemPackageLPw(childPkg.packageName);
14614        }
14615    }
14616
14617    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14618            PackageParser.Package newPkg) {
14619        // Disable the parent package (parent always replaced)
14620        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14621        // Disable the child packages
14622        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14623        for (int i = 0; i < childCount; i++) {
14624            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14625            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14626            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14627        }
14628        return disabled;
14629    }
14630
14631    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14632            String installerPackageName) {
14633        // Enable the parent package
14634        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14635        // Enable the child packages
14636        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14637        for (int i = 0; i < childCount; i++) {
14638            PackageParser.Package childPkg = pkg.childPackages.get(i);
14639            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14640        }
14641    }
14642
14643    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14644        // Collect all used permissions in the UID
14645        ArraySet<String> usedPermissions = new ArraySet<>();
14646        final int packageCount = su.packages.size();
14647        for (int i = 0; i < packageCount; i++) {
14648            PackageSetting ps = su.packages.valueAt(i);
14649            if (ps.pkg == null) {
14650                continue;
14651            }
14652            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14653            for (int j = 0; j < requestedPermCount; j++) {
14654                String permission = ps.pkg.requestedPermissions.get(j);
14655                BasePermission bp = mSettings.mPermissions.get(permission);
14656                if (bp != null) {
14657                    usedPermissions.add(permission);
14658                }
14659            }
14660        }
14661
14662        PermissionsState permissionsState = su.getPermissionsState();
14663        // Prune install permissions
14664        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14665        final int installPermCount = installPermStates.size();
14666        for (int i = installPermCount - 1; i >= 0;  i--) {
14667            PermissionState permissionState = installPermStates.get(i);
14668            if (!usedPermissions.contains(permissionState.getName())) {
14669                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14670                if (bp != null) {
14671                    permissionsState.revokeInstallPermission(bp);
14672                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14673                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14674                }
14675            }
14676        }
14677
14678        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14679
14680        // Prune runtime permissions
14681        for (int userId : allUserIds) {
14682            List<PermissionState> runtimePermStates = permissionsState
14683                    .getRuntimePermissionStates(userId);
14684            final int runtimePermCount = runtimePermStates.size();
14685            for (int i = runtimePermCount - 1; i >= 0; i--) {
14686                PermissionState permissionState = runtimePermStates.get(i);
14687                if (!usedPermissions.contains(permissionState.getName())) {
14688                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14689                    if (bp != null) {
14690                        permissionsState.revokeRuntimePermission(bp, userId);
14691                        permissionsState.updatePermissionFlags(bp, userId,
14692                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14693                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14694                                runtimePermissionChangedUserIds, userId);
14695                    }
14696                }
14697            }
14698        }
14699
14700        return runtimePermissionChangedUserIds;
14701    }
14702
14703    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14704            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14705        // Update the parent package setting
14706        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14707                res, user);
14708        // Update the child packages setting
14709        final int childCount = (newPackage.childPackages != null)
14710                ? newPackage.childPackages.size() : 0;
14711        for (int i = 0; i < childCount; i++) {
14712            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14713            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14714            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14715                    childRes.origUsers, childRes, user);
14716        }
14717    }
14718
14719    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14720            String installerPackageName, int[] allUsers, int[] installedForUsers,
14721            PackageInstalledInfo res, UserHandle user) {
14722        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14723
14724        String pkgName = newPackage.packageName;
14725        synchronized (mPackages) {
14726            //write settings. the installStatus will be incomplete at this stage.
14727            //note that the new package setting would have already been
14728            //added to mPackages. It hasn't been persisted yet.
14729            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14730            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14731            mSettings.writeLPr();
14732            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14733        }
14734
14735        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14736        synchronized (mPackages) {
14737            updatePermissionsLPw(newPackage.packageName, newPackage,
14738                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14739                            ? UPDATE_PERMISSIONS_ALL : 0));
14740            // For system-bundled packages, we assume that installing an upgraded version
14741            // of the package implies that the user actually wants to run that new code,
14742            // so we enable the package.
14743            PackageSetting ps = mSettings.mPackages.get(pkgName);
14744            final int userId = user.getIdentifier();
14745            if (ps != null) {
14746                if (isSystemApp(newPackage)) {
14747                    if (DEBUG_INSTALL) {
14748                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14749                    }
14750                    // Enable system package for requested users
14751                    if (res.origUsers != null) {
14752                        for (int origUserId : res.origUsers) {
14753                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14754                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14755                                        origUserId, installerPackageName);
14756                            }
14757                        }
14758                    }
14759                    // Also convey the prior install/uninstall state
14760                    if (allUsers != null && installedForUsers != null) {
14761                        for (int currentUserId : allUsers) {
14762                            final boolean installed = ArrayUtils.contains(
14763                                    installedForUsers, currentUserId);
14764                            if (DEBUG_INSTALL) {
14765                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14766                            }
14767                            ps.setInstalled(installed, currentUserId);
14768                        }
14769                        // these install state changes will be persisted in the
14770                        // upcoming call to mSettings.writeLPr().
14771                    }
14772                }
14773                // It's implied that when a user requests installation, they want the app to be
14774                // installed and enabled.
14775                if (userId != UserHandle.USER_ALL) {
14776                    ps.setInstalled(true, userId);
14777                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14778                }
14779            }
14780            res.name = pkgName;
14781            res.uid = newPackage.applicationInfo.uid;
14782            res.pkg = newPackage;
14783            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14784            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14785            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14786            //to update install status
14787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14788            mSettings.writeLPr();
14789            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14790        }
14791
14792        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14793    }
14794
14795    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14796        try {
14797            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14798            installPackageLI(args, res);
14799        } finally {
14800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14801        }
14802    }
14803
14804    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14805        final int installFlags = args.installFlags;
14806        final String installerPackageName = args.installerPackageName;
14807        final String volumeUuid = args.volumeUuid;
14808        final File tmpPackageFile = new File(args.getCodePath());
14809        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14810        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14811                || (args.volumeUuid != null));
14812        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14813        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14814        boolean replace = false;
14815        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14816        if (args.move != null) {
14817            // moving a complete application; perform an initial scan on the new install location
14818            scanFlags |= SCAN_INITIAL;
14819        }
14820        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14821            scanFlags |= SCAN_DONT_KILL_APP;
14822        }
14823
14824        // Result object to be returned
14825        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14826
14827        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14828
14829        // Sanity check
14830        if (ephemeral && (forwardLocked || onExternal)) {
14831            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14832                    + " external=" + onExternal);
14833            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14834            return;
14835        }
14836
14837        // Retrieve PackageSettings and parse package
14838        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14839                | PackageParser.PARSE_ENFORCE_CODE
14840                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14841                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14842                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14843                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14844        PackageParser pp = new PackageParser();
14845        pp.setSeparateProcesses(mSeparateProcesses);
14846        pp.setDisplayMetrics(mMetrics);
14847
14848        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14849        final PackageParser.Package pkg;
14850        try {
14851            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14852        } catch (PackageParserException e) {
14853            res.setError("Failed parse during installPackageLI", e);
14854            return;
14855        } finally {
14856            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14857        }
14858
14859        // If we are installing a clustered package add results for the children
14860        if (pkg.childPackages != null) {
14861            synchronized (mPackages) {
14862                final int childCount = pkg.childPackages.size();
14863                for (int i = 0; i < childCount; i++) {
14864                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14865                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14866                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14867                    childRes.pkg = childPkg;
14868                    childRes.name = childPkg.packageName;
14869                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14870                    if (childPs != null) {
14871                        childRes.origUsers = childPs.queryInstalledUsers(
14872                                sUserManager.getUserIds(), true);
14873                    }
14874                    if ((mPackages.containsKey(childPkg.packageName))) {
14875                        childRes.removedInfo = new PackageRemovedInfo();
14876                        childRes.removedInfo.removedPackage = childPkg.packageName;
14877                    }
14878                    if (res.addedChildPackages == null) {
14879                        res.addedChildPackages = new ArrayMap<>();
14880                    }
14881                    res.addedChildPackages.put(childPkg.packageName, childRes);
14882                }
14883            }
14884        }
14885
14886        // If package doesn't declare API override, mark that we have an install
14887        // time CPU ABI override.
14888        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14889            pkg.cpuAbiOverride = args.abiOverride;
14890        }
14891
14892        String pkgName = res.name = pkg.packageName;
14893        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14894            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14895                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14896                return;
14897            }
14898        }
14899
14900        try {
14901            // either use what we've been given or parse directly from the APK
14902            if (args.certificates != null) {
14903                try {
14904                    PackageParser.populateCertificates(pkg, args.certificates);
14905                } catch (PackageParserException e) {
14906                    // there was something wrong with the certificates we were given;
14907                    // try to pull them from the APK
14908                    PackageParser.collectCertificates(pkg, parseFlags);
14909                }
14910            } else {
14911                PackageParser.collectCertificates(pkg, parseFlags);
14912            }
14913        } catch (PackageParserException e) {
14914            res.setError("Failed collect during installPackageLI", e);
14915            return;
14916        }
14917
14918        // Get rid of all references to package scan path via parser.
14919        pp = null;
14920        String oldCodePath = null;
14921        boolean systemApp = false;
14922        synchronized (mPackages) {
14923            // Check if installing already existing package
14924            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14925                String oldName = mSettings.getRenamedPackage(pkgName);
14926                if (pkg.mOriginalPackages != null
14927                        && pkg.mOriginalPackages.contains(oldName)
14928                        && mPackages.containsKey(oldName)) {
14929                    // This package is derived from an original package,
14930                    // and this device has been updating from that original
14931                    // name.  We must continue using the original name, so
14932                    // rename the new package here.
14933                    pkg.setPackageName(oldName);
14934                    pkgName = pkg.packageName;
14935                    replace = true;
14936                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14937                            + oldName + " pkgName=" + pkgName);
14938                } else if (mPackages.containsKey(pkgName)) {
14939                    // This package, under its official name, already exists
14940                    // on the device; we should replace it.
14941                    replace = true;
14942                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14943                }
14944
14945                // Child packages are installed through the parent package
14946                if (pkg.parentPackage != null) {
14947                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14948                            "Package " + pkg.packageName + " is child of package "
14949                                    + pkg.parentPackage.parentPackage + ". Child packages "
14950                                    + "can be updated only through the parent package.");
14951                    return;
14952                }
14953
14954                if (replace) {
14955                    // Prevent apps opting out from runtime permissions
14956                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14957                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14958                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14959                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14960                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14961                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14962                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14963                                        + " doesn't support runtime permissions but the old"
14964                                        + " target SDK " + oldTargetSdk + " does.");
14965                        return;
14966                    }
14967
14968                    // Prevent installing of child packages
14969                    if (oldPackage.parentPackage != null) {
14970                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14971                                "Package " + pkg.packageName + " is child of package "
14972                                        + oldPackage.parentPackage + ". Child packages "
14973                                        + "can be updated only through the parent package.");
14974                        return;
14975                    }
14976                }
14977            }
14978
14979            PackageSetting ps = mSettings.mPackages.get(pkgName);
14980            if (ps != null) {
14981                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14982
14983                // Quick sanity check that we're signed correctly if updating;
14984                // we'll check this again later when scanning, but we want to
14985                // bail early here before tripping over redefined permissions.
14986                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14987                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14988                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14989                                + pkg.packageName + " upgrade keys do not match the "
14990                                + "previously installed version");
14991                        return;
14992                    }
14993                } else {
14994                    try {
14995                        verifySignaturesLP(ps, pkg);
14996                    } catch (PackageManagerException e) {
14997                        res.setError(e.error, e.getMessage());
14998                        return;
14999                    }
15000                }
15001
15002                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15003                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15004                    systemApp = (ps.pkg.applicationInfo.flags &
15005                            ApplicationInfo.FLAG_SYSTEM) != 0;
15006                }
15007                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15008            }
15009
15010            // Check whether the newly-scanned package wants to define an already-defined perm
15011            int N = pkg.permissions.size();
15012            for (int i = N-1; i >= 0; i--) {
15013                PackageParser.Permission perm = pkg.permissions.get(i);
15014                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15015                if (bp != null) {
15016                    // If the defining package is signed with our cert, it's okay.  This
15017                    // also includes the "updating the same package" case, of course.
15018                    // "updating same package" could also involve key-rotation.
15019                    final boolean sigsOk;
15020                    if (bp.sourcePackage.equals(pkg.packageName)
15021                            && (bp.packageSetting instanceof PackageSetting)
15022                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15023                                    scanFlags))) {
15024                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15025                    } else {
15026                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15027                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15028                    }
15029                    if (!sigsOk) {
15030                        // If the owning package is the system itself, we log but allow
15031                        // install to proceed; we fail the install on all other permission
15032                        // redefinitions.
15033                        if (!bp.sourcePackage.equals("android")) {
15034                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15035                                    + pkg.packageName + " attempting to redeclare permission "
15036                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15037                            res.origPermission = perm.info.name;
15038                            res.origPackage = bp.sourcePackage;
15039                            return;
15040                        } else {
15041                            Slog.w(TAG, "Package " + pkg.packageName
15042                                    + " attempting to redeclare system permission "
15043                                    + perm.info.name + "; ignoring new declaration");
15044                            pkg.permissions.remove(i);
15045                        }
15046                    }
15047                }
15048            }
15049        }
15050
15051        if (systemApp) {
15052            if (onExternal) {
15053                // Abort update; system app can't be replaced with app on sdcard
15054                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15055                        "Cannot install updates to system apps on sdcard");
15056                return;
15057            } else if (ephemeral) {
15058                // Abort update; system app can't be replaced with an ephemeral app
15059                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15060                        "Cannot update a system app with an ephemeral app");
15061                return;
15062            }
15063        }
15064
15065        if (args.move != null) {
15066            // We did an in-place move, so dex is ready to roll
15067            scanFlags |= SCAN_NO_DEX;
15068            scanFlags |= SCAN_MOVE;
15069
15070            synchronized (mPackages) {
15071                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15072                if (ps == null) {
15073                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15074                            "Missing settings for moved package " + pkgName);
15075                }
15076
15077                // We moved the entire application as-is, so bring over the
15078                // previously derived ABI information.
15079                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15080                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15081            }
15082
15083        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15084            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15085            scanFlags |= SCAN_NO_DEX;
15086
15087            try {
15088                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15089                    args.abiOverride : pkg.cpuAbiOverride);
15090                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15091                        true /* extract libs */);
15092            } catch (PackageManagerException pme) {
15093                Slog.e(TAG, "Error deriving application ABI", pme);
15094                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15095                return;
15096            }
15097
15098            // Shared libraries for the package need to be updated.
15099            synchronized (mPackages) {
15100                try {
15101                    updateSharedLibrariesLPw(pkg, null);
15102                } catch (PackageManagerException e) {
15103                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15104                }
15105            }
15106            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15107            // Do not run PackageDexOptimizer through the local performDexOpt
15108            // method because `pkg` may not be in `mPackages` yet.
15109            //
15110            // Also, don't fail application installs if the dexopt step fails.
15111            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15112                    null /* instructionSets */, false /* checkProfiles */,
15113                    getCompilerFilterForReason(REASON_INSTALL),
15114                    getOrCreateCompilerPackageStats(pkg));
15115            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15116
15117            // Notify BackgroundDexOptService that the package has been changed.
15118            // If this is an update of a package which used to fail to compile,
15119            // BDOS will remove it from its blacklist.
15120            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15121        }
15122
15123        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15124            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15125            return;
15126        }
15127
15128        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15129
15130        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15131                "installPackageLI")) {
15132            if (replace) {
15133                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15134                        installerPackageName, res);
15135            } else {
15136                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15137                        args.user, installerPackageName, volumeUuid, res);
15138            }
15139        }
15140        synchronized (mPackages) {
15141            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15142            if (ps != null) {
15143                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15144            }
15145
15146            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15147            for (int i = 0; i < childCount; i++) {
15148                PackageParser.Package childPkg = pkg.childPackages.get(i);
15149                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15150                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15151                if (childPs != null) {
15152                    childRes.newUsers = childPs.queryInstalledUsers(
15153                            sUserManager.getUserIds(), true);
15154                }
15155            }
15156        }
15157    }
15158
15159    private void startIntentFilterVerifications(int userId, boolean replacing,
15160            PackageParser.Package pkg) {
15161        if (mIntentFilterVerifierComponent == null) {
15162            Slog.w(TAG, "No IntentFilter verification will not be done as "
15163                    + "there is no IntentFilterVerifier available!");
15164            return;
15165        }
15166
15167        final int verifierUid = getPackageUid(
15168                mIntentFilterVerifierComponent.getPackageName(),
15169                MATCH_DEBUG_TRIAGED_MISSING,
15170                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15171
15172        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15173        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15174        mHandler.sendMessage(msg);
15175
15176        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15177        for (int i = 0; i < childCount; i++) {
15178            PackageParser.Package childPkg = pkg.childPackages.get(i);
15179            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15180            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15181            mHandler.sendMessage(msg);
15182        }
15183    }
15184
15185    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15186            PackageParser.Package pkg) {
15187        int size = pkg.activities.size();
15188        if (size == 0) {
15189            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15190                    "No activity, so no need to verify any IntentFilter!");
15191            return;
15192        }
15193
15194        final boolean hasDomainURLs = hasDomainURLs(pkg);
15195        if (!hasDomainURLs) {
15196            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15197                    "No domain URLs, so no need to verify any IntentFilter!");
15198            return;
15199        }
15200
15201        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15202                + " if any IntentFilter from the " + size
15203                + " Activities needs verification ...");
15204
15205        int count = 0;
15206        final String packageName = pkg.packageName;
15207
15208        synchronized (mPackages) {
15209            // If this is a new install and we see that we've already run verification for this
15210            // package, we have nothing to do: it means the state was restored from backup.
15211            if (!replacing) {
15212                IntentFilterVerificationInfo ivi =
15213                        mSettings.getIntentFilterVerificationLPr(packageName);
15214                if (ivi != null) {
15215                    if (DEBUG_DOMAIN_VERIFICATION) {
15216                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15217                                + ivi.getStatusString());
15218                    }
15219                    return;
15220                }
15221            }
15222
15223            // If any filters need to be verified, then all need to be.
15224            boolean needToVerify = false;
15225            for (PackageParser.Activity a : pkg.activities) {
15226                for (ActivityIntentInfo filter : a.intents) {
15227                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15228                        if (DEBUG_DOMAIN_VERIFICATION) {
15229                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15230                        }
15231                        needToVerify = true;
15232                        break;
15233                    }
15234                }
15235            }
15236
15237            if (needToVerify) {
15238                final int verificationId = mIntentFilterVerificationToken++;
15239                for (PackageParser.Activity a : pkg.activities) {
15240                    for (ActivityIntentInfo filter : a.intents) {
15241                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15242                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15243                                    "Verification needed for IntentFilter:" + filter.toString());
15244                            mIntentFilterVerifier.addOneIntentFilterVerification(
15245                                    verifierUid, userId, verificationId, filter, packageName);
15246                            count++;
15247                        }
15248                    }
15249                }
15250            }
15251        }
15252
15253        if (count > 0) {
15254            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15255                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15256                    +  " for userId:" + userId);
15257            mIntentFilterVerifier.startVerifications(userId);
15258        } else {
15259            if (DEBUG_DOMAIN_VERIFICATION) {
15260                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15261            }
15262        }
15263    }
15264
15265    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15266        final ComponentName cn  = filter.activity.getComponentName();
15267        final String packageName = cn.getPackageName();
15268
15269        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15270                packageName);
15271        if (ivi == null) {
15272            return true;
15273        }
15274        int status = ivi.getStatus();
15275        switch (status) {
15276            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15277            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15278                return true;
15279
15280            default:
15281                // Nothing to do
15282                return false;
15283        }
15284    }
15285
15286    private static boolean isMultiArch(ApplicationInfo info) {
15287        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15288    }
15289
15290    private static boolean isExternal(PackageParser.Package pkg) {
15291        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15292    }
15293
15294    private static boolean isExternal(PackageSetting ps) {
15295        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15296    }
15297
15298    private static boolean isEphemeral(PackageParser.Package pkg) {
15299        return pkg.applicationInfo.isEphemeralApp();
15300    }
15301
15302    private static boolean isEphemeral(PackageSetting ps) {
15303        return ps.pkg != null && isEphemeral(ps.pkg);
15304    }
15305
15306    private static boolean isSystemApp(PackageParser.Package pkg) {
15307        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15308    }
15309
15310    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15311        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15312    }
15313
15314    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15315        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15316    }
15317
15318    private static boolean isSystemApp(PackageSetting ps) {
15319        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15320    }
15321
15322    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15323        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15324    }
15325
15326    private int packageFlagsToInstallFlags(PackageSetting ps) {
15327        int installFlags = 0;
15328        if (isEphemeral(ps)) {
15329            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15330        }
15331        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15332            // This existing package was an external ASEC install when we have
15333            // the external flag without a UUID
15334            installFlags |= PackageManager.INSTALL_EXTERNAL;
15335        }
15336        if (ps.isForwardLocked()) {
15337            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15338        }
15339        return installFlags;
15340    }
15341
15342    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15343        if (isExternal(pkg)) {
15344            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15345                return StorageManager.UUID_PRIMARY_PHYSICAL;
15346            } else {
15347                return pkg.volumeUuid;
15348            }
15349        } else {
15350            return StorageManager.UUID_PRIVATE_INTERNAL;
15351        }
15352    }
15353
15354    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15355        if (isExternal(pkg)) {
15356            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15357                return mSettings.getExternalVersion();
15358            } else {
15359                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15360            }
15361        } else {
15362            return mSettings.getInternalVersion();
15363        }
15364    }
15365
15366    private void deleteTempPackageFiles() {
15367        final FilenameFilter filter = new FilenameFilter() {
15368            public boolean accept(File dir, String name) {
15369                return name.startsWith("vmdl") && name.endsWith(".tmp");
15370            }
15371        };
15372        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15373            file.delete();
15374        }
15375    }
15376
15377    @Override
15378    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15379            int flags) {
15380        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15381                flags);
15382    }
15383
15384    @Override
15385    public void deletePackage(final String packageName,
15386            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15387        mContext.enforceCallingOrSelfPermission(
15388                android.Manifest.permission.DELETE_PACKAGES, null);
15389        Preconditions.checkNotNull(packageName);
15390        Preconditions.checkNotNull(observer);
15391        final int uid = Binder.getCallingUid();
15392        if (uid != Process.SHELL_UID && uid != Process.ROOT_UID && uid != Process.SYSTEM_UID
15393                && uid != getPackageUid(mRequiredInstallerPackage, 0, UserHandle.getUserId(uid))
15394                && uid != getPackageUid(mStorageManagerPackage, 0, UserHandle.getUserId(uid))
15395                && !isOrphaned(packageName)
15396                && !isCallerSameAsInstaller(uid, packageName)) {
15397            try {
15398                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15399                intent.setData(Uri.fromParts("package", packageName, null));
15400                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15401                observer.onUserActionRequired(intent);
15402            } catch (RemoteException re) {
15403            }
15404            return;
15405        }
15406        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15407        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15408        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15409            mContext.enforceCallingOrSelfPermission(
15410                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15411                    "deletePackage for user " + userId);
15412        }
15413
15414        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15415            try {
15416                observer.onPackageDeleted(packageName,
15417                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15418            } catch (RemoteException re) {
15419            }
15420            return;
15421        }
15422
15423        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15424            try {
15425                observer.onPackageDeleted(packageName,
15426                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15427            } catch (RemoteException re) {
15428            }
15429            return;
15430        }
15431
15432        if (DEBUG_REMOVE) {
15433            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15434                    + " deleteAllUsers: " + deleteAllUsers );
15435        }
15436        // Queue up an async operation since the package deletion may take a little while.
15437        mHandler.post(new Runnable() {
15438            public void run() {
15439                mHandler.removeCallbacks(this);
15440                int returnCode;
15441                if (!deleteAllUsers) {
15442                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15443                } else {
15444                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15445                    // If nobody is blocking uninstall, proceed with delete for all users
15446                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15447                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15448                    } else {
15449                        // Otherwise uninstall individually for users with blockUninstalls=false
15450                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15451                        for (int userId : users) {
15452                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15453                                returnCode = deletePackageX(packageName, userId, userFlags);
15454                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15455                                    Slog.w(TAG, "Package delete failed for user " + userId
15456                                            + ", returnCode " + returnCode);
15457                                }
15458                            }
15459                        }
15460                        // The app has only been marked uninstalled for certain users.
15461                        // We still need to report that delete was blocked
15462                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15463                    }
15464                }
15465                try {
15466                    observer.onPackageDeleted(packageName, returnCode, null);
15467                } catch (RemoteException e) {
15468                    Log.i(TAG, "Observer no longer exists.");
15469                } //end catch
15470            } //end run
15471        });
15472    }
15473
15474    private boolean isCallerSameAsInstaller(int callingUid, String pkgName) {
15475        final int installerPkgUid = getPackageUid(getInstallerPackageName(pkgName),
15476                0 /* flags */, UserHandle.getUserId(callingUid));
15477        return installerPkgUid == callingUid;
15478    }
15479
15480    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15481        int[] result = EMPTY_INT_ARRAY;
15482        for (int userId : userIds) {
15483            if (getBlockUninstallForUser(packageName, userId)) {
15484                result = ArrayUtils.appendInt(result, userId);
15485            }
15486        }
15487        return result;
15488    }
15489
15490    @Override
15491    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15492        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15493    }
15494
15495    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15496        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15497                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15498        try {
15499            if (dpm != null) {
15500                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15501                        /* callingUserOnly =*/ false);
15502                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15503                        : deviceOwnerComponentName.getPackageName();
15504                // Does the package contains the device owner?
15505                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15506                // this check is probably not needed, since DO should be registered as a device
15507                // admin on some user too. (Original bug for this: b/17657954)
15508                if (packageName.equals(deviceOwnerPackageName)) {
15509                    return true;
15510                }
15511                // Does it contain a device admin for any user?
15512                int[] users;
15513                if (userId == UserHandle.USER_ALL) {
15514                    users = sUserManager.getUserIds();
15515                } else {
15516                    users = new int[]{userId};
15517                }
15518                for (int i = 0; i < users.length; ++i) {
15519                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15520                        return true;
15521                    }
15522                }
15523            }
15524        } catch (RemoteException e) {
15525        }
15526        return false;
15527    }
15528
15529    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15530        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15531    }
15532
15533    /**
15534     *  This method is an internal method that could be get invoked either
15535     *  to delete an installed package or to clean up a failed installation.
15536     *  After deleting an installed package, a broadcast is sent to notify any
15537     *  listeners that the package has been removed. For cleaning up a failed
15538     *  installation, the broadcast is not necessary since the package's
15539     *  installation wouldn't have sent the initial broadcast either
15540     *  The key steps in deleting a package are
15541     *  deleting the package information in internal structures like mPackages,
15542     *  deleting the packages base directories through installd
15543     *  updating mSettings to reflect current status
15544     *  persisting settings for later use
15545     *  sending a broadcast if necessary
15546     */
15547    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15548        final PackageRemovedInfo info = new PackageRemovedInfo();
15549        final boolean res;
15550
15551        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15552                ? UserHandle.USER_ALL : userId;
15553
15554        if (isPackageDeviceAdmin(packageName, removeUser)) {
15555            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15556            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15557        }
15558
15559        PackageSetting uninstalledPs = null;
15560
15561        // for the uninstall-updates case and restricted profiles, remember the per-
15562        // user handle installed state
15563        int[] allUsers;
15564        synchronized (mPackages) {
15565            uninstalledPs = mSettings.mPackages.get(packageName);
15566            if (uninstalledPs == null) {
15567                Slog.w(TAG, "Not removing non-existent package " + packageName);
15568                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15569            }
15570            allUsers = sUserManager.getUserIds();
15571            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15572        }
15573
15574        final int freezeUser;
15575        if (isUpdatedSystemApp(uninstalledPs)
15576                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15577            // We're downgrading a system app, which will apply to all users, so
15578            // freeze them all during the downgrade
15579            freezeUser = UserHandle.USER_ALL;
15580        } else {
15581            freezeUser = removeUser;
15582        }
15583
15584        synchronized (mInstallLock) {
15585            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15586            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15587                    deleteFlags, "deletePackageX")) {
15588                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15589                        deleteFlags | REMOVE_CHATTY, info, true, null);
15590            }
15591            synchronized (mPackages) {
15592                if (res) {
15593                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15594                }
15595            }
15596        }
15597
15598        if (res) {
15599            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15600            info.sendPackageRemovedBroadcasts(killApp);
15601            info.sendSystemPackageUpdatedBroadcasts();
15602            info.sendSystemPackageAppearedBroadcasts();
15603        }
15604        // Force a gc here.
15605        Runtime.getRuntime().gc();
15606        // Delete the resources here after sending the broadcast to let
15607        // other processes clean up before deleting resources.
15608        if (info.args != null) {
15609            synchronized (mInstallLock) {
15610                info.args.doPostDeleteLI(true);
15611            }
15612        }
15613
15614        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15615    }
15616
15617    class PackageRemovedInfo {
15618        String removedPackage;
15619        int uid = -1;
15620        int removedAppId = -1;
15621        int[] origUsers;
15622        int[] removedUsers = null;
15623        boolean isRemovedPackageSystemUpdate = false;
15624        boolean isUpdate;
15625        boolean dataRemoved;
15626        boolean removedForAllUsers;
15627        // Clean up resources deleted packages.
15628        InstallArgs args = null;
15629        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15630        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15631
15632        void sendPackageRemovedBroadcasts(boolean killApp) {
15633            sendPackageRemovedBroadcastInternal(killApp);
15634            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15635            for (int i = 0; i < childCount; i++) {
15636                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15637                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15638            }
15639        }
15640
15641        void sendSystemPackageUpdatedBroadcasts() {
15642            if (isRemovedPackageSystemUpdate) {
15643                sendSystemPackageUpdatedBroadcastsInternal();
15644                final int childCount = (removedChildPackages != null)
15645                        ? removedChildPackages.size() : 0;
15646                for (int i = 0; i < childCount; i++) {
15647                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15648                    if (childInfo.isRemovedPackageSystemUpdate) {
15649                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15650                    }
15651                }
15652            }
15653        }
15654
15655        void sendSystemPackageAppearedBroadcasts() {
15656            final int packageCount = (appearedChildPackages != null)
15657                    ? appearedChildPackages.size() : 0;
15658            for (int i = 0; i < packageCount; i++) {
15659                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15660                for (int userId : installedInfo.newUsers) {
15661                    sendPackageAddedForUser(installedInfo.name, true,
15662                            UserHandle.getAppId(installedInfo.uid), userId);
15663                }
15664            }
15665        }
15666
15667        private void sendSystemPackageUpdatedBroadcastsInternal() {
15668            Bundle extras = new Bundle(2);
15669            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15670            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15671            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15672                    extras, 0, null, null, null);
15673            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15674                    extras, 0, null, null, null);
15675            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15676                    null, 0, removedPackage, null, null);
15677        }
15678
15679        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15680            Bundle extras = new Bundle(2);
15681            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15682            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15683            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15684            if (isUpdate || isRemovedPackageSystemUpdate) {
15685                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15686            }
15687            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15688            if (removedPackage != null) {
15689                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15690                        extras, 0, null, null, removedUsers);
15691                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15692                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15693                            removedPackage, extras, 0, null, null, removedUsers);
15694                }
15695            }
15696            if (removedAppId >= 0) {
15697                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15698                        removedUsers);
15699            }
15700        }
15701    }
15702
15703    /*
15704     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15705     * flag is not set, the data directory is removed as well.
15706     * make sure this flag is set for partially installed apps. If not its meaningless to
15707     * delete a partially installed application.
15708     */
15709    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15710            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15711        String packageName = ps.name;
15712        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15713        // Retrieve object to delete permissions for shared user later on
15714        final PackageParser.Package deletedPkg;
15715        final PackageSetting deletedPs;
15716        // reader
15717        synchronized (mPackages) {
15718            deletedPkg = mPackages.get(packageName);
15719            deletedPs = mSettings.mPackages.get(packageName);
15720            if (outInfo != null) {
15721                outInfo.removedPackage = packageName;
15722                outInfo.removedUsers = deletedPs != null
15723                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15724                        : null;
15725            }
15726        }
15727
15728        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15729
15730        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15731            final PackageParser.Package resolvedPkg;
15732            if (deletedPkg != null) {
15733                resolvedPkg = deletedPkg;
15734            } else {
15735                // We don't have a parsed package when it lives on an ejected
15736                // adopted storage device, so fake something together
15737                resolvedPkg = new PackageParser.Package(ps.name);
15738                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15739            }
15740            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15741                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15742            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15743            if (outInfo != null) {
15744                outInfo.dataRemoved = true;
15745            }
15746            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15747        }
15748
15749        // writer
15750        synchronized (mPackages) {
15751            if (deletedPs != null) {
15752                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15753                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15754                    clearDefaultBrowserIfNeeded(packageName);
15755                    if (outInfo != null) {
15756                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15757                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15758                    }
15759                    updatePermissionsLPw(deletedPs.name, null, 0);
15760                    if (deletedPs.sharedUser != null) {
15761                        // Remove permissions associated with package. Since runtime
15762                        // permissions are per user we have to kill the removed package
15763                        // or packages running under the shared user of the removed
15764                        // package if revoking the permissions requested only by the removed
15765                        // package is successful and this causes a change in gids.
15766                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15767                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15768                                    userId);
15769                            if (userIdToKill == UserHandle.USER_ALL
15770                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15771                                // If gids changed for this user, kill all affected packages.
15772                                mHandler.post(new Runnable() {
15773                                    @Override
15774                                    public void run() {
15775                                        // This has to happen with no lock held.
15776                                        killApplication(deletedPs.name, deletedPs.appId,
15777                                                KILL_APP_REASON_GIDS_CHANGED);
15778                                    }
15779                                });
15780                                break;
15781                            }
15782                        }
15783                    }
15784                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15785                }
15786                // make sure to preserve per-user disabled state if this removal was just
15787                // a downgrade of a system app to the factory package
15788                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15789                    if (DEBUG_REMOVE) {
15790                        Slog.d(TAG, "Propagating install state across downgrade");
15791                    }
15792                    for (int userId : allUserHandles) {
15793                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15794                        if (DEBUG_REMOVE) {
15795                            Slog.d(TAG, "    user " + userId + " => " + installed);
15796                        }
15797                        ps.setInstalled(installed, userId);
15798                    }
15799                }
15800            }
15801            // can downgrade to reader
15802            if (writeSettings) {
15803                // Save settings now
15804                mSettings.writeLPr();
15805            }
15806        }
15807        if (outInfo != null) {
15808            // A user ID was deleted here. Go through all users and remove it
15809            // from KeyStore.
15810            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15811        }
15812    }
15813
15814    static boolean locationIsPrivileged(File path) {
15815        try {
15816            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15817                    .getCanonicalPath();
15818            return path.getCanonicalPath().startsWith(privilegedAppDir);
15819        } catch (IOException e) {
15820            Slog.e(TAG, "Unable to access code path " + path);
15821        }
15822        return false;
15823    }
15824
15825    /*
15826     * Tries to delete system package.
15827     */
15828    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15829            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15830            boolean writeSettings) {
15831        if (deletedPs.parentPackageName != null) {
15832            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15833            return false;
15834        }
15835
15836        final boolean applyUserRestrictions
15837                = (allUserHandles != null) && (outInfo.origUsers != null);
15838        final PackageSetting disabledPs;
15839        // Confirm if the system package has been updated
15840        // An updated system app can be deleted. This will also have to restore
15841        // the system pkg from system partition
15842        // reader
15843        synchronized (mPackages) {
15844            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15845        }
15846
15847        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15848                + " disabledPs=" + disabledPs);
15849
15850        if (disabledPs == null) {
15851            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15852            return false;
15853        } else if (DEBUG_REMOVE) {
15854            Slog.d(TAG, "Deleting system pkg from data partition");
15855        }
15856
15857        if (DEBUG_REMOVE) {
15858            if (applyUserRestrictions) {
15859                Slog.d(TAG, "Remembering install states:");
15860                for (int userId : allUserHandles) {
15861                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15862                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15863                }
15864            }
15865        }
15866
15867        // Delete the updated package
15868        outInfo.isRemovedPackageSystemUpdate = true;
15869        if (outInfo.removedChildPackages != null) {
15870            final int childCount = (deletedPs.childPackageNames != null)
15871                    ? deletedPs.childPackageNames.size() : 0;
15872            for (int i = 0; i < childCount; i++) {
15873                String childPackageName = deletedPs.childPackageNames.get(i);
15874                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15875                        .contains(childPackageName)) {
15876                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15877                            childPackageName);
15878                    if (childInfo != null) {
15879                        childInfo.isRemovedPackageSystemUpdate = true;
15880                    }
15881                }
15882            }
15883        }
15884
15885        if (disabledPs.versionCode < deletedPs.versionCode) {
15886            // Delete data for downgrades
15887            flags &= ~PackageManager.DELETE_KEEP_DATA;
15888        } else {
15889            // Preserve data by setting flag
15890            flags |= PackageManager.DELETE_KEEP_DATA;
15891        }
15892
15893        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15894                outInfo, writeSettings, disabledPs.pkg);
15895        if (!ret) {
15896            return false;
15897        }
15898
15899        // writer
15900        synchronized (mPackages) {
15901            // Reinstate the old system package
15902            enableSystemPackageLPw(disabledPs.pkg);
15903            // Remove any native libraries from the upgraded package.
15904            removeNativeBinariesLI(deletedPs);
15905        }
15906
15907        // Install the system package
15908        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15909        int parseFlags = mDefParseFlags
15910                | PackageParser.PARSE_MUST_BE_APK
15911                | PackageParser.PARSE_IS_SYSTEM
15912                | PackageParser.PARSE_IS_SYSTEM_DIR;
15913        if (locationIsPrivileged(disabledPs.codePath)) {
15914            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15915        }
15916
15917        final PackageParser.Package newPkg;
15918        try {
15919            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15920        } catch (PackageManagerException e) {
15921            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15922                    + e.getMessage());
15923            return false;
15924        }
15925        try {
15926            // update shared libraries for the newly re-installed system package
15927            updateSharedLibrariesLPw(newPkg, null);
15928        } catch (PackageManagerException e) {
15929            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15930        }
15931
15932        prepareAppDataAfterInstallLIF(newPkg);
15933
15934        // writer
15935        synchronized (mPackages) {
15936            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15937
15938            // Propagate the permissions state as we do not want to drop on the floor
15939            // runtime permissions. The update permissions method below will take
15940            // care of removing obsolete permissions and grant install permissions.
15941            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15942            updatePermissionsLPw(newPkg.packageName, newPkg,
15943                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15944
15945            if (applyUserRestrictions) {
15946                if (DEBUG_REMOVE) {
15947                    Slog.d(TAG, "Propagating install state across reinstall");
15948                }
15949                for (int userId : allUserHandles) {
15950                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15951                    if (DEBUG_REMOVE) {
15952                        Slog.d(TAG, "    user " + userId + " => " + installed);
15953                    }
15954                    ps.setInstalled(installed, userId);
15955
15956                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15957                }
15958                // Regardless of writeSettings we need to ensure that this restriction
15959                // state propagation is persisted
15960                mSettings.writeAllUsersPackageRestrictionsLPr();
15961            }
15962            // can downgrade to reader here
15963            if (writeSettings) {
15964                mSettings.writeLPr();
15965            }
15966        }
15967        return true;
15968    }
15969
15970    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15971            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15972            PackageRemovedInfo outInfo, boolean writeSettings,
15973            PackageParser.Package replacingPackage) {
15974        synchronized (mPackages) {
15975            if (outInfo != null) {
15976                outInfo.uid = ps.appId;
15977            }
15978
15979            if (outInfo != null && outInfo.removedChildPackages != null) {
15980                final int childCount = (ps.childPackageNames != null)
15981                        ? ps.childPackageNames.size() : 0;
15982                for (int i = 0; i < childCount; i++) {
15983                    String childPackageName = ps.childPackageNames.get(i);
15984                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15985                    if (childPs == null) {
15986                        return false;
15987                    }
15988                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15989                            childPackageName);
15990                    if (childInfo != null) {
15991                        childInfo.uid = childPs.appId;
15992                    }
15993                }
15994            }
15995        }
15996
15997        // Delete package data from internal structures and also remove data if flag is set
15998        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15999
16000        // Delete the child packages data
16001        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16002        for (int i = 0; i < childCount; i++) {
16003            PackageSetting childPs;
16004            synchronized (mPackages) {
16005                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16006            }
16007            if (childPs != null) {
16008                PackageRemovedInfo childOutInfo = (outInfo != null
16009                        && outInfo.removedChildPackages != null)
16010                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16011                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16012                        && (replacingPackage != null
16013                        && !replacingPackage.hasChildPackage(childPs.name))
16014                        ? flags & ~DELETE_KEEP_DATA : flags;
16015                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16016                        deleteFlags, writeSettings);
16017            }
16018        }
16019
16020        // Delete application code and resources only for parent packages
16021        if (ps.parentPackageName == null) {
16022            if (deleteCodeAndResources && (outInfo != null)) {
16023                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16024                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16025                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16026            }
16027        }
16028
16029        return true;
16030    }
16031
16032    @Override
16033    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16034            int userId) {
16035        mContext.enforceCallingOrSelfPermission(
16036                android.Manifest.permission.DELETE_PACKAGES, null);
16037        synchronized (mPackages) {
16038            PackageSetting ps = mSettings.mPackages.get(packageName);
16039            if (ps == null) {
16040                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16041                return false;
16042            }
16043            if (!ps.getInstalled(userId)) {
16044                // Can't block uninstall for an app that is not installed or enabled.
16045                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16046                return false;
16047            }
16048            ps.setBlockUninstall(blockUninstall, userId);
16049            mSettings.writePackageRestrictionsLPr(userId);
16050        }
16051        return true;
16052    }
16053
16054    @Override
16055    public boolean getBlockUninstallForUser(String packageName, int userId) {
16056        synchronized (mPackages) {
16057            PackageSetting ps = mSettings.mPackages.get(packageName);
16058            if (ps == null) {
16059                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16060                return false;
16061            }
16062            return ps.getBlockUninstall(userId);
16063        }
16064    }
16065
16066    @Override
16067    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16068        int callingUid = Binder.getCallingUid();
16069        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16070            throw new SecurityException(
16071                    "setRequiredForSystemUser can only be run by the system or root");
16072        }
16073        synchronized (mPackages) {
16074            PackageSetting ps = mSettings.mPackages.get(packageName);
16075            if (ps == null) {
16076                Log.w(TAG, "Package doesn't exist: " + packageName);
16077                return false;
16078            }
16079            if (systemUserApp) {
16080                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16081            } else {
16082                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16083            }
16084            mSettings.writeLPr();
16085        }
16086        return true;
16087    }
16088
16089    /*
16090     * This method handles package deletion in general
16091     */
16092    private boolean deletePackageLIF(String packageName, UserHandle user,
16093            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16094            PackageRemovedInfo outInfo, boolean writeSettings,
16095            PackageParser.Package replacingPackage) {
16096        if (packageName == null) {
16097            Slog.w(TAG, "Attempt to delete null packageName.");
16098            return false;
16099        }
16100
16101        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16102
16103        PackageSetting ps;
16104
16105        synchronized (mPackages) {
16106            ps = mSettings.mPackages.get(packageName);
16107            if (ps == null) {
16108                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16109                return false;
16110            }
16111
16112            if (ps.parentPackageName != null && (!isSystemApp(ps)
16113                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16114                if (DEBUG_REMOVE) {
16115                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16116                            + ((user == null) ? UserHandle.USER_ALL : user));
16117                }
16118                final int removedUserId = (user != null) ? user.getIdentifier()
16119                        : UserHandle.USER_ALL;
16120                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16121                    return false;
16122                }
16123                markPackageUninstalledForUserLPw(ps, user);
16124                scheduleWritePackageRestrictionsLocked(user);
16125                return true;
16126            }
16127        }
16128
16129        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16130                && user.getIdentifier() != UserHandle.USER_ALL)) {
16131            // The caller is asking that the package only be deleted for a single
16132            // user.  To do this, we just mark its uninstalled state and delete
16133            // its data. If this is a system app, we only allow this to happen if
16134            // they have set the special DELETE_SYSTEM_APP which requests different
16135            // semantics than normal for uninstalling system apps.
16136            markPackageUninstalledForUserLPw(ps, user);
16137
16138            if (!isSystemApp(ps)) {
16139                // Do not uninstall the APK if an app should be cached
16140                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16141                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16142                    // Other user still have this package installed, so all
16143                    // we need to do is clear this user's data and save that
16144                    // it is uninstalled.
16145                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16146                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16147                        return false;
16148                    }
16149                    scheduleWritePackageRestrictionsLocked(user);
16150                    return true;
16151                } else {
16152                    // We need to set it back to 'installed' so the uninstall
16153                    // broadcasts will be sent correctly.
16154                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16155                    ps.setInstalled(true, user.getIdentifier());
16156                }
16157            } else {
16158                // This is a system app, so we assume that the
16159                // other users still have this package installed, so all
16160                // we need to do is clear this user's data and save that
16161                // it is uninstalled.
16162                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16163                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16164                    return false;
16165                }
16166                scheduleWritePackageRestrictionsLocked(user);
16167                return true;
16168            }
16169        }
16170
16171        // If we are deleting a composite package for all users, keep track
16172        // of result for each child.
16173        if (ps.childPackageNames != null && outInfo != null) {
16174            synchronized (mPackages) {
16175                final int childCount = ps.childPackageNames.size();
16176                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16177                for (int i = 0; i < childCount; i++) {
16178                    String childPackageName = ps.childPackageNames.get(i);
16179                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16180                    childInfo.removedPackage = childPackageName;
16181                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16182                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16183                    if (childPs != null) {
16184                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16185                    }
16186                }
16187            }
16188        }
16189
16190        boolean ret = false;
16191        if (isSystemApp(ps)) {
16192            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16193            // When an updated system application is deleted we delete the existing resources
16194            // as well and fall back to existing code in system partition
16195            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16196        } else {
16197            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16198            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16199                    outInfo, writeSettings, replacingPackage);
16200        }
16201
16202        // Take a note whether we deleted the package for all users
16203        if (outInfo != null) {
16204            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16205            if (outInfo.removedChildPackages != null) {
16206                synchronized (mPackages) {
16207                    final int childCount = outInfo.removedChildPackages.size();
16208                    for (int i = 0; i < childCount; i++) {
16209                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16210                        if (childInfo != null) {
16211                            childInfo.removedForAllUsers = mPackages.get(
16212                                    childInfo.removedPackage) == null;
16213                        }
16214                    }
16215                }
16216            }
16217            // If we uninstalled an update to a system app there may be some
16218            // child packages that appeared as they are declared in the system
16219            // app but were not declared in the update.
16220            if (isSystemApp(ps)) {
16221                synchronized (mPackages) {
16222                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16223                    final int childCount = (updatedPs.childPackageNames != null)
16224                            ? updatedPs.childPackageNames.size() : 0;
16225                    for (int i = 0; i < childCount; i++) {
16226                        String childPackageName = updatedPs.childPackageNames.get(i);
16227                        if (outInfo.removedChildPackages == null
16228                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16229                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16230                            if (childPs == null) {
16231                                continue;
16232                            }
16233                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16234                            installRes.name = childPackageName;
16235                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16236                            installRes.pkg = mPackages.get(childPackageName);
16237                            installRes.uid = childPs.pkg.applicationInfo.uid;
16238                            if (outInfo.appearedChildPackages == null) {
16239                                outInfo.appearedChildPackages = new ArrayMap<>();
16240                            }
16241                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16242                        }
16243                    }
16244                }
16245            }
16246        }
16247
16248        return ret;
16249    }
16250
16251    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16252        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16253                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16254        for (int nextUserId : userIds) {
16255            if (DEBUG_REMOVE) {
16256                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16257            }
16258            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16259                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16260                    false /*hidden*/, false /*suspended*/, null, null, null,
16261                    false /*blockUninstall*/,
16262                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16263        }
16264    }
16265
16266    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16267            PackageRemovedInfo outInfo) {
16268        final PackageParser.Package pkg;
16269        synchronized (mPackages) {
16270            pkg = mPackages.get(ps.name);
16271        }
16272
16273        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16274                : new int[] {userId};
16275        for (int nextUserId : userIds) {
16276            if (DEBUG_REMOVE) {
16277                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16278                        + nextUserId);
16279            }
16280
16281            destroyAppDataLIF(pkg, userId,
16282                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16283            destroyAppProfilesLIF(pkg, userId);
16284            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16285            schedulePackageCleaning(ps.name, nextUserId, false);
16286            synchronized (mPackages) {
16287                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16288                    scheduleWritePackageRestrictionsLocked(nextUserId);
16289                }
16290                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16291            }
16292        }
16293
16294        if (outInfo != null) {
16295            outInfo.removedPackage = ps.name;
16296            outInfo.removedAppId = ps.appId;
16297            outInfo.removedUsers = userIds;
16298        }
16299
16300        return true;
16301    }
16302
16303    private final class ClearStorageConnection implements ServiceConnection {
16304        IMediaContainerService mContainerService;
16305
16306        @Override
16307        public void onServiceConnected(ComponentName name, IBinder service) {
16308            synchronized (this) {
16309                mContainerService = IMediaContainerService.Stub.asInterface(service);
16310                notifyAll();
16311            }
16312        }
16313
16314        @Override
16315        public void onServiceDisconnected(ComponentName name) {
16316        }
16317    }
16318
16319    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16320        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16321
16322        final boolean mounted;
16323        if (Environment.isExternalStorageEmulated()) {
16324            mounted = true;
16325        } else {
16326            final String status = Environment.getExternalStorageState();
16327
16328            mounted = status.equals(Environment.MEDIA_MOUNTED)
16329                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16330        }
16331
16332        if (!mounted) {
16333            return;
16334        }
16335
16336        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16337        int[] users;
16338        if (userId == UserHandle.USER_ALL) {
16339            users = sUserManager.getUserIds();
16340        } else {
16341            users = new int[] { userId };
16342        }
16343        final ClearStorageConnection conn = new ClearStorageConnection();
16344        if (mContext.bindServiceAsUser(
16345                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16346            try {
16347                for (int curUser : users) {
16348                    long timeout = SystemClock.uptimeMillis() + 5000;
16349                    synchronized (conn) {
16350                        long now;
16351                        while (conn.mContainerService == null &&
16352                                (now = SystemClock.uptimeMillis()) < timeout) {
16353                            try {
16354                                conn.wait(timeout - now);
16355                            } catch (InterruptedException e) {
16356                            }
16357                        }
16358                    }
16359                    if (conn.mContainerService == null) {
16360                        return;
16361                    }
16362
16363                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16364                    clearDirectory(conn.mContainerService,
16365                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16366                    if (allData) {
16367                        clearDirectory(conn.mContainerService,
16368                                userEnv.buildExternalStorageAppDataDirs(packageName));
16369                        clearDirectory(conn.mContainerService,
16370                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16371                    }
16372                }
16373            } finally {
16374                mContext.unbindService(conn);
16375            }
16376        }
16377    }
16378
16379    @Override
16380    public void clearApplicationProfileData(String packageName) {
16381        enforceSystemOrRoot("Only the system can clear all profile data");
16382
16383        final PackageParser.Package pkg;
16384        synchronized (mPackages) {
16385            pkg = mPackages.get(packageName);
16386        }
16387
16388        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16389            synchronized (mInstallLock) {
16390                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16391                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16392                        true /* removeBaseMarker */);
16393            }
16394        }
16395    }
16396
16397    @Override
16398    public void clearApplicationUserData(final String packageName,
16399            final IPackageDataObserver observer, final int userId) {
16400        mContext.enforceCallingOrSelfPermission(
16401                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16402
16403        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16404                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16405
16406        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16407            throw new SecurityException("Cannot clear data for a protected package: "
16408                    + packageName);
16409        }
16410        // Queue up an async operation since the package deletion may take a little while.
16411        mHandler.post(new Runnable() {
16412            public void run() {
16413                mHandler.removeCallbacks(this);
16414                final boolean succeeded;
16415                try (PackageFreezer freezer = freezePackage(packageName,
16416                        "clearApplicationUserData")) {
16417                    synchronized (mInstallLock) {
16418                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16419                    }
16420                    clearExternalStorageDataSync(packageName, userId, true);
16421                }
16422                if (succeeded) {
16423                    // invoke DeviceStorageMonitor's update method to clear any notifications
16424                    DeviceStorageMonitorInternal dsm = LocalServices
16425                            .getService(DeviceStorageMonitorInternal.class);
16426                    if (dsm != null) {
16427                        dsm.checkMemory();
16428                    }
16429                }
16430                if(observer != null) {
16431                    try {
16432                        observer.onRemoveCompleted(packageName, succeeded);
16433                    } catch (RemoteException e) {
16434                        Log.i(TAG, "Observer no longer exists.");
16435                    }
16436                } //end if observer
16437            } //end run
16438        });
16439    }
16440
16441    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16442        if (packageName == null) {
16443            Slog.w(TAG, "Attempt to delete null packageName.");
16444            return false;
16445        }
16446
16447        // Try finding details about the requested package
16448        PackageParser.Package pkg;
16449        synchronized (mPackages) {
16450            pkg = mPackages.get(packageName);
16451            if (pkg == null) {
16452                final PackageSetting ps = mSettings.mPackages.get(packageName);
16453                if (ps != null) {
16454                    pkg = ps.pkg;
16455                }
16456            }
16457
16458            if (pkg == null) {
16459                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16460                return false;
16461            }
16462
16463            PackageSetting ps = (PackageSetting) pkg.mExtras;
16464            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16465        }
16466
16467        clearAppDataLIF(pkg, userId,
16468                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16469
16470        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16471        removeKeystoreDataIfNeeded(userId, appId);
16472
16473        UserManagerInternal umInternal = getUserManagerInternal();
16474        final int flags;
16475        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16476            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16477        } else if (umInternal.isUserRunning(userId)) {
16478            flags = StorageManager.FLAG_STORAGE_DE;
16479        } else {
16480            flags = 0;
16481        }
16482        prepareAppDataContentsLIF(pkg, userId, flags);
16483
16484        return true;
16485    }
16486
16487    /**
16488     * Reverts user permission state changes (permissions and flags) in
16489     * all packages for a given user.
16490     *
16491     * @param userId The device user for which to do a reset.
16492     */
16493    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16494        final int packageCount = mPackages.size();
16495        for (int i = 0; i < packageCount; i++) {
16496            PackageParser.Package pkg = mPackages.valueAt(i);
16497            PackageSetting ps = (PackageSetting) pkg.mExtras;
16498            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16499        }
16500    }
16501
16502    private void resetNetworkPolicies(int userId) {
16503        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16504    }
16505
16506    /**
16507     * Reverts user permission state changes (permissions and flags).
16508     *
16509     * @param ps The package for which to reset.
16510     * @param userId The device user for which to do a reset.
16511     */
16512    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16513            final PackageSetting ps, final int userId) {
16514        if (ps.pkg == null) {
16515            return;
16516        }
16517
16518        // These are flags that can change base on user actions.
16519        final int userSettableMask = FLAG_PERMISSION_USER_SET
16520                | FLAG_PERMISSION_USER_FIXED
16521                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16522                | FLAG_PERMISSION_REVIEW_REQUIRED;
16523
16524        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16525                | FLAG_PERMISSION_POLICY_FIXED;
16526
16527        boolean writeInstallPermissions = false;
16528        boolean writeRuntimePermissions = false;
16529
16530        final int permissionCount = ps.pkg.requestedPermissions.size();
16531        for (int i = 0; i < permissionCount; i++) {
16532            String permission = ps.pkg.requestedPermissions.get(i);
16533
16534            BasePermission bp = mSettings.mPermissions.get(permission);
16535            if (bp == null) {
16536                continue;
16537            }
16538
16539            // If shared user we just reset the state to which only this app contributed.
16540            if (ps.sharedUser != null) {
16541                boolean used = false;
16542                final int packageCount = ps.sharedUser.packages.size();
16543                for (int j = 0; j < packageCount; j++) {
16544                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16545                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16546                            && pkg.pkg.requestedPermissions.contains(permission)) {
16547                        used = true;
16548                        break;
16549                    }
16550                }
16551                if (used) {
16552                    continue;
16553                }
16554            }
16555
16556            PermissionsState permissionsState = ps.getPermissionsState();
16557
16558            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16559
16560            // Always clear the user settable flags.
16561            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16562                    bp.name) != null;
16563            // If permission review is enabled and this is a legacy app, mark the
16564            // permission as requiring a review as this is the initial state.
16565            int flags = 0;
16566            if (mPermissionReviewRequired
16567                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16568                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16569            }
16570            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16571                if (hasInstallState) {
16572                    writeInstallPermissions = true;
16573                } else {
16574                    writeRuntimePermissions = true;
16575                }
16576            }
16577
16578            // Below is only runtime permission handling.
16579            if (!bp.isRuntime()) {
16580                continue;
16581            }
16582
16583            // Never clobber system or policy.
16584            if ((oldFlags & policyOrSystemFlags) != 0) {
16585                continue;
16586            }
16587
16588            // If this permission was granted by default, make sure it is.
16589            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16590                if (permissionsState.grantRuntimePermission(bp, userId)
16591                        != PERMISSION_OPERATION_FAILURE) {
16592                    writeRuntimePermissions = true;
16593                }
16594            // If permission review is enabled the permissions for a legacy apps
16595            // are represented as constantly granted runtime ones, so don't revoke.
16596            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16597                // Otherwise, reset the permission.
16598                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16599                switch (revokeResult) {
16600                    case PERMISSION_OPERATION_SUCCESS:
16601                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16602                        writeRuntimePermissions = true;
16603                        final int appId = ps.appId;
16604                        mHandler.post(new Runnable() {
16605                            @Override
16606                            public void run() {
16607                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16608                            }
16609                        });
16610                    } break;
16611                }
16612            }
16613        }
16614
16615        // Synchronously write as we are taking permissions away.
16616        if (writeRuntimePermissions) {
16617            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16618        }
16619
16620        // Synchronously write as we are taking permissions away.
16621        if (writeInstallPermissions) {
16622            mSettings.writeLPr();
16623        }
16624    }
16625
16626    /**
16627     * Remove entries from the keystore daemon. Will only remove it if the
16628     * {@code appId} is valid.
16629     */
16630    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16631        if (appId < 0) {
16632            return;
16633        }
16634
16635        final KeyStore keyStore = KeyStore.getInstance();
16636        if (keyStore != null) {
16637            if (userId == UserHandle.USER_ALL) {
16638                for (final int individual : sUserManager.getUserIds()) {
16639                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16640                }
16641            } else {
16642                keyStore.clearUid(UserHandle.getUid(userId, appId));
16643            }
16644        } else {
16645            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16646        }
16647    }
16648
16649    @Override
16650    public void deleteApplicationCacheFiles(final String packageName,
16651            final IPackageDataObserver observer) {
16652        final int userId = UserHandle.getCallingUserId();
16653        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16654    }
16655
16656    @Override
16657    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16658            final IPackageDataObserver observer) {
16659        mContext.enforceCallingOrSelfPermission(
16660                android.Manifest.permission.DELETE_CACHE_FILES, null);
16661        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16662                /* requireFullPermission= */ true, /* checkShell= */ false,
16663                "delete application cache files");
16664
16665        final PackageParser.Package pkg;
16666        synchronized (mPackages) {
16667            pkg = mPackages.get(packageName);
16668        }
16669
16670        // Queue up an async operation since the package deletion may take a little while.
16671        mHandler.post(new Runnable() {
16672            public void run() {
16673                synchronized (mInstallLock) {
16674                    final int flags = StorageManager.FLAG_STORAGE_DE
16675                            | StorageManager.FLAG_STORAGE_CE;
16676                    // We're only clearing cache files, so we don't care if the
16677                    // app is unfrozen and still able to run
16678                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16679                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16680                }
16681                clearExternalStorageDataSync(packageName, userId, false);
16682                if (observer != null) {
16683                    try {
16684                        observer.onRemoveCompleted(packageName, true);
16685                    } catch (RemoteException e) {
16686                        Log.i(TAG, "Observer no longer exists.");
16687                    }
16688                }
16689            }
16690        });
16691    }
16692
16693    @Override
16694    public void getPackageSizeInfo(final String packageName, int userHandle,
16695            final IPackageStatsObserver observer) {
16696        mContext.enforceCallingOrSelfPermission(
16697                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16698        if (packageName == null) {
16699            throw new IllegalArgumentException("Attempt to get size of null packageName");
16700        }
16701
16702        PackageStats stats = new PackageStats(packageName, userHandle);
16703
16704        /*
16705         * Queue up an async operation since the package measurement may take a
16706         * little while.
16707         */
16708        Message msg = mHandler.obtainMessage(INIT_COPY);
16709        msg.obj = new MeasureParams(stats, observer);
16710        mHandler.sendMessage(msg);
16711    }
16712
16713    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16714        final PackageSetting ps;
16715        synchronized (mPackages) {
16716            ps = mSettings.mPackages.get(packageName);
16717            if (ps == null) {
16718                Slog.w(TAG, "Failed to find settings for " + packageName);
16719                return false;
16720            }
16721        }
16722        try {
16723            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16724                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16725                    ps.getCeDataInode(userId), ps.codePathString, stats);
16726        } catch (InstallerException e) {
16727            Slog.w(TAG, String.valueOf(e));
16728            return false;
16729        }
16730
16731        // For now, ignore code size of packages on system partition
16732        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16733            stats.codeSize = 0;
16734        }
16735
16736        return true;
16737    }
16738
16739    private int getUidTargetSdkVersionLockedLPr(int uid) {
16740        Object obj = mSettings.getUserIdLPr(uid);
16741        if (obj instanceof SharedUserSetting) {
16742            final SharedUserSetting sus = (SharedUserSetting) obj;
16743            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16744            final Iterator<PackageSetting> it = sus.packages.iterator();
16745            while (it.hasNext()) {
16746                final PackageSetting ps = it.next();
16747                if (ps.pkg != null) {
16748                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16749                    if (v < vers) vers = v;
16750                }
16751            }
16752            return vers;
16753        } else if (obj instanceof PackageSetting) {
16754            final PackageSetting ps = (PackageSetting) obj;
16755            if (ps.pkg != null) {
16756                return ps.pkg.applicationInfo.targetSdkVersion;
16757            }
16758        }
16759        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16760    }
16761
16762    @Override
16763    public void addPreferredActivity(IntentFilter filter, int match,
16764            ComponentName[] set, ComponentName activity, int userId) {
16765        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16766                "Adding preferred");
16767    }
16768
16769    private void addPreferredActivityInternal(IntentFilter filter, int match,
16770            ComponentName[] set, ComponentName activity, boolean always, int userId,
16771            String opname) {
16772        // writer
16773        int callingUid = Binder.getCallingUid();
16774        enforceCrossUserPermission(callingUid, userId,
16775                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16776        if (filter.countActions() == 0) {
16777            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16778            return;
16779        }
16780        synchronized (mPackages) {
16781            if (mContext.checkCallingOrSelfPermission(
16782                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16783                    != PackageManager.PERMISSION_GRANTED) {
16784                if (getUidTargetSdkVersionLockedLPr(callingUid)
16785                        < Build.VERSION_CODES.FROYO) {
16786                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16787                            + callingUid);
16788                    return;
16789                }
16790                mContext.enforceCallingOrSelfPermission(
16791                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16792            }
16793
16794            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16795            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16796                    + userId + ":");
16797            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16798            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16799            scheduleWritePackageRestrictionsLocked(userId);
16800            postPreferredActivityChangedBroadcast(userId);
16801        }
16802    }
16803
16804    private void postPreferredActivityChangedBroadcast(int userId) {
16805        mHandler.post(() -> {
16806            final IActivityManager am = ActivityManagerNative.getDefault();
16807            if (am == null) {
16808                return;
16809            }
16810
16811            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16812            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16813            try {
16814                am.broadcastIntent(null, intent, null, null,
16815                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16816                        null, false, false, userId);
16817            } catch (RemoteException e) {
16818            }
16819        });
16820    }
16821
16822    @Override
16823    public void replacePreferredActivity(IntentFilter filter, int match,
16824            ComponentName[] set, ComponentName activity, int userId) {
16825        if (filter.countActions() != 1) {
16826            throw new IllegalArgumentException(
16827                    "replacePreferredActivity expects filter to have only 1 action.");
16828        }
16829        if (filter.countDataAuthorities() != 0
16830                || filter.countDataPaths() != 0
16831                || filter.countDataSchemes() > 1
16832                || filter.countDataTypes() != 0) {
16833            throw new IllegalArgumentException(
16834                    "replacePreferredActivity expects filter to have no data authorities, " +
16835                    "paths, or types; and at most one scheme.");
16836        }
16837
16838        final int callingUid = Binder.getCallingUid();
16839        enforceCrossUserPermission(callingUid, userId,
16840                true /* requireFullPermission */, false /* checkShell */,
16841                "replace preferred activity");
16842        synchronized (mPackages) {
16843            if (mContext.checkCallingOrSelfPermission(
16844                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16845                    != PackageManager.PERMISSION_GRANTED) {
16846                if (getUidTargetSdkVersionLockedLPr(callingUid)
16847                        < Build.VERSION_CODES.FROYO) {
16848                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16849                            + Binder.getCallingUid());
16850                    return;
16851                }
16852                mContext.enforceCallingOrSelfPermission(
16853                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16854            }
16855
16856            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16857            if (pir != null) {
16858                // Get all of the existing entries that exactly match this filter.
16859                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16860                if (existing != null && existing.size() == 1) {
16861                    PreferredActivity cur = existing.get(0);
16862                    if (DEBUG_PREFERRED) {
16863                        Slog.i(TAG, "Checking replace of preferred:");
16864                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16865                        if (!cur.mPref.mAlways) {
16866                            Slog.i(TAG, "  -- CUR; not mAlways!");
16867                        } else {
16868                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16869                            Slog.i(TAG, "  -- CUR: mSet="
16870                                    + Arrays.toString(cur.mPref.mSetComponents));
16871                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16872                            Slog.i(TAG, "  -- NEW: mMatch="
16873                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16874                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16875                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16876                        }
16877                    }
16878                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16879                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16880                            && cur.mPref.sameSet(set)) {
16881                        // Setting the preferred activity to what it happens to be already
16882                        if (DEBUG_PREFERRED) {
16883                            Slog.i(TAG, "Replacing with same preferred activity "
16884                                    + cur.mPref.mShortComponent + " for user "
16885                                    + userId + ":");
16886                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16887                        }
16888                        return;
16889                    }
16890                }
16891
16892                if (existing != null) {
16893                    if (DEBUG_PREFERRED) {
16894                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16895                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16896                    }
16897                    for (int i = 0; i < existing.size(); i++) {
16898                        PreferredActivity pa = existing.get(i);
16899                        if (DEBUG_PREFERRED) {
16900                            Slog.i(TAG, "Removing existing preferred activity "
16901                                    + pa.mPref.mComponent + ":");
16902                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16903                        }
16904                        pir.removeFilter(pa);
16905                    }
16906                }
16907            }
16908            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16909                    "Replacing preferred");
16910        }
16911    }
16912
16913    @Override
16914    public void clearPackagePreferredActivities(String packageName) {
16915        final int uid = Binder.getCallingUid();
16916        // writer
16917        synchronized (mPackages) {
16918            PackageParser.Package pkg = mPackages.get(packageName);
16919            if (pkg == null || pkg.applicationInfo.uid != uid) {
16920                if (mContext.checkCallingOrSelfPermission(
16921                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16922                        != PackageManager.PERMISSION_GRANTED) {
16923                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16924                            < Build.VERSION_CODES.FROYO) {
16925                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16926                                + Binder.getCallingUid());
16927                        return;
16928                    }
16929                    mContext.enforceCallingOrSelfPermission(
16930                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16931                }
16932            }
16933
16934            int user = UserHandle.getCallingUserId();
16935            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16936                scheduleWritePackageRestrictionsLocked(user);
16937            }
16938        }
16939    }
16940
16941    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16942    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16943        ArrayList<PreferredActivity> removed = null;
16944        boolean changed = false;
16945        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16946            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16947            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16948            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16949                continue;
16950            }
16951            Iterator<PreferredActivity> it = pir.filterIterator();
16952            while (it.hasNext()) {
16953                PreferredActivity pa = it.next();
16954                // Mark entry for removal only if it matches the package name
16955                // and the entry is of type "always".
16956                if (packageName == null ||
16957                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16958                                && pa.mPref.mAlways)) {
16959                    if (removed == null) {
16960                        removed = new ArrayList<PreferredActivity>();
16961                    }
16962                    removed.add(pa);
16963                }
16964            }
16965            if (removed != null) {
16966                for (int j=0; j<removed.size(); j++) {
16967                    PreferredActivity pa = removed.get(j);
16968                    pir.removeFilter(pa);
16969                }
16970                changed = true;
16971            }
16972        }
16973        if (changed) {
16974            postPreferredActivityChangedBroadcast(userId);
16975        }
16976        return changed;
16977    }
16978
16979    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16980    private void clearIntentFilterVerificationsLPw(int userId) {
16981        final int packageCount = mPackages.size();
16982        for (int i = 0; i < packageCount; i++) {
16983            PackageParser.Package pkg = mPackages.valueAt(i);
16984            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16985        }
16986    }
16987
16988    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16989    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16990        if (userId == UserHandle.USER_ALL) {
16991            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16992                    sUserManager.getUserIds())) {
16993                for (int oneUserId : sUserManager.getUserIds()) {
16994                    scheduleWritePackageRestrictionsLocked(oneUserId);
16995                }
16996            }
16997        } else {
16998            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16999                scheduleWritePackageRestrictionsLocked(userId);
17000            }
17001        }
17002    }
17003
17004    void clearDefaultBrowserIfNeeded(String packageName) {
17005        for (int oneUserId : sUserManager.getUserIds()) {
17006            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17007            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17008            if (packageName.equals(defaultBrowserPackageName)) {
17009                setDefaultBrowserPackageName(null, oneUserId);
17010            }
17011        }
17012    }
17013
17014    @Override
17015    public void resetApplicationPreferences(int userId) {
17016        mContext.enforceCallingOrSelfPermission(
17017                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17018        final long identity = Binder.clearCallingIdentity();
17019        // writer
17020        try {
17021            synchronized (mPackages) {
17022                clearPackagePreferredActivitiesLPw(null, userId);
17023                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17024                // TODO: We have to reset the default SMS and Phone. This requires
17025                // significant refactoring to keep all default apps in the package
17026                // manager (cleaner but more work) or have the services provide
17027                // callbacks to the package manager to request a default app reset.
17028                applyFactoryDefaultBrowserLPw(userId);
17029                clearIntentFilterVerificationsLPw(userId);
17030                primeDomainVerificationsLPw(userId);
17031                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17032                scheduleWritePackageRestrictionsLocked(userId);
17033            }
17034            resetNetworkPolicies(userId);
17035        } finally {
17036            Binder.restoreCallingIdentity(identity);
17037        }
17038    }
17039
17040    @Override
17041    public int getPreferredActivities(List<IntentFilter> outFilters,
17042            List<ComponentName> outActivities, String packageName) {
17043
17044        int num = 0;
17045        final int userId = UserHandle.getCallingUserId();
17046        // reader
17047        synchronized (mPackages) {
17048            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17049            if (pir != null) {
17050                final Iterator<PreferredActivity> it = pir.filterIterator();
17051                while (it.hasNext()) {
17052                    final PreferredActivity pa = it.next();
17053                    if (packageName == null
17054                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17055                                    && pa.mPref.mAlways)) {
17056                        if (outFilters != null) {
17057                            outFilters.add(new IntentFilter(pa));
17058                        }
17059                        if (outActivities != null) {
17060                            outActivities.add(pa.mPref.mComponent);
17061                        }
17062                    }
17063                }
17064            }
17065        }
17066
17067        return num;
17068    }
17069
17070    @Override
17071    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17072            int userId) {
17073        int callingUid = Binder.getCallingUid();
17074        if (callingUid != Process.SYSTEM_UID) {
17075            throw new SecurityException(
17076                    "addPersistentPreferredActivity can only be run by the system");
17077        }
17078        if (filter.countActions() == 0) {
17079            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17080            return;
17081        }
17082        synchronized (mPackages) {
17083            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17084                    ":");
17085            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17086            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17087                    new PersistentPreferredActivity(filter, activity));
17088            scheduleWritePackageRestrictionsLocked(userId);
17089            postPreferredActivityChangedBroadcast(userId);
17090        }
17091    }
17092
17093    @Override
17094    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17095        int callingUid = Binder.getCallingUid();
17096        if (callingUid != Process.SYSTEM_UID) {
17097            throw new SecurityException(
17098                    "clearPackagePersistentPreferredActivities can only be run by the system");
17099        }
17100        ArrayList<PersistentPreferredActivity> removed = null;
17101        boolean changed = false;
17102        synchronized (mPackages) {
17103            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17104                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17105                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17106                        .valueAt(i);
17107                if (userId != thisUserId) {
17108                    continue;
17109                }
17110                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17111                while (it.hasNext()) {
17112                    PersistentPreferredActivity ppa = it.next();
17113                    // Mark entry for removal only if it matches the package name.
17114                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17115                        if (removed == null) {
17116                            removed = new ArrayList<PersistentPreferredActivity>();
17117                        }
17118                        removed.add(ppa);
17119                    }
17120                }
17121                if (removed != null) {
17122                    for (int j=0; j<removed.size(); j++) {
17123                        PersistentPreferredActivity ppa = removed.get(j);
17124                        ppir.removeFilter(ppa);
17125                    }
17126                    changed = true;
17127                }
17128            }
17129
17130            if (changed) {
17131                scheduleWritePackageRestrictionsLocked(userId);
17132                postPreferredActivityChangedBroadcast(userId);
17133            }
17134        }
17135    }
17136
17137    /**
17138     * Common machinery for picking apart a restored XML blob and passing
17139     * it to a caller-supplied functor to be applied to the running system.
17140     */
17141    private void restoreFromXml(XmlPullParser parser, int userId,
17142            String expectedStartTag, BlobXmlRestorer functor)
17143            throws IOException, XmlPullParserException {
17144        int type;
17145        while ((type = parser.next()) != XmlPullParser.START_TAG
17146                && type != XmlPullParser.END_DOCUMENT) {
17147        }
17148        if (type != XmlPullParser.START_TAG) {
17149            // oops didn't find a start tag?!
17150            if (DEBUG_BACKUP) {
17151                Slog.e(TAG, "Didn't find start tag during restore");
17152            }
17153            return;
17154        }
17155Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17156        // this is supposed to be TAG_PREFERRED_BACKUP
17157        if (!expectedStartTag.equals(parser.getName())) {
17158            if (DEBUG_BACKUP) {
17159                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17160            }
17161            return;
17162        }
17163
17164        // skip interfering stuff, then we're aligned with the backing implementation
17165        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17166Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17167        functor.apply(parser, userId);
17168    }
17169
17170    private interface BlobXmlRestorer {
17171        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17172    }
17173
17174    /**
17175     * Non-Binder method, support for the backup/restore mechanism: write the
17176     * full set of preferred activities in its canonical XML format.  Returns the
17177     * XML output as a byte array, or null if there is none.
17178     */
17179    @Override
17180    public byte[] getPreferredActivityBackup(int userId) {
17181        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17182            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17183        }
17184
17185        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17186        try {
17187            final XmlSerializer serializer = new FastXmlSerializer();
17188            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17189            serializer.startDocument(null, true);
17190            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17191
17192            synchronized (mPackages) {
17193                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17194            }
17195
17196            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17197            serializer.endDocument();
17198            serializer.flush();
17199        } catch (Exception e) {
17200            if (DEBUG_BACKUP) {
17201                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17202            }
17203            return null;
17204        }
17205
17206        return dataStream.toByteArray();
17207    }
17208
17209    @Override
17210    public void restorePreferredActivities(byte[] backup, int userId) {
17211        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17212            throw new SecurityException("Only the system may call restorePreferredActivities()");
17213        }
17214
17215        try {
17216            final XmlPullParser parser = Xml.newPullParser();
17217            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17218            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17219                    new BlobXmlRestorer() {
17220                        @Override
17221                        public void apply(XmlPullParser parser, int userId)
17222                                throws XmlPullParserException, IOException {
17223                            synchronized (mPackages) {
17224                                mSettings.readPreferredActivitiesLPw(parser, userId);
17225                            }
17226                        }
17227                    } );
17228        } catch (Exception e) {
17229            if (DEBUG_BACKUP) {
17230                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17231            }
17232        }
17233    }
17234
17235    /**
17236     * Non-Binder method, support for the backup/restore mechanism: write the
17237     * default browser (etc) settings in its canonical XML format.  Returns the default
17238     * browser XML representation as a byte array, or null if there is none.
17239     */
17240    @Override
17241    public byte[] getDefaultAppsBackup(int userId) {
17242        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17243            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17244        }
17245
17246        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17247        try {
17248            final XmlSerializer serializer = new FastXmlSerializer();
17249            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17250            serializer.startDocument(null, true);
17251            serializer.startTag(null, TAG_DEFAULT_APPS);
17252
17253            synchronized (mPackages) {
17254                mSettings.writeDefaultAppsLPr(serializer, userId);
17255            }
17256
17257            serializer.endTag(null, TAG_DEFAULT_APPS);
17258            serializer.endDocument();
17259            serializer.flush();
17260        } catch (Exception e) {
17261            if (DEBUG_BACKUP) {
17262                Slog.e(TAG, "Unable to write default apps for backup", e);
17263            }
17264            return null;
17265        }
17266
17267        return dataStream.toByteArray();
17268    }
17269
17270    @Override
17271    public void restoreDefaultApps(byte[] backup, int userId) {
17272        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17273            throw new SecurityException("Only the system may call restoreDefaultApps()");
17274        }
17275
17276        try {
17277            final XmlPullParser parser = Xml.newPullParser();
17278            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17279            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17280                    new BlobXmlRestorer() {
17281                        @Override
17282                        public void apply(XmlPullParser parser, int userId)
17283                                throws XmlPullParserException, IOException {
17284                            synchronized (mPackages) {
17285                                mSettings.readDefaultAppsLPw(parser, userId);
17286                            }
17287                        }
17288                    } );
17289        } catch (Exception e) {
17290            if (DEBUG_BACKUP) {
17291                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17292            }
17293        }
17294    }
17295
17296    @Override
17297    public byte[] getIntentFilterVerificationBackup(int userId) {
17298        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17299            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17300        }
17301
17302        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17303        try {
17304            final XmlSerializer serializer = new FastXmlSerializer();
17305            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17306            serializer.startDocument(null, true);
17307            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17308
17309            synchronized (mPackages) {
17310                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17311            }
17312
17313            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17314            serializer.endDocument();
17315            serializer.flush();
17316        } catch (Exception e) {
17317            if (DEBUG_BACKUP) {
17318                Slog.e(TAG, "Unable to write default apps for backup", e);
17319            }
17320            return null;
17321        }
17322
17323        return dataStream.toByteArray();
17324    }
17325
17326    @Override
17327    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17328        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17329            throw new SecurityException("Only the system may call restorePreferredActivities()");
17330        }
17331
17332        try {
17333            final XmlPullParser parser = Xml.newPullParser();
17334            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17335            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17336                    new BlobXmlRestorer() {
17337                        @Override
17338                        public void apply(XmlPullParser parser, int userId)
17339                                throws XmlPullParserException, IOException {
17340                            synchronized (mPackages) {
17341                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17342                                mSettings.writeLPr();
17343                            }
17344                        }
17345                    } );
17346        } catch (Exception e) {
17347            if (DEBUG_BACKUP) {
17348                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17349            }
17350        }
17351    }
17352
17353    @Override
17354    public byte[] getPermissionGrantBackup(int userId) {
17355        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17356            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17357        }
17358
17359        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17360        try {
17361            final XmlSerializer serializer = new FastXmlSerializer();
17362            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17363            serializer.startDocument(null, true);
17364            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17365
17366            synchronized (mPackages) {
17367                serializeRuntimePermissionGrantsLPr(serializer, userId);
17368            }
17369
17370            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17371            serializer.endDocument();
17372            serializer.flush();
17373        } catch (Exception e) {
17374            if (DEBUG_BACKUP) {
17375                Slog.e(TAG, "Unable to write default apps for backup", e);
17376            }
17377            return null;
17378        }
17379
17380        return dataStream.toByteArray();
17381    }
17382
17383    @Override
17384    public void restorePermissionGrants(byte[] backup, int userId) {
17385        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17386            throw new SecurityException("Only the system may call restorePermissionGrants()");
17387        }
17388
17389        try {
17390            final XmlPullParser parser = Xml.newPullParser();
17391            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17392            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17393                    new BlobXmlRestorer() {
17394                        @Override
17395                        public void apply(XmlPullParser parser, int userId)
17396                                throws XmlPullParserException, IOException {
17397                            synchronized (mPackages) {
17398                                processRestoredPermissionGrantsLPr(parser, userId);
17399                            }
17400                        }
17401                    } );
17402        } catch (Exception e) {
17403            if (DEBUG_BACKUP) {
17404                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17405            }
17406        }
17407    }
17408
17409    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17410            throws IOException {
17411        serializer.startTag(null, TAG_ALL_GRANTS);
17412
17413        final int N = mSettings.mPackages.size();
17414        for (int i = 0; i < N; i++) {
17415            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17416            boolean pkgGrantsKnown = false;
17417
17418            PermissionsState packagePerms = ps.getPermissionsState();
17419
17420            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17421                final int grantFlags = state.getFlags();
17422                // only look at grants that are not system/policy fixed
17423                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17424                    final boolean isGranted = state.isGranted();
17425                    // And only back up the user-twiddled state bits
17426                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17427                        final String packageName = mSettings.mPackages.keyAt(i);
17428                        if (!pkgGrantsKnown) {
17429                            serializer.startTag(null, TAG_GRANT);
17430                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17431                            pkgGrantsKnown = true;
17432                        }
17433
17434                        final boolean userSet =
17435                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17436                        final boolean userFixed =
17437                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17438                        final boolean revoke =
17439                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17440
17441                        serializer.startTag(null, TAG_PERMISSION);
17442                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17443                        if (isGranted) {
17444                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17445                        }
17446                        if (userSet) {
17447                            serializer.attribute(null, ATTR_USER_SET, "true");
17448                        }
17449                        if (userFixed) {
17450                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17451                        }
17452                        if (revoke) {
17453                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17454                        }
17455                        serializer.endTag(null, TAG_PERMISSION);
17456                    }
17457                }
17458            }
17459
17460            if (pkgGrantsKnown) {
17461                serializer.endTag(null, TAG_GRANT);
17462            }
17463        }
17464
17465        serializer.endTag(null, TAG_ALL_GRANTS);
17466    }
17467
17468    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17469            throws XmlPullParserException, IOException {
17470        String pkgName = null;
17471        int outerDepth = parser.getDepth();
17472        int type;
17473        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17474                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17475            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17476                continue;
17477            }
17478
17479            final String tagName = parser.getName();
17480            if (tagName.equals(TAG_GRANT)) {
17481                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17482                if (DEBUG_BACKUP) {
17483                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17484                }
17485            } else if (tagName.equals(TAG_PERMISSION)) {
17486
17487                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17488                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17489
17490                int newFlagSet = 0;
17491                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17492                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17493                }
17494                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17495                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17496                }
17497                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17498                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17499                }
17500                if (DEBUG_BACKUP) {
17501                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17502                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17503                }
17504                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17505                if (ps != null) {
17506                    // Already installed so we apply the grant immediately
17507                    if (DEBUG_BACKUP) {
17508                        Slog.v(TAG, "        + already installed; applying");
17509                    }
17510                    PermissionsState perms = ps.getPermissionsState();
17511                    BasePermission bp = mSettings.mPermissions.get(permName);
17512                    if (bp != null) {
17513                        if (isGranted) {
17514                            perms.grantRuntimePermission(bp, userId);
17515                        }
17516                        if (newFlagSet != 0) {
17517                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17518                        }
17519                    }
17520                } else {
17521                    // Need to wait for post-restore install to apply the grant
17522                    if (DEBUG_BACKUP) {
17523                        Slog.v(TAG, "        - not yet installed; saving for later");
17524                    }
17525                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17526                            isGranted, newFlagSet, userId);
17527                }
17528            } else {
17529                PackageManagerService.reportSettingsProblem(Log.WARN,
17530                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17531                XmlUtils.skipCurrentTag(parser);
17532            }
17533        }
17534
17535        scheduleWriteSettingsLocked();
17536        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17537    }
17538
17539    @Override
17540    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17541            int sourceUserId, int targetUserId, int flags) {
17542        mContext.enforceCallingOrSelfPermission(
17543                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17544        int callingUid = Binder.getCallingUid();
17545        enforceOwnerRights(ownerPackage, callingUid);
17546        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17547        if (intentFilter.countActions() == 0) {
17548            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17549            return;
17550        }
17551        synchronized (mPackages) {
17552            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17553                    ownerPackage, targetUserId, flags);
17554            CrossProfileIntentResolver resolver =
17555                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17556            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17557            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17558            if (existing != null) {
17559                int size = existing.size();
17560                for (int i = 0; i < size; i++) {
17561                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17562                        return;
17563                    }
17564                }
17565            }
17566            resolver.addFilter(newFilter);
17567            scheduleWritePackageRestrictionsLocked(sourceUserId);
17568        }
17569    }
17570
17571    @Override
17572    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17573        mContext.enforceCallingOrSelfPermission(
17574                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17575        int callingUid = Binder.getCallingUid();
17576        enforceOwnerRights(ownerPackage, callingUid);
17577        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17578        synchronized (mPackages) {
17579            CrossProfileIntentResolver resolver =
17580                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17581            ArraySet<CrossProfileIntentFilter> set =
17582                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17583            for (CrossProfileIntentFilter filter : set) {
17584                if (filter.getOwnerPackage().equals(ownerPackage)) {
17585                    resolver.removeFilter(filter);
17586                }
17587            }
17588            scheduleWritePackageRestrictionsLocked(sourceUserId);
17589        }
17590    }
17591
17592    // Enforcing that callingUid is owning pkg on userId
17593    private void enforceOwnerRights(String pkg, int callingUid) {
17594        // The system owns everything.
17595        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17596            return;
17597        }
17598        int callingUserId = UserHandle.getUserId(callingUid);
17599        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17600        if (pi == null) {
17601            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17602                    + callingUserId);
17603        }
17604        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17605            throw new SecurityException("Calling uid " + callingUid
17606                    + " does not own package " + pkg);
17607        }
17608    }
17609
17610    @Override
17611    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17612        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17613    }
17614
17615    private Intent getHomeIntent() {
17616        Intent intent = new Intent(Intent.ACTION_MAIN);
17617        intent.addCategory(Intent.CATEGORY_HOME);
17618        intent.addCategory(Intent.CATEGORY_DEFAULT);
17619        return intent;
17620    }
17621
17622    private IntentFilter getHomeFilter() {
17623        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17624        filter.addCategory(Intent.CATEGORY_HOME);
17625        filter.addCategory(Intent.CATEGORY_DEFAULT);
17626        return filter;
17627    }
17628
17629    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17630            int userId) {
17631        Intent intent  = getHomeIntent();
17632        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17633                PackageManager.GET_META_DATA, userId);
17634        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17635                true, false, false, userId);
17636
17637        allHomeCandidates.clear();
17638        if (list != null) {
17639            for (ResolveInfo ri : list) {
17640                allHomeCandidates.add(ri);
17641            }
17642        }
17643        return (preferred == null || preferred.activityInfo == null)
17644                ? null
17645                : new ComponentName(preferred.activityInfo.packageName,
17646                        preferred.activityInfo.name);
17647    }
17648
17649    @Override
17650    public void setHomeActivity(ComponentName comp, int userId) {
17651        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17652        getHomeActivitiesAsUser(homeActivities, userId);
17653
17654        boolean found = false;
17655
17656        final int size = homeActivities.size();
17657        final ComponentName[] set = new ComponentName[size];
17658        for (int i = 0; i < size; i++) {
17659            final ResolveInfo candidate = homeActivities.get(i);
17660            final ActivityInfo info = candidate.activityInfo;
17661            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17662            set[i] = activityName;
17663            if (!found && activityName.equals(comp)) {
17664                found = true;
17665            }
17666        }
17667        if (!found) {
17668            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17669                    + userId);
17670        }
17671        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17672                set, comp, userId);
17673    }
17674
17675    private @Nullable String getSetupWizardPackageName() {
17676        final Intent intent = new Intent(Intent.ACTION_MAIN);
17677        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17678
17679        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17680                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17681                        | MATCH_DISABLED_COMPONENTS,
17682                UserHandle.myUserId());
17683        if (matches.size() == 1) {
17684            return matches.get(0).getComponentInfo().packageName;
17685        } else {
17686            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17687                    + ": matches=" + matches);
17688            return null;
17689        }
17690    }
17691
17692    private @Nullable String getStorageManagerPackageName() {
17693        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17694
17695        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17696                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17697                        | MATCH_DISABLED_COMPONENTS,
17698                UserHandle.myUserId());
17699        if (matches.size() == 1) {
17700            return matches.get(0).getComponentInfo().packageName;
17701        } else {
17702            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17703                    + matches.size() + ": matches=" + matches);
17704            return null;
17705        }
17706    }
17707
17708    @Override
17709    public void setApplicationEnabledSetting(String appPackageName,
17710            int newState, int flags, int userId, String callingPackage) {
17711        if (!sUserManager.exists(userId)) return;
17712        if (callingPackage == null) {
17713            callingPackage = Integer.toString(Binder.getCallingUid());
17714        }
17715        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17716    }
17717
17718    @Override
17719    public void setComponentEnabledSetting(ComponentName componentName,
17720            int newState, int flags, int userId) {
17721        if (!sUserManager.exists(userId)) return;
17722        setEnabledSetting(componentName.getPackageName(),
17723                componentName.getClassName(), newState, flags, userId, null);
17724    }
17725
17726    private void setEnabledSetting(final String packageName, String className, int newState,
17727            final int flags, int userId, String callingPackage) {
17728        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17729              || newState == COMPONENT_ENABLED_STATE_ENABLED
17730              || newState == COMPONENT_ENABLED_STATE_DISABLED
17731              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17732              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17733            throw new IllegalArgumentException("Invalid new component state: "
17734                    + newState);
17735        }
17736        PackageSetting pkgSetting;
17737        final int uid = Binder.getCallingUid();
17738        final int permission;
17739        if (uid == Process.SYSTEM_UID) {
17740            permission = PackageManager.PERMISSION_GRANTED;
17741        } else {
17742            permission = mContext.checkCallingOrSelfPermission(
17743                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17744        }
17745        enforceCrossUserPermission(uid, userId,
17746                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17747        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17748        boolean sendNow = false;
17749        boolean isApp = (className == null);
17750        String componentName = isApp ? packageName : className;
17751        int packageUid = -1;
17752        ArrayList<String> components;
17753
17754        // writer
17755        synchronized (mPackages) {
17756            pkgSetting = mSettings.mPackages.get(packageName);
17757            if (pkgSetting == null) {
17758                if (className == null) {
17759                    throw new IllegalArgumentException("Unknown package: " + packageName);
17760                }
17761                throw new IllegalArgumentException(
17762                        "Unknown component: " + packageName + "/" + className);
17763            }
17764        }
17765
17766        // Limit who can change which apps
17767        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17768            // Don't allow apps that don't have permission to modify other apps
17769            if (!allowedByPermission) {
17770                throw new SecurityException(
17771                        "Permission Denial: attempt to change component state from pid="
17772                        + Binder.getCallingPid()
17773                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17774            }
17775            // Don't allow changing protected packages.
17776            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17777                throw new SecurityException("Cannot disable a protected package: " + packageName);
17778            }
17779        }
17780
17781        synchronized (mPackages) {
17782            if (uid == Process.SHELL_UID) {
17783                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17784                int oldState = pkgSetting.getEnabled(userId);
17785                if (className == null
17786                    &&
17787                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17788                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17789                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17790                    &&
17791                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17792                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17793                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17794                    // ok
17795                } else {
17796                    throw new SecurityException(
17797                            "Shell cannot change component state for " + packageName + "/"
17798                            + className + " to " + newState);
17799                }
17800            }
17801            if (className == null) {
17802                // We're dealing with an application/package level state change
17803                if (pkgSetting.getEnabled(userId) == newState) {
17804                    // Nothing to do
17805                    return;
17806                }
17807                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17808                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17809                    // Don't care about who enables an app.
17810                    callingPackage = null;
17811                }
17812                pkgSetting.setEnabled(newState, userId, callingPackage);
17813                // pkgSetting.pkg.mSetEnabled = newState;
17814            } else {
17815                // We're dealing with a component level state change
17816                // First, verify that this is a valid class name.
17817                PackageParser.Package pkg = pkgSetting.pkg;
17818                if (pkg == null || !pkg.hasComponentClassName(className)) {
17819                    if (pkg != null &&
17820                            pkg.applicationInfo.targetSdkVersion >=
17821                                    Build.VERSION_CODES.JELLY_BEAN) {
17822                        throw new IllegalArgumentException("Component class " + className
17823                                + " does not exist in " + packageName);
17824                    } else {
17825                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17826                                + className + " does not exist in " + packageName);
17827                    }
17828                }
17829                switch (newState) {
17830                case COMPONENT_ENABLED_STATE_ENABLED:
17831                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17832                        return;
17833                    }
17834                    break;
17835                case COMPONENT_ENABLED_STATE_DISABLED:
17836                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17837                        return;
17838                    }
17839                    break;
17840                case COMPONENT_ENABLED_STATE_DEFAULT:
17841                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17842                        return;
17843                    }
17844                    break;
17845                default:
17846                    Slog.e(TAG, "Invalid new component state: " + newState);
17847                    return;
17848                }
17849            }
17850            scheduleWritePackageRestrictionsLocked(userId);
17851            components = mPendingBroadcasts.get(userId, packageName);
17852            final boolean newPackage = components == null;
17853            if (newPackage) {
17854                components = new ArrayList<String>();
17855            }
17856            if (!components.contains(componentName)) {
17857                components.add(componentName);
17858            }
17859            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17860                sendNow = true;
17861                // Purge entry from pending broadcast list if another one exists already
17862                // since we are sending one right away.
17863                mPendingBroadcasts.remove(userId, packageName);
17864            } else {
17865                if (newPackage) {
17866                    mPendingBroadcasts.put(userId, packageName, components);
17867                }
17868                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17869                    // Schedule a message
17870                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17871                }
17872            }
17873        }
17874
17875        long callingId = Binder.clearCallingIdentity();
17876        try {
17877            if (sendNow) {
17878                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17879                sendPackageChangedBroadcast(packageName,
17880                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17881            }
17882        } finally {
17883            Binder.restoreCallingIdentity(callingId);
17884        }
17885    }
17886
17887    @Override
17888    public void flushPackageRestrictionsAsUser(int userId) {
17889        if (!sUserManager.exists(userId)) {
17890            return;
17891        }
17892        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17893                false /* checkShell */, "flushPackageRestrictions");
17894        synchronized (mPackages) {
17895            mSettings.writePackageRestrictionsLPr(userId);
17896            mDirtyUsers.remove(userId);
17897            if (mDirtyUsers.isEmpty()) {
17898                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17899            }
17900        }
17901    }
17902
17903    private void sendPackageChangedBroadcast(String packageName,
17904            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17905        if (DEBUG_INSTALL)
17906            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17907                    + componentNames);
17908        Bundle extras = new Bundle(4);
17909        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17910        String nameList[] = new String[componentNames.size()];
17911        componentNames.toArray(nameList);
17912        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17913        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17914        extras.putInt(Intent.EXTRA_UID, packageUid);
17915        // If this is not reporting a change of the overall package, then only send it
17916        // to registered receivers.  We don't want to launch a swath of apps for every
17917        // little component state change.
17918        final int flags = !componentNames.contains(packageName)
17919                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17920        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17921                new int[] {UserHandle.getUserId(packageUid)});
17922    }
17923
17924    @Override
17925    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17926        if (!sUserManager.exists(userId)) return;
17927        final int uid = Binder.getCallingUid();
17928        final int permission = mContext.checkCallingOrSelfPermission(
17929                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17930        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17931        enforceCrossUserPermission(uid, userId,
17932                true /* requireFullPermission */, true /* checkShell */, "stop package");
17933        // writer
17934        synchronized (mPackages) {
17935            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17936                    allowedByPermission, uid, userId)) {
17937                scheduleWritePackageRestrictionsLocked(userId);
17938            }
17939        }
17940    }
17941
17942    @Override
17943    public String getInstallerPackageName(String packageName) {
17944        // reader
17945        synchronized (mPackages) {
17946            return mSettings.getInstallerPackageNameLPr(packageName);
17947        }
17948    }
17949
17950    public boolean isOrphaned(String packageName) {
17951        // reader
17952        synchronized (mPackages) {
17953            return mSettings.isOrphaned(packageName);
17954        }
17955    }
17956
17957    @Override
17958    public int getApplicationEnabledSetting(String packageName, int userId) {
17959        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17960        int uid = Binder.getCallingUid();
17961        enforceCrossUserPermission(uid, userId,
17962                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17963        // reader
17964        synchronized (mPackages) {
17965            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17966        }
17967    }
17968
17969    @Override
17970    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17971        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17972        int uid = Binder.getCallingUid();
17973        enforceCrossUserPermission(uid, userId,
17974                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17975        // reader
17976        synchronized (mPackages) {
17977            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17978        }
17979    }
17980
17981    @Override
17982    public void enterSafeMode() {
17983        enforceSystemOrRoot("Only the system can request entering safe mode");
17984
17985        if (!mSystemReady) {
17986            mSafeMode = true;
17987        }
17988    }
17989
17990    @Override
17991    public void systemReady() {
17992        mSystemReady = true;
17993
17994        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
17995        // disabled after already being started.
17996        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
17997                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
17998
17999        // Read the compatibilty setting when the system is ready.
18000        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18001                mContext.getContentResolver(),
18002                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18003        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18004        if (DEBUG_SETTINGS) {
18005            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18006        }
18007
18008        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18009
18010        synchronized (mPackages) {
18011            // Verify that all of the preferred activity components actually
18012            // exist.  It is possible for applications to be updated and at
18013            // that point remove a previously declared activity component that
18014            // had been set as a preferred activity.  We try to clean this up
18015            // the next time we encounter that preferred activity, but it is
18016            // possible for the user flow to never be able to return to that
18017            // situation so here we do a sanity check to make sure we haven't
18018            // left any junk around.
18019            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18020            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18021                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18022                removed.clear();
18023                for (PreferredActivity pa : pir.filterSet()) {
18024                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18025                        removed.add(pa);
18026                    }
18027                }
18028                if (removed.size() > 0) {
18029                    for (int r=0; r<removed.size(); r++) {
18030                        PreferredActivity pa = removed.get(r);
18031                        Slog.w(TAG, "Removing dangling preferred activity: "
18032                                + pa.mPref.mComponent);
18033                        pir.removeFilter(pa);
18034                    }
18035                    mSettings.writePackageRestrictionsLPr(
18036                            mSettings.mPreferredActivities.keyAt(i));
18037                }
18038            }
18039
18040            for (int userId : UserManagerService.getInstance().getUserIds()) {
18041                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18042                    grantPermissionsUserIds = ArrayUtils.appendInt(
18043                            grantPermissionsUserIds, userId);
18044                }
18045            }
18046        }
18047        sUserManager.systemReady();
18048
18049        // If we upgraded grant all default permissions before kicking off.
18050        for (int userId : grantPermissionsUserIds) {
18051            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18052        }
18053
18054        // If we did not grant default permissions, we preload from this the
18055        // default permission exceptions lazily to ensure we don't hit the
18056        // disk on a new user creation.
18057        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18058            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18059        }
18060
18061        // Kick off any messages waiting for system ready
18062        if (mPostSystemReadyMessages != null) {
18063            for (Message msg : mPostSystemReadyMessages) {
18064                msg.sendToTarget();
18065            }
18066            mPostSystemReadyMessages = null;
18067        }
18068
18069        // Watch for external volumes that come and go over time
18070        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18071        storage.registerListener(mStorageListener);
18072
18073        mInstallerService.systemReady();
18074        mPackageDexOptimizer.systemReady();
18075
18076        MountServiceInternal mountServiceInternal = LocalServices.getService(
18077                MountServiceInternal.class);
18078        mountServiceInternal.addExternalStoragePolicy(
18079                new MountServiceInternal.ExternalStorageMountPolicy() {
18080            @Override
18081            public int getMountMode(int uid, String packageName) {
18082                if (Process.isIsolated(uid)) {
18083                    return Zygote.MOUNT_EXTERNAL_NONE;
18084                }
18085                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18086                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18087                }
18088                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18089                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18090                }
18091                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18092                    return Zygote.MOUNT_EXTERNAL_READ;
18093                }
18094                return Zygote.MOUNT_EXTERNAL_WRITE;
18095            }
18096
18097            @Override
18098            public boolean hasExternalStorage(int uid, String packageName) {
18099                return true;
18100            }
18101        });
18102
18103        // Now that we're mostly running, clean up stale users and apps
18104        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18105        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18106    }
18107
18108    @Override
18109    public boolean isSafeMode() {
18110        return mSafeMode;
18111    }
18112
18113    @Override
18114    public boolean hasSystemUidErrors() {
18115        return mHasSystemUidErrors;
18116    }
18117
18118    static String arrayToString(int[] array) {
18119        StringBuffer buf = new StringBuffer(128);
18120        buf.append('[');
18121        if (array != null) {
18122            for (int i=0; i<array.length; i++) {
18123                if (i > 0) buf.append(", ");
18124                buf.append(array[i]);
18125            }
18126        }
18127        buf.append(']');
18128        return buf.toString();
18129    }
18130
18131    static class DumpState {
18132        public static final int DUMP_LIBS = 1 << 0;
18133        public static final int DUMP_FEATURES = 1 << 1;
18134        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18135        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18136        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18137        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18138        public static final int DUMP_PERMISSIONS = 1 << 6;
18139        public static final int DUMP_PACKAGES = 1 << 7;
18140        public static final int DUMP_SHARED_USERS = 1 << 8;
18141        public static final int DUMP_MESSAGES = 1 << 9;
18142        public static final int DUMP_PROVIDERS = 1 << 10;
18143        public static final int DUMP_VERIFIERS = 1 << 11;
18144        public static final int DUMP_PREFERRED = 1 << 12;
18145        public static final int DUMP_PREFERRED_XML = 1 << 13;
18146        public static final int DUMP_KEYSETS = 1 << 14;
18147        public static final int DUMP_VERSION = 1 << 15;
18148        public static final int DUMP_INSTALLS = 1 << 16;
18149        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18150        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18151        public static final int DUMP_FROZEN = 1 << 19;
18152        public static final int DUMP_DEXOPT = 1 << 20;
18153        public static final int DUMP_COMPILER_STATS = 1 << 21;
18154
18155        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18156
18157        private int mTypes;
18158
18159        private int mOptions;
18160
18161        private boolean mTitlePrinted;
18162
18163        private SharedUserSetting mSharedUser;
18164
18165        public boolean isDumping(int type) {
18166            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18167                return true;
18168            }
18169
18170            return (mTypes & type) != 0;
18171        }
18172
18173        public void setDump(int type) {
18174            mTypes |= type;
18175        }
18176
18177        public boolean isOptionEnabled(int option) {
18178            return (mOptions & option) != 0;
18179        }
18180
18181        public void setOptionEnabled(int option) {
18182            mOptions |= option;
18183        }
18184
18185        public boolean onTitlePrinted() {
18186            final boolean printed = mTitlePrinted;
18187            mTitlePrinted = true;
18188            return printed;
18189        }
18190
18191        public boolean getTitlePrinted() {
18192            return mTitlePrinted;
18193        }
18194
18195        public void setTitlePrinted(boolean enabled) {
18196            mTitlePrinted = enabled;
18197        }
18198
18199        public SharedUserSetting getSharedUser() {
18200            return mSharedUser;
18201        }
18202
18203        public void setSharedUser(SharedUserSetting user) {
18204            mSharedUser = user;
18205        }
18206    }
18207
18208    @Override
18209    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18210            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18211        (new PackageManagerShellCommand(this)).exec(
18212                this, in, out, err, args, resultReceiver);
18213    }
18214
18215    @Override
18216    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18217        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18218                != PackageManager.PERMISSION_GRANTED) {
18219            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18220                    + Binder.getCallingPid()
18221                    + ", uid=" + Binder.getCallingUid()
18222                    + " without permission "
18223                    + android.Manifest.permission.DUMP);
18224            return;
18225        }
18226
18227        DumpState dumpState = new DumpState();
18228        boolean fullPreferred = false;
18229        boolean checkin = false;
18230
18231        String packageName = null;
18232        ArraySet<String> permissionNames = null;
18233
18234        int opti = 0;
18235        while (opti < args.length) {
18236            String opt = args[opti];
18237            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18238                break;
18239            }
18240            opti++;
18241
18242            if ("-a".equals(opt)) {
18243                // Right now we only know how to print all.
18244            } else if ("-h".equals(opt)) {
18245                pw.println("Package manager dump options:");
18246                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18247                pw.println("    --checkin: dump for a checkin");
18248                pw.println("    -f: print details of intent filters");
18249                pw.println("    -h: print this help");
18250                pw.println("  cmd may be one of:");
18251                pw.println("    l[ibraries]: list known shared libraries");
18252                pw.println("    f[eatures]: list device features");
18253                pw.println("    k[eysets]: print known keysets");
18254                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18255                pw.println("    perm[issions]: dump permissions");
18256                pw.println("    permission [name ...]: dump declaration and use of given permission");
18257                pw.println("    pref[erred]: print preferred package settings");
18258                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18259                pw.println("    prov[iders]: dump content providers");
18260                pw.println("    p[ackages]: dump installed packages");
18261                pw.println("    s[hared-users]: dump shared user IDs");
18262                pw.println("    m[essages]: print collected runtime messages");
18263                pw.println("    v[erifiers]: print package verifier info");
18264                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18265                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18266                pw.println("    version: print database version info");
18267                pw.println("    write: write current settings now");
18268                pw.println("    installs: details about install sessions");
18269                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18270                pw.println("    dexopt: dump dexopt state");
18271                pw.println("    compiler-stats: dump compiler statistics");
18272                pw.println("    <package.name>: info about given package");
18273                return;
18274            } else if ("--checkin".equals(opt)) {
18275                checkin = true;
18276            } else if ("-f".equals(opt)) {
18277                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18278            } else {
18279                pw.println("Unknown argument: " + opt + "; use -h for help");
18280            }
18281        }
18282
18283        // Is the caller requesting to dump a particular piece of data?
18284        if (opti < args.length) {
18285            String cmd = args[opti];
18286            opti++;
18287            // Is this a package name?
18288            if ("android".equals(cmd) || cmd.contains(".")) {
18289                packageName = cmd;
18290                // When dumping a single package, we always dump all of its
18291                // filter information since the amount of data will be reasonable.
18292                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18293            } else if ("check-permission".equals(cmd)) {
18294                if (opti >= args.length) {
18295                    pw.println("Error: check-permission missing permission argument");
18296                    return;
18297                }
18298                String perm = args[opti];
18299                opti++;
18300                if (opti >= args.length) {
18301                    pw.println("Error: check-permission missing package argument");
18302                    return;
18303                }
18304                String pkg = args[opti];
18305                opti++;
18306                int user = UserHandle.getUserId(Binder.getCallingUid());
18307                if (opti < args.length) {
18308                    try {
18309                        user = Integer.parseInt(args[opti]);
18310                    } catch (NumberFormatException e) {
18311                        pw.println("Error: check-permission user argument is not a number: "
18312                                + args[opti]);
18313                        return;
18314                    }
18315                }
18316                pw.println(checkPermission(perm, pkg, user));
18317                return;
18318            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18319                dumpState.setDump(DumpState.DUMP_LIBS);
18320            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18321                dumpState.setDump(DumpState.DUMP_FEATURES);
18322            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18323                if (opti >= args.length) {
18324                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18325                            | DumpState.DUMP_SERVICE_RESOLVERS
18326                            | DumpState.DUMP_RECEIVER_RESOLVERS
18327                            | DumpState.DUMP_CONTENT_RESOLVERS);
18328                } else {
18329                    while (opti < args.length) {
18330                        String name = args[opti];
18331                        if ("a".equals(name) || "activity".equals(name)) {
18332                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18333                        } else if ("s".equals(name) || "service".equals(name)) {
18334                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18335                        } else if ("r".equals(name) || "receiver".equals(name)) {
18336                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18337                        } else if ("c".equals(name) || "content".equals(name)) {
18338                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18339                        } else {
18340                            pw.println("Error: unknown resolver table type: " + name);
18341                            return;
18342                        }
18343                        opti++;
18344                    }
18345                }
18346            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18347                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18348            } else if ("permission".equals(cmd)) {
18349                if (opti >= args.length) {
18350                    pw.println("Error: permission requires permission name");
18351                    return;
18352                }
18353                permissionNames = new ArraySet<>();
18354                while (opti < args.length) {
18355                    permissionNames.add(args[opti]);
18356                    opti++;
18357                }
18358                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18359                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18360            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18361                dumpState.setDump(DumpState.DUMP_PREFERRED);
18362            } else if ("preferred-xml".equals(cmd)) {
18363                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18364                if (opti < args.length && "--full".equals(args[opti])) {
18365                    fullPreferred = true;
18366                    opti++;
18367                }
18368            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18369                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18370            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18371                dumpState.setDump(DumpState.DUMP_PACKAGES);
18372            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18373                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18374            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18375                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18376            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18377                dumpState.setDump(DumpState.DUMP_MESSAGES);
18378            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18379                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18380            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18381                    || "intent-filter-verifiers".equals(cmd)) {
18382                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18383            } else if ("version".equals(cmd)) {
18384                dumpState.setDump(DumpState.DUMP_VERSION);
18385            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18386                dumpState.setDump(DumpState.DUMP_KEYSETS);
18387            } else if ("installs".equals(cmd)) {
18388                dumpState.setDump(DumpState.DUMP_INSTALLS);
18389            } else if ("frozen".equals(cmd)) {
18390                dumpState.setDump(DumpState.DUMP_FROZEN);
18391            } else if ("dexopt".equals(cmd)) {
18392                dumpState.setDump(DumpState.DUMP_DEXOPT);
18393            } else if ("compiler-stats".equals(cmd)) {
18394                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18395            } else if ("write".equals(cmd)) {
18396                synchronized (mPackages) {
18397                    mSettings.writeLPr();
18398                    pw.println("Settings written.");
18399                    return;
18400                }
18401            }
18402        }
18403
18404        if (checkin) {
18405            pw.println("vers,1");
18406        }
18407
18408        // reader
18409        synchronized (mPackages) {
18410            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18411                if (!checkin) {
18412                    if (dumpState.onTitlePrinted())
18413                        pw.println();
18414                    pw.println("Database versions:");
18415                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18416                }
18417            }
18418
18419            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18420                if (!checkin) {
18421                    if (dumpState.onTitlePrinted())
18422                        pw.println();
18423                    pw.println("Verifiers:");
18424                    pw.print("  Required: ");
18425                    pw.print(mRequiredVerifierPackage);
18426                    pw.print(" (uid=");
18427                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18428                            UserHandle.USER_SYSTEM));
18429                    pw.println(")");
18430                } else if (mRequiredVerifierPackage != null) {
18431                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18432                    pw.print(",");
18433                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18434                            UserHandle.USER_SYSTEM));
18435                }
18436            }
18437
18438            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18439                    packageName == null) {
18440                if (mIntentFilterVerifierComponent != null) {
18441                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18442                    if (!checkin) {
18443                        if (dumpState.onTitlePrinted())
18444                            pw.println();
18445                        pw.println("Intent Filter Verifier:");
18446                        pw.print("  Using: ");
18447                        pw.print(verifierPackageName);
18448                        pw.print(" (uid=");
18449                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18450                                UserHandle.USER_SYSTEM));
18451                        pw.println(")");
18452                    } else if (verifierPackageName != null) {
18453                        pw.print("ifv,"); pw.print(verifierPackageName);
18454                        pw.print(",");
18455                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18456                                UserHandle.USER_SYSTEM));
18457                    }
18458                } else {
18459                    pw.println();
18460                    pw.println("No Intent Filter Verifier available!");
18461                }
18462            }
18463
18464            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18465                boolean printedHeader = false;
18466                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18467                while (it.hasNext()) {
18468                    String name = it.next();
18469                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18470                    if (!checkin) {
18471                        if (!printedHeader) {
18472                            if (dumpState.onTitlePrinted())
18473                                pw.println();
18474                            pw.println("Libraries:");
18475                            printedHeader = true;
18476                        }
18477                        pw.print("  ");
18478                    } else {
18479                        pw.print("lib,");
18480                    }
18481                    pw.print(name);
18482                    if (!checkin) {
18483                        pw.print(" -> ");
18484                    }
18485                    if (ent.path != null) {
18486                        if (!checkin) {
18487                            pw.print("(jar) ");
18488                            pw.print(ent.path);
18489                        } else {
18490                            pw.print(",jar,");
18491                            pw.print(ent.path);
18492                        }
18493                    } else {
18494                        if (!checkin) {
18495                            pw.print("(apk) ");
18496                            pw.print(ent.apk);
18497                        } else {
18498                            pw.print(",apk,");
18499                            pw.print(ent.apk);
18500                        }
18501                    }
18502                    pw.println();
18503                }
18504            }
18505
18506            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18507                if (dumpState.onTitlePrinted())
18508                    pw.println();
18509                if (!checkin) {
18510                    pw.println("Features:");
18511                }
18512
18513                for (FeatureInfo feat : mAvailableFeatures.values()) {
18514                    if (checkin) {
18515                        pw.print("feat,");
18516                        pw.print(feat.name);
18517                        pw.print(",");
18518                        pw.println(feat.version);
18519                    } else {
18520                        pw.print("  ");
18521                        pw.print(feat.name);
18522                        if (feat.version > 0) {
18523                            pw.print(" version=");
18524                            pw.print(feat.version);
18525                        }
18526                        pw.println();
18527                    }
18528                }
18529            }
18530
18531            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18532                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18533                        : "Activity Resolver Table:", "  ", packageName,
18534                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18535                    dumpState.setTitlePrinted(true);
18536                }
18537            }
18538            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18539                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18540                        : "Receiver Resolver Table:", "  ", packageName,
18541                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18542                    dumpState.setTitlePrinted(true);
18543                }
18544            }
18545            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18546                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18547                        : "Service Resolver Table:", "  ", packageName,
18548                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18549                    dumpState.setTitlePrinted(true);
18550                }
18551            }
18552            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18553                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18554                        : "Provider Resolver Table:", "  ", packageName,
18555                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18556                    dumpState.setTitlePrinted(true);
18557                }
18558            }
18559
18560            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18561                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18562                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18563                    int user = mSettings.mPreferredActivities.keyAt(i);
18564                    if (pir.dump(pw,
18565                            dumpState.getTitlePrinted()
18566                                ? "\nPreferred Activities User " + user + ":"
18567                                : "Preferred Activities User " + user + ":", "  ",
18568                            packageName, true, false)) {
18569                        dumpState.setTitlePrinted(true);
18570                    }
18571                }
18572            }
18573
18574            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18575                pw.flush();
18576                FileOutputStream fout = new FileOutputStream(fd);
18577                BufferedOutputStream str = new BufferedOutputStream(fout);
18578                XmlSerializer serializer = new FastXmlSerializer();
18579                try {
18580                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18581                    serializer.startDocument(null, true);
18582                    serializer.setFeature(
18583                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18584                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18585                    serializer.endDocument();
18586                    serializer.flush();
18587                } catch (IllegalArgumentException e) {
18588                    pw.println("Failed writing: " + e);
18589                } catch (IllegalStateException e) {
18590                    pw.println("Failed writing: " + e);
18591                } catch (IOException e) {
18592                    pw.println("Failed writing: " + e);
18593                }
18594            }
18595
18596            if (!checkin
18597                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18598                    && packageName == null) {
18599                pw.println();
18600                int count = mSettings.mPackages.size();
18601                if (count == 0) {
18602                    pw.println("No applications!");
18603                    pw.println();
18604                } else {
18605                    final String prefix = "  ";
18606                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18607                    if (allPackageSettings.size() == 0) {
18608                        pw.println("No domain preferred apps!");
18609                        pw.println();
18610                    } else {
18611                        pw.println("App verification status:");
18612                        pw.println();
18613                        count = 0;
18614                        for (PackageSetting ps : allPackageSettings) {
18615                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18616                            if (ivi == null || ivi.getPackageName() == null) continue;
18617                            pw.println(prefix + "Package: " + ivi.getPackageName());
18618                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18619                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18620                            pw.println();
18621                            count++;
18622                        }
18623                        if (count == 0) {
18624                            pw.println(prefix + "No app verification established.");
18625                            pw.println();
18626                        }
18627                        for (int userId : sUserManager.getUserIds()) {
18628                            pw.println("App linkages for user " + userId + ":");
18629                            pw.println();
18630                            count = 0;
18631                            for (PackageSetting ps : allPackageSettings) {
18632                                final long status = ps.getDomainVerificationStatusForUser(userId);
18633                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18634                                    continue;
18635                                }
18636                                pw.println(prefix + "Package: " + ps.name);
18637                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18638                                String statusStr = IntentFilterVerificationInfo.
18639                                        getStatusStringFromValue(status);
18640                                pw.println(prefix + "Status:  " + statusStr);
18641                                pw.println();
18642                                count++;
18643                            }
18644                            if (count == 0) {
18645                                pw.println(prefix + "No configured app linkages.");
18646                                pw.println();
18647                            }
18648                        }
18649                    }
18650                }
18651            }
18652
18653            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18654                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18655                if (packageName == null && permissionNames == null) {
18656                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18657                        if (iperm == 0) {
18658                            if (dumpState.onTitlePrinted())
18659                                pw.println();
18660                            pw.println("AppOp Permissions:");
18661                        }
18662                        pw.print("  AppOp Permission ");
18663                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18664                        pw.println(":");
18665                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18666                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18667                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18668                        }
18669                    }
18670                }
18671            }
18672
18673            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18674                boolean printedSomething = false;
18675                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18676                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18677                        continue;
18678                    }
18679                    if (!printedSomething) {
18680                        if (dumpState.onTitlePrinted())
18681                            pw.println();
18682                        pw.println("Registered ContentProviders:");
18683                        printedSomething = true;
18684                    }
18685                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18686                    pw.print("    "); pw.println(p.toString());
18687                }
18688                printedSomething = false;
18689                for (Map.Entry<String, PackageParser.Provider> entry :
18690                        mProvidersByAuthority.entrySet()) {
18691                    PackageParser.Provider p = entry.getValue();
18692                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18693                        continue;
18694                    }
18695                    if (!printedSomething) {
18696                        if (dumpState.onTitlePrinted())
18697                            pw.println();
18698                        pw.println("ContentProvider Authorities:");
18699                        printedSomething = true;
18700                    }
18701                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18702                    pw.print("    "); pw.println(p.toString());
18703                    if (p.info != null && p.info.applicationInfo != null) {
18704                        final String appInfo = p.info.applicationInfo.toString();
18705                        pw.print("      applicationInfo="); pw.println(appInfo);
18706                    }
18707                }
18708            }
18709
18710            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18711                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18712            }
18713
18714            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18715                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18716            }
18717
18718            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18719                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18720            }
18721
18722            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18723                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18724            }
18725
18726            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18727                // XXX should handle packageName != null by dumping only install data that
18728                // the given package is involved with.
18729                if (dumpState.onTitlePrinted()) pw.println();
18730                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18731            }
18732
18733            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18734                // XXX should handle packageName != null by dumping only install data that
18735                // the given package is involved with.
18736                if (dumpState.onTitlePrinted()) pw.println();
18737
18738                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18739                ipw.println();
18740                ipw.println("Frozen packages:");
18741                ipw.increaseIndent();
18742                if (mFrozenPackages.size() == 0) {
18743                    ipw.println("(none)");
18744                } else {
18745                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18746                        ipw.println(mFrozenPackages.valueAt(i));
18747                    }
18748                }
18749                ipw.decreaseIndent();
18750            }
18751
18752            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18753                if (dumpState.onTitlePrinted()) pw.println();
18754                dumpDexoptStateLPr(pw, packageName);
18755            }
18756
18757            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18758                if (dumpState.onTitlePrinted()) pw.println();
18759                dumpCompilerStatsLPr(pw, packageName);
18760            }
18761
18762            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18763                if (dumpState.onTitlePrinted()) pw.println();
18764                mSettings.dumpReadMessagesLPr(pw, dumpState);
18765
18766                pw.println();
18767                pw.println("Package warning messages:");
18768                BufferedReader in = null;
18769                String line = null;
18770                try {
18771                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18772                    while ((line = in.readLine()) != null) {
18773                        if (line.contains("ignored: updated version")) continue;
18774                        pw.println(line);
18775                    }
18776                } catch (IOException ignored) {
18777                } finally {
18778                    IoUtils.closeQuietly(in);
18779                }
18780            }
18781
18782            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18783                BufferedReader in = null;
18784                String line = null;
18785                try {
18786                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18787                    while ((line = in.readLine()) != null) {
18788                        if (line.contains("ignored: updated version")) continue;
18789                        pw.print("msg,");
18790                        pw.println(line);
18791                    }
18792                } catch (IOException ignored) {
18793                } finally {
18794                    IoUtils.closeQuietly(in);
18795                }
18796            }
18797        }
18798    }
18799
18800    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18801        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18802        ipw.println();
18803        ipw.println("Dexopt state:");
18804        ipw.increaseIndent();
18805        Collection<PackageParser.Package> packages = null;
18806        if (packageName != null) {
18807            PackageParser.Package targetPackage = mPackages.get(packageName);
18808            if (targetPackage != null) {
18809                packages = Collections.singletonList(targetPackage);
18810            } else {
18811                ipw.println("Unable to find package: " + packageName);
18812                return;
18813            }
18814        } else {
18815            packages = mPackages.values();
18816        }
18817
18818        for (PackageParser.Package pkg : packages) {
18819            ipw.println("[" + pkg.packageName + "]");
18820            ipw.increaseIndent();
18821            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18822            ipw.decreaseIndent();
18823        }
18824    }
18825
18826    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18827        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18828        ipw.println();
18829        ipw.println("Compiler stats:");
18830        ipw.increaseIndent();
18831        Collection<PackageParser.Package> packages = null;
18832        if (packageName != null) {
18833            PackageParser.Package targetPackage = mPackages.get(packageName);
18834            if (targetPackage != null) {
18835                packages = Collections.singletonList(targetPackage);
18836            } else {
18837                ipw.println("Unable to find package: " + packageName);
18838                return;
18839            }
18840        } else {
18841            packages = mPackages.values();
18842        }
18843
18844        for (PackageParser.Package pkg : packages) {
18845            ipw.println("[" + pkg.packageName + "]");
18846            ipw.increaseIndent();
18847
18848            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18849            if (stats == null) {
18850                ipw.println("(No recorded stats)");
18851            } else {
18852                stats.dump(ipw);
18853            }
18854            ipw.decreaseIndent();
18855        }
18856    }
18857
18858    private String dumpDomainString(String packageName) {
18859        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18860                .getList();
18861        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18862
18863        ArraySet<String> result = new ArraySet<>();
18864        if (iviList.size() > 0) {
18865            for (IntentFilterVerificationInfo ivi : iviList) {
18866                for (String host : ivi.getDomains()) {
18867                    result.add(host);
18868                }
18869            }
18870        }
18871        if (filters != null && filters.size() > 0) {
18872            for (IntentFilter filter : filters) {
18873                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18874                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18875                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18876                    result.addAll(filter.getHostsList());
18877                }
18878            }
18879        }
18880
18881        StringBuilder sb = new StringBuilder(result.size() * 16);
18882        for (String domain : result) {
18883            if (sb.length() > 0) sb.append(" ");
18884            sb.append(domain);
18885        }
18886        return sb.toString();
18887    }
18888
18889    // ------- apps on sdcard specific code -------
18890    static final boolean DEBUG_SD_INSTALL = false;
18891
18892    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18893
18894    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18895
18896    private boolean mMediaMounted = false;
18897
18898    static String getEncryptKey() {
18899        try {
18900            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18901                    SD_ENCRYPTION_KEYSTORE_NAME);
18902            if (sdEncKey == null) {
18903                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18904                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18905                if (sdEncKey == null) {
18906                    Slog.e(TAG, "Failed to create encryption keys");
18907                    return null;
18908                }
18909            }
18910            return sdEncKey;
18911        } catch (NoSuchAlgorithmException nsae) {
18912            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18913            return null;
18914        } catch (IOException ioe) {
18915            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18916            return null;
18917        }
18918    }
18919
18920    /*
18921     * Update media status on PackageManager.
18922     */
18923    @Override
18924    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18925        int callingUid = Binder.getCallingUid();
18926        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18927            throw new SecurityException("Media status can only be updated by the system");
18928        }
18929        // reader; this apparently protects mMediaMounted, but should probably
18930        // be a different lock in that case.
18931        synchronized (mPackages) {
18932            Log.i(TAG, "Updating external media status from "
18933                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18934                    + (mediaStatus ? "mounted" : "unmounted"));
18935            if (DEBUG_SD_INSTALL)
18936                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18937                        + ", mMediaMounted=" + mMediaMounted);
18938            if (mediaStatus == mMediaMounted) {
18939                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18940                        : 0, -1);
18941                mHandler.sendMessage(msg);
18942                return;
18943            }
18944            mMediaMounted = mediaStatus;
18945        }
18946        // Queue up an async operation since the package installation may take a
18947        // little while.
18948        mHandler.post(new Runnable() {
18949            public void run() {
18950                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18951            }
18952        });
18953    }
18954
18955    /**
18956     * Called by MountService when the initial ASECs to scan are available.
18957     * Should block until all the ASEC containers are finished being scanned.
18958     */
18959    public void scanAvailableAsecs() {
18960        updateExternalMediaStatusInner(true, false, false);
18961    }
18962
18963    /*
18964     * Collect information of applications on external media, map them against
18965     * existing containers and update information based on current mount status.
18966     * Please note that we always have to report status if reportStatus has been
18967     * set to true especially when unloading packages.
18968     */
18969    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18970            boolean externalStorage) {
18971        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18972        int[] uidArr = EmptyArray.INT;
18973
18974        final String[] list = PackageHelper.getSecureContainerList();
18975        if (ArrayUtils.isEmpty(list)) {
18976            Log.i(TAG, "No secure containers found");
18977        } else {
18978            // Process list of secure containers and categorize them
18979            // as active or stale based on their package internal state.
18980
18981            // reader
18982            synchronized (mPackages) {
18983                for (String cid : list) {
18984                    // Leave stages untouched for now; installer service owns them
18985                    if (PackageInstallerService.isStageName(cid)) continue;
18986
18987                    if (DEBUG_SD_INSTALL)
18988                        Log.i(TAG, "Processing container " + cid);
18989                    String pkgName = getAsecPackageName(cid);
18990                    if (pkgName == null) {
18991                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18992                        continue;
18993                    }
18994                    if (DEBUG_SD_INSTALL)
18995                        Log.i(TAG, "Looking for pkg : " + pkgName);
18996
18997                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18998                    if (ps == null) {
18999                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19000                        continue;
19001                    }
19002
19003                    /*
19004                     * Skip packages that are not external if we're unmounting
19005                     * external storage.
19006                     */
19007                    if (externalStorage && !isMounted && !isExternal(ps)) {
19008                        continue;
19009                    }
19010
19011                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19012                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19013                    // The package status is changed only if the code path
19014                    // matches between settings and the container id.
19015                    if (ps.codePathString != null
19016                            && ps.codePathString.startsWith(args.getCodePath())) {
19017                        if (DEBUG_SD_INSTALL) {
19018                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19019                                    + " at code path: " + ps.codePathString);
19020                        }
19021
19022                        // We do have a valid package installed on sdcard
19023                        processCids.put(args, ps.codePathString);
19024                        final int uid = ps.appId;
19025                        if (uid != -1) {
19026                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19027                        }
19028                    } else {
19029                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19030                                + ps.codePathString);
19031                    }
19032                }
19033            }
19034
19035            Arrays.sort(uidArr);
19036        }
19037
19038        // Process packages with valid entries.
19039        if (isMounted) {
19040            if (DEBUG_SD_INSTALL)
19041                Log.i(TAG, "Loading packages");
19042            loadMediaPackages(processCids, uidArr, externalStorage);
19043            startCleaningPackages();
19044            mInstallerService.onSecureContainersAvailable();
19045        } else {
19046            if (DEBUG_SD_INSTALL)
19047                Log.i(TAG, "Unloading packages");
19048            unloadMediaPackages(processCids, uidArr, reportStatus);
19049        }
19050    }
19051
19052    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19053            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19054        final int size = infos.size();
19055        final String[] packageNames = new String[size];
19056        final int[] packageUids = new int[size];
19057        for (int i = 0; i < size; i++) {
19058            final ApplicationInfo info = infos.get(i);
19059            packageNames[i] = info.packageName;
19060            packageUids[i] = info.uid;
19061        }
19062        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19063                finishedReceiver);
19064    }
19065
19066    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19067            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19068        sendResourcesChangedBroadcast(mediaStatus, replacing,
19069                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19070    }
19071
19072    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19073            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19074        int size = pkgList.length;
19075        if (size > 0) {
19076            // Send broadcasts here
19077            Bundle extras = new Bundle();
19078            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19079            if (uidArr != null) {
19080                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19081            }
19082            if (replacing) {
19083                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19084            }
19085            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19086                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19087            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19088        }
19089    }
19090
19091   /*
19092     * Look at potentially valid container ids from processCids If package
19093     * information doesn't match the one on record or package scanning fails,
19094     * the cid is added to list of removeCids. We currently don't delete stale
19095     * containers.
19096     */
19097    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19098            boolean externalStorage) {
19099        ArrayList<String> pkgList = new ArrayList<String>();
19100        Set<AsecInstallArgs> keys = processCids.keySet();
19101
19102        for (AsecInstallArgs args : keys) {
19103            String codePath = processCids.get(args);
19104            if (DEBUG_SD_INSTALL)
19105                Log.i(TAG, "Loading container : " + args.cid);
19106            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19107            try {
19108                // Make sure there are no container errors first.
19109                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19110                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19111                            + " when installing from sdcard");
19112                    continue;
19113                }
19114                // Check code path here.
19115                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19116                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19117                            + " does not match one in settings " + codePath);
19118                    continue;
19119                }
19120                // Parse package
19121                int parseFlags = mDefParseFlags;
19122                if (args.isExternalAsec()) {
19123                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19124                }
19125                if (args.isFwdLocked()) {
19126                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19127                }
19128
19129                synchronized (mInstallLock) {
19130                    PackageParser.Package pkg = null;
19131                    try {
19132                        // Sadly we don't know the package name yet to freeze it
19133                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19134                                SCAN_IGNORE_FROZEN, 0, null);
19135                    } catch (PackageManagerException e) {
19136                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19137                    }
19138                    // Scan the package
19139                    if (pkg != null) {
19140                        /*
19141                         * TODO why is the lock being held? doPostInstall is
19142                         * called in other places without the lock. This needs
19143                         * to be straightened out.
19144                         */
19145                        // writer
19146                        synchronized (mPackages) {
19147                            retCode = PackageManager.INSTALL_SUCCEEDED;
19148                            pkgList.add(pkg.packageName);
19149                            // Post process args
19150                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19151                                    pkg.applicationInfo.uid);
19152                        }
19153                    } else {
19154                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19155                    }
19156                }
19157
19158            } finally {
19159                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19160                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19161                }
19162            }
19163        }
19164        // writer
19165        synchronized (mPackages) {
19166            // If the platform SDK has changed since the last time we booted,
19167            // we need to re-grant app permission to catch any new ones that
19168            // appear. This is really a hack, and means that apps can in some
19169            // cases get permissions that the user didn't initially explicitly
19170            // allow... it would be nice to have some better way to handle
19171            // this situation.
19172            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19173                    : mSettings.getInternalVersion();
19174            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19175                    : StorageManager.UUID_PRIVATE_INTERNAL;
19176
19177            int updateFlags = UPDATE_PERMISSIONS_ALL;
19178            if (ver.sdkVersion != mSdkVersion) {
19179                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19180                        + mSdkVersion + "; regranting permissions for external");
19181                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19182            }
19183            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19184
19185            // Yay, everything is now upgraded
19186            ver.forceCurrent();
19187
19188            // can downgrade to reader
19189            // Persist settings
19190            mSettings.writeLPr();
19191        }
19192        // Send a broadcast to let everyone know we are done processing
19193        if (pkgList.size() > 0) {
19194            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19195        }
19196    }
19197
19198   /*
19199     * Utility method to unload a list of specified containers
19200     */
19201    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19202        // Just unmount all valid containers.
19203        for (AsecInstallArgs arg : cidArgs) {
19204            synchronized (mInstallLock) {
19205                arg.doPostDeleteLI(false);
19206           }
19207       }
19208   }
19209
19210    /*
19211     * Unload packages mounted on external media. This involves deleting package
19212     * data from internal structures, sending broadcasts about disabled packages,
19213     * gc'ing to free up references, unmounting all secure containers
19214     * corresponding to packages on external media, and posting a
19215     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19216     * that we always have to post this message if status has been requested no
19217     * matter what.
19218     */
19219    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19220            final boolean reportStatus) {
19221        if (DEBUG_SD_INSTALL)
19222            Log.i(TAG, "unloading media packages");
19223        ArrayList<String> pkgList = new ArrayList<String>();
19224        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19225        final Set<AsecInstallArgs> keys = processCids.keySet();
19226        for (AsecInstallArgs args : keys) {
19227            String pkgName = args.getPackageName();
19228            if (DEBUG_SD_INSTALL)
19229                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19230            // Delete package internally
19231            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19232            synchronized (mInstallLock) {
19233                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19234                final boolean res;
19235                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19236                        "unloadMediaPackages")) {
19237                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19238                            null);
19239                }
19240                if (res) {
19241                    pkgList.add(pkgName);
19242                } else {
19243                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19244                    failedList.add(args);
19245                }
19246            }
19247        }
19248
19249        // reader
19250        synchronized (mPackages) {
19251            // We didn't update the settings after removing each package;
19252            // write them now for all packages.
19253            mSettings.writeLPr();
19254        }
19255
19256        // We have to absolutely send UPDATED_MEDIA_STATUS only
19257        // after confirming that all the receivers processed the ordered
19258        // broadcast when packages get disabled, force a gc to clean things up.
19259        // and unload all the containers.
19260        if (pkgList.size() > 0) {
19261            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19262                    new IIntentReceiver.Stub() {
19263                public void performReceive(Intent intent, int resultCode, String data,
19264                        Bundle extras, boolean ordered, boolean sticky,
19265                        int sendingUser) throws RemoteException {
19266                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19267                            reportStatus ? 1 : 0, 1, keys);
19268                    mHandler.sendMessage(msg);
19269                }
19270            });
19271        } else {
19272            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19273                    keys);
19274            mHandler.sendMessage(msg);
19275        }
19276    }
19277
19278    private void loadPrivatePackages(final VolumeInfo vol) {
19279        mHandler.post(new Runnable() {
19280            @Override
19281            public void run() {
19282                loadPrivatePackagesInner(vol);
19283            }
19284        });
19285    }
19286
19287    private void loadPrivatePackagesInner(VolumeInfo vol) {
19288        final String volumeUuid = vol.fsUuid;
19289        if (TextUtils.isEmpty(volumeUuid)) {
19290            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19291            return;
19292        }
19293
19294        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19295        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19296        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19297
19298        final VersionInfo ver;
19299        final List<PackageSetting> packages;
19300        synchronized (mPackages) {
19301            ver = mSettings.findOrCreateVersion(volumeUuid);
19302            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19303        }
19304
19305        for (PackageSetting ps : packages) {
19306            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19307            synchronized (mInstallLock) {
19308                final PackageParser.Package pkg;
19309                try {
19310                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19311                    loaded.add(pkg.applicationInfo);
19312
19313                } catch (PackageManagerException e) {
19314                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19315                }
19316
19317                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19318                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19319                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19320                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19321                }
19322            }
19323        }
19324
19325        // Reconcile app data for all started/unlocked users
19326        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19327        final UserManager um = mContext.getSystemService(UserManager.class);
19328        UserManagerInternal umInternal = getUserManagerInternal();
19329        for (UserInfo user : um.getUsers()) {
19330            final int flags;
19331            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19332                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19333            } else if (umInternal.isUserRunning(user.id)) {
19334                flags = StorageManager.FLAG_STORAGE_DE;
19335            } else {
19336                continue;
19337            }
19338
19339            try {
19340                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19341                synchronized (mInstallLock) {
19342                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19343                }
19344            } catch (IllegalStateException e) {
19345                // Device was probably ejected, and we'll process that event momentarily
19346                Slog.w(TAG, "Failed to prepare storage: " + e);
19347            }
19348        }
19349
19350        synchronized (mPackages) {
19351            int updateFlags = UPDATE_PERMISSIONS_ALL;
19352            if (ver.sdkVersion != mSdkVersion) {
19353                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19354                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19355                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19356            }
19357            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19358
19359            // Yay, everything is now upgraded
19360            ver.forceCurrent();
19361
19362            mSettings.writeLPr();
19363        }
19364
19365        for (PackageFreezer freezer : freezers) {
19366            freezer.close();
19367        }
19368
19369        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19370        sendResourcesChangedBroadcast(true, false, loaded, null);
19371    }
19372
19373    private void unloadPrivatePackages(final VolumeInfo vol) {
19374        mHandler.post(new Runnable() {
19375            @Override
19376            public void run() {
19377                unloadPrivatePackagesInner(vol);
19378            }
19379        });
19380    }
19381
19382    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19383        final String volumeUuid = vol.fsUuid;
19384        if (TextUtils.isEmpty(volumeUuid)) {
19385            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19386            return;
19387        }
19388
19389        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19390        synchronized (mInstallLock) {
19391        synchronized (mPackages) {
19392            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19393            for (PackageSetting ps : packages) {
19394                if (ps.pkg == null) continue;
19395
19396                final ApplicationInfo info = ps.pkg.applicationInfo;
19397                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19398                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19399
19400                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19401                        "unloadPrivatePackagesInner")) {
19402                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19403                            false, null)) {
19404                        unloaded.add(info);
19405                    } else {
19406                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19407                    }
19408                }
19409
19410                // Try very hard to release any references to this package
19411                // so we don't risk the system server being killed due to
19412                // open FDs
19413                AttributeCache.instance().removePackage(ps.name);
19414            }
19415
19416            mSettings.writeLPr();
19417        }
19418        }
19419
19420        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19421        sendResourcesChangedBroadcast(false, false, unloaded, null);
19422
19423        // Try very hard to release any references to this path so we don't risk
19424        // the system server being killed due to open FDs
19425        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19426
19427        for (int i = 0; i < 3; i++) {
19428            System.gc();
19429            System.runFinalization();
19430        }
19431    }
19432
19433    /**
19434     * Prepare storage areas for given user on all mounted devices.
19435     */
19436    void prepareUserData(int userId, int userSerial, int flags) {
19437        synchronized (mInstallLock) {
19438            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19439            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19440                final String volumeUuid = vol.getFsUuid();
19441                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19442            }
19443        }
19444    }
19445
19446    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19447            boolean allowRecover) {
19448        // Prepare storage and verify that serial numbers are consistent; if
19449        // there's a mismatch we need to destroy to avoid leaking data
19450        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19451        try {
19452            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19453
19454            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19455                UserManagerService.enforceSerialNumber(
19456                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19457                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19458                    UserManagerService.enforceSerialNumber(
19459                            Environment.getDataSystemDeDirectory(userId), userSerial);
19460                }
19461            }
19462            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19463                UserManagerService.enforceSerialNumber(
19464                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19465                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19466                    UserManagerService.enforceSerialNumber(
19467                            Environment.getDataSystemCeDirectory(userId), userSerial);
19468                }
19469            }
19470
19471            synchronized (mInstallLock) {
19472                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19473            }
19474        } catch (Exception e) {
19475            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19476                    + " because we failed to prepare: " + e);
19477            destroyUserDataLI(volumeUuid, userId,
19478                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19479
19480            if (allowRecover) {
19481                // Try one last time; if we fail again we're really in trouble
19482                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19483            }
19484        }
19485    }
19486
19487    /**
19488     * Destroy storage areas for given user on all mounted devices.
19489     */
19490    void destroyUserData(int userId, int flags) {
19491        synchronized (mInstallLock) {
19492            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19493            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19494                final String volumeUuid = vol.getFsUuid();
19495                destroyUserDataLI(volumeUuid, userId, flags);
19496            }
19497        }
19498    }
19499
19500    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19501        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19502        try {
19503            // Clean up app data, profile data, and media data
19504            mInstaller.destroyUserData(volumeUuid, userId, flags);
19505
19506            // Clean up system data
19507            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19508                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19509                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19510                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19511                }
19512                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19513                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19514                }
19515            }
19516
19517            // Data with special labels is now gone, so finish the job
19518            storage.destroyUserStorage(volumeUuid, userId, flags);
19519
19520        } catch (Exception e) {
19521            logCriticalInfo(Log.WARN,
19522                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19523        }
19524    }
19525
19526    /**
19527     * Examine all users present on given mounted volume, and destroy data
19528     * belonging to users that are no longer valid, or whose user ID has been
19529     * recycled.
19530     */
19531    private void reconcileUsers(String volumeUuid) {
19532        final List<File> files = new ArrayList<>();
19533        Collections.addAll(files, FileUtils
19534                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19535        Collections.addAll(files, FileUtils
19536                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19537        Collections.addAll(files, FileUtils
19538                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19539        Collections.addAll(files, FileUtils
19540                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19541        for (File file : files) {
19542            if (!file.isDirectory()) continue;
19543
19544            final int userId;
19545            final UserInfo info;
19546            try {
19547                userId = Integer.parseInt(file.getName());
19548                info = sUserManager.getUserInfo(userId);
19549            } catch (NumberFormatException e) {
19550                Slog.w(TAG, "Invalid user directory " + file);
19551                continue;
19552            }
19553
19554            boolean destroyUser = false;
19555            if (info == null) {
19556                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19557                        + " because no matching user was found");
19558                destroyUser = true;
19559            } else if (!mOnlyCore) {
19560                try {
19561                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19562                } catch (IOException e) {
19563                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19564                            + " because we failed to enforce serial number: " + e);
19565                    destroyUser = true;
19566                }
19567            }
19568
19569            if (destroyUser) {
19570                synchronized (mInstallLock) {
19571                    destroyUserDataLI(volumeUuid, userId,
19572                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19573                }
19574            }
19575        }
19576    }
19577
19578    private void assertPackageKnown(String volumeUuid, String packageName)
19579            throws PackageManagerException {
19580        synchronized (mPackages) {
19581            final PackageSetting ps = mSettings.mPackages.get(packageName);
19582            if (ps == null) {
19583                throw new PackageManagerException("Package " + packageName + " is unknown");
19584            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19585                throw new PackageManagerException(
19586                        "Package " + packageName + " found on unknown volume " + volumeUuid
19587                                + "; expected volume " + ps.volumeUuid);
19588            }
19589        }
19590    }
19591
19592    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19593            throws PackageManagerException {
19594        synchronized (mPackages) {
19595            final PackageSetting ps = mSettings.mPackages.get(packageName);
19596            if (ps == null) {
19597                throw new PackageManagerException("Package " + packageName + " is unknown");
19598            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19599                throw new PackageManagerException(
19600                        "Package " + packageName + " found on unknown volume " + volumeUuid
19601                                + "; expected volume " + ps.volumeUuid);
19602            } else if (!ps.getInstalled(userId)) {
19603                throw new PackageManagerException(
19604                        "Package " + packageName + " not installed for user " + userId);
19605            }
19606        }
19607    }
19608
19609    /**
19610     * Examine all apps present on given mounted volume, and destroy apps that
19611     * aren't expected, either due to uninstallation or reinstallation on
19612     * another volume.
19613     */
19614    private void reconcileApps(String volumeUuid) {
19615        final File[] files = FileUtils
19616                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19617        for (File file : files) {
19618            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19619                    && !PackageInstallerService.isStageName(file.getName());
19620            if (!isPackage) {
19621                // Ignore entries which are not packages
19622                continue;
19623            }
19624
19625            try {
19626                final PackageLite pkg = PackageParser.parsePackageLite(file,
19627                        PackageParser.PARSE_MUST_BE_APK);
19628                assertPackageKnown(volumeUuid, pkg.packageName);
19629
19630            } catch (PackageParserException | PackageManagerException e) {
19631                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19632                synchronized (mInstallLock) {
19633                    removeCodePathLI(file);
19634                }
19635            }
19636        }
19637    }
19638
19639    /**
19640     * Reconcile all app data for the given user.
19641     * <p>
19642     * Verifies that directories exist and that ownership and labeling is
19643     * correct for all installed apps on all mounted volumes.
19644     */
19645    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19646        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19647        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19648            final String volumeUuid = vol.getFsUuid();
19649            synchronized (mInstallLock) {
19650                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19651            }
19652        }
19653    }
19654
19655    /**
19656     * Reconcile all app data on given mounted volume.
19657     * <p>
19658     * Destroys app data that isn't expected, either due to uninstallation or
19659     * reinstallation on another volume.
19660     * <p>
19661     * Verifies that directories exist and that ownership and labeling is
19662     * correct for all installed apps.
19663     */
19664    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19665            boolean migrateAppData) {
19666        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19667                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19668
19669        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19670        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19671
19672        boolean restoreconNeeded = false;
19673
19674        // First look for stale data that doesn't belong, and check if things
19675        // have changed since we did our last restorecon
19676        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19677            if (StorageManager.isFileEncryptedNativeOrEmulated()
19678                    && !StorageManager.isUserKeyUnlocked(userId)) {
19679                throw new RuntimeException(
19680                        "Yikes, someone asked us to reconcile CE storage while " + userId
19681                                + " was still locked; this would have caused massive data loss!");
19682            }
19683
19684            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19685
19686            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19687            for (File file : files) {
19688                final String packageName = file.getName();
19689                try {
19690                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19691                } catch (PackageManagerException e) {
19692                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19693                    try {
19694                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19695                                StorageManager.FLAG_STORAGE_CE, 0);
19696                    } catch (InstallerException e2) {
19697                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19698                    }
19699                }
19700            }
19701        }
19702        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19703            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19704
19705            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19706            for (File file : files) {
19707                final String packageName = file.getName();
19708                try {
19709                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19710                } catch (PackageManagerException e) {
19711                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19712                    try {
19713                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19714                                StorageManager.FLAG_STORAGE_DE, 0);
19715                    } catch (InstallerException e2) {
19716                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19717                    }
19718                }
19719            }
19720        }
19721
19722        // Ensure that data directories are ready to roll for all packages
19723        // installed for this volume and user
19724        final List<PackageSetting> packages;
19725        synchronized (mPackages) {
19726            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19727        }
19728        int preparedCount = 0;
19729        for (PackageSetting ps : packages) {
19730            final String packageName = ps.name;
19731            if (ps.pkg == null) {
19732                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19733                // TODO: might be due to legacy ASEC apps; we should circle back
19734                // and reconcile again once they're scanned
19735                continue;
19736            }
19737
19738            if (ps.getInstalled(userId)) {
19739                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19740
19741                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
19742                    // We may have just shuffled around app data directories, so
19743                    // prepare them one more time
19744                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19745                }
19746
19747                preparedCount++;
19748            }
19749        }
19750
19751        if (restoreconNeeded) {
19752            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19753                SELinuxMMAC.setRestoreconDone(ceDir);
19754            }
19755            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19756                SELinuxMMAC.setRestoreconDone(deDir);
19757            }
19758        }
19759
19760        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19761                + " packages; restoreconNeeded was " + restoreconNeeded);
19762    }
19763
19764    /**
19765     * Prepare app data for the given app just after it was installed or
19766     * upgraded. This method carefully only touches users that it's installed
19767     * for, and it forces a restorecon to handle any seinfo changes.
19768     * <p>
19769     * Verifies that directories exist and that ownership and labeling is
19770     * correct for all installed apps. If there is an ownership mismatch, it
19771     * will try recovering system apps by wiping data; third-party app data is
19772     * left intact.
19773     * <p>
19774     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19775     */
19776    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19777        final PackageSetting ps;
19778        synchronized (mPackages) {
19779            ps = mSettings.mPackages.get(pkg.packageName);
19780            mSettings.writeKernelMappingLPr(ps);
19781        }
19782
19783        final UserManager um = mContext.getSystemService(UserManager.class);
19784        UserManagerInternal umInternal = getUserManagerInternal();
19785        for (UserInfo user : um.getUsers()) {
19786            final int flags;
19787            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19788                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19789            } else if (umInternal.isUserRunning(user.id)) {
19790                flags = StorageManager.FLAG_STORAGE_DE;
19791            } else {
19792                continue;
19793            }
19794
19795            if (ps.getInstalled(user.id)) {
19796                // Whenever an app changes, force a restorecon of its data
19797                // TODO: when user data is locked, mark that we're still dirty
19798                prepareAppDataLIF(pkg, user.id, flags, true);
19799            }
19800        }
19801    }
19802
19803    /**
19804     * Prepare app data for the given app.
19805     * <p>
19806     * Verifies that directories exist and that ownership and labeling is
19807     * correct for all installed apps. If there is an ownership mismatch, this
19808     * will try recovering system apps by wiping data; third-party app data is
19809     * left intact.
19810     */
19811    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19812            boolean restoreconNeeded) {
19813        if (pkg == null) {
19814            Slog.wtf(TAG, "Package was null!", new Throwable());
19815            return;
19816        }
19817        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19818        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19819        for (int i = 0; i < childCount; i++) {
19820            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19821        }
19822    }
19823
19824    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19825            boolean restoreconNeeded) {
19826        if (DEBUG_APP_DATA) {
19827            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19828                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19829        }
19830
19831        final String volumeUuid = pkg.volumeUuid;
19832        final String packageName = pkg.packageName;
19833        final ApplicationInfo app = pkg.applicationInfo;
19834        final int appId = UserHandle.getAppId(app.uid);
19835
19836        Preconditions.checkNotNull(app.seinfo);
19837
19838        try {
19839            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19840                    appId, app.seinfo, app.targetSdkVersion);
19841        } catch (InstallerException e) {
19842            if (app.isSystemApp()) {
19843                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19844                        + ", but trying to recover: " + e);
19845                destroyAppDataLeafLIF(pkg, userId, flags);
19846                try {
19847                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19848                            appId, app.seinfo, app.targetSdkVersion);
19849                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19850                } catch (InstallerException e2) {
19851                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19852                }
19853            } else {
19854                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19855            }
19856        }
19857
19858        if (restoreconNeeded) {
19859            try {
19860                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19861                        app.seinfo);
19862            } catch (InstallerException e) {
19863                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19864            }
19865        }
19866
19867        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19868            try {
19869                // CE storage is unlocked right now, so read out the inode and
19870                // remember for use later when it's locked
19871                // TODO: mark this structure as dirty so we persist it!
19872                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19873                        StorageManager.FLAG_STORAGE_CE);
19874                synchronized (mPackages) {
19875                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19876                    if (ps != null) {
19877                        ps.setCeDataInode(ceDataInode, userId);
19878                    }
19879                }
19880            } catch (InstallerException e) {
19881                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19882            }
19883        }
19884
19885        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19886    }
19887
19888    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19889        if (pkg == null) {
19890            Slog.wtf(TAG, "Package was null!", new Throwable());
19891            return;
19892        }
19893        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19894        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19895        for (int i = 0; i < childCount; i++) {
19896            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19897        }
19898    }
19899
19900    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19901        final String volumeUuid = pkg.volumeUuid;
19902        final String packageName = pkg.packageName;
19903        final ApplicationInfo app = pkg.applicationInfo;
19904
19905        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19906            // Create a native library symlink only if we have native libraries
19907            // and if the native libraries are 32 bit libraries. We do not provide
19908            // this symlink for 64 bit libraries.
19909            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19910                final String nativeLibPath = app.nativeLibraryDir;
19911                try {
19912                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19913                            nativeLibPath, userId);
19914                } catch (InstallerException e) {
19915                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19916                }
19917            }
19918        }
19919    }
19920
19921    /**
19922     * For system apps on non-FBE devices, this method migrates any existing
19923     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19924     * requested by the app.
19925     */
19926    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19927        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19928                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19929            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19930                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19931            try {
19932                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19933                        storageTarget);
19934            } catch (InstallerException e) {
19935                logCriticalInfo(Log.WARN,
19936                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19937            }
19938            return true;
19939        } else {
19940            return false;
19941        }
19942    }
19943
19944    public PackageFreezer freezePackage(String packageName, String killReason) {
19945        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19946    }
19947
19948    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19949        return new PackageFreezer(packageName, userId, killReason);
19950    }
19951
19952    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19953            String killReason) {
19954        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19955    }
19956
19957    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19958            String killReason) {
19959        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19960            return new PackageFreezer();
19961        } else {
19962            return freezePackage(packageName, userId, killReason);
19963        }
19964    }
19965
19966    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19967            String killReason) {
19968        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19969    }
19970
19971    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19972            String killReason) {
19973        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19974            return new PackageFreezer();
19975        } else {
19976            return freezePackage(packageName, userId, killReason);
19977        }
19978    }
19979
19980    /**
19981     * Class that freezes and kills the given package upon creation, and
19982     * unfreezes it upon closing. This is typically used when doing surgery on
19983     * app code/data to prevent the app from running while you're working.
19984     */
19985    private class PackageFreezer implements AutoCloseable {
19986        private final String mPackageName;
19987        private final PackageFreezer[] mChildren;
19988
19989        private final boolean mWeFroze;
19990
19991        private final AtomicBoolean mClosed = new AtomicBoolean();
19992        private final CloseGuard mCloseGuard = CloseGuard.get();
19993
19994        /**
19995         * Create and return a stub freezer that doesn't actually do anything,
19996         * typically used when someone requested
19997         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19998         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19999         */
20000        public PackageFreezer() {
20001            mPackageName = null;
20002            mChildren = null;
20003            mWeFroze = false;
20004            mCloseGuard.open("close");
20005        }
20006
20007        public PackageFreezer(String packageName, int userId, String killReason) {
20008            synchronized (mPackages) {
20009                mPackageName = packageName;
20010                mWeFroze = mFrozenPackages.add(mPackageName);
20011
20012                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20013                if (ps != null) {
20014                    killApplication(ps.name, ps.appId, userId, killReason);
20015                }
20016
20017                final PackageParser.Package p = mPackages.get(packageName);
20018                if (p != null && p.childPackages != null) {
20019                    final int N = p.childPackages.size();
20020                    mChildren = new PackageFreezer[N];
20021                    for (int i = 0; i < N; i++) {
20022                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20023                                userId, killReason);
20024                    }
20025                } else {
20026                    mChildren = null;
20027                }
20028            }
20029            mCloseGuard.open("close");
20030        }
20031
20032        @Override
20033        protected void finalize() throws Throwable {
20034            try {
20035                mCloseGuard.warnIfOpen();
20036                close();
20037            } finally {
20038                super.finalize();
20039            }
20040        }
20041
20042        @Override
20043        public void close() {
20044            mCloseGuard.close();
20045            if (mClosed.compareAndSet(false, true)) {
20046                synchronized (mPackages) {
20047                    if (mWeFroze) {
20048                        mFrozenPackages.remove(mPackageName);
20049                    }
20050
20051                    if (mChildren != null) {
20052                        for (PackageFreezer freezer : mChildren) {
20053                            freezer.close();
20054                        }
20055                    }
20056                }
20057            }
20058        }
20059    }
20060
20061    /**
20062     * Verify that given package is currently frozen.
20063     */
20064    private void checkPackageFrozen(String packageName) {
20065        synchronized (mPackages) {
20066            if (!mFrozenPackages.contains(packageName)) {
20067                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20068            }
20069        }
20070    }
20071
20072    @Override
20073    public int movePackage(final String packageName, final String volumeUuid) {
20074        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20075
20076        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20077        final int moveId = mNextMoveId.getAndIncrement();
20078        mHandler.post(new Runnable() {
20079            @Override
20080            public void run() {
20081                try {
20082                    movePackageInternal(packageName, volumeUuid, moveId, user);
20083                } catch (PackageManagerException e) {
20084                    Slog.w(TAG, "Failed to move " + packageName, e);
20085                    mMoveCallbacks.notifyStatusChanged(moveId,
20086                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20087                }
20088            }
20089        });
20090        return moveId;
20091    }
20092
20093    private void movePackageInternal(final String packageName, final String volumeUuid,
20094            final int moveId, UserHandle user) throws PackageManagerException {
20095        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20096        final PackageManager pm = mContext.getPackageManager();
20097
20098        final boolean currentAsec;
20099        final String currentVolumeUuid;
20100        final File codeFile;
20101        final String installerPackageName;
20102        final String packageAbiOverride;
20103        final int appId;
20104        final String seinfo;
20105        final String label;
20106        final int targetSdkVersion;
20107        final PackageFreezer freezer;
20108        final int[] installedUserIds;
20109
20110        // reader
20111        synchronized (mPackages) {
20112            final PackageParser.Package pkg = mPackages.get(packageName);
20113            final PackageSetting ps = mSettings.mPackages.get(packageName);
20114            if (pkg == null || ps == null) {
20115                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20116            }
20117
20118            if (pkg.applicationInfo.isSystemApp()) {
20119                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20120                        "Cannot move system application");
20121            }
20122
20123            if (pkg.applicationInfo.isExternalAsec()) {
20124                currentAsec = true;
20125                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20126            } else if (pkg.applicationInfo.isForwardLocked()) {
20127                currentAsec = true;
20128                currentVolumeUuid = "forward_locked";
20129            } else {
20130                currentAsec = false;
20131                currentVolumeUuid = ps.volumeUuid;
20132
20133                final File probe = new File(pkg.codePath);
20134                final File probeOat = new File(probe, "oat");
20135                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20136                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20137                            "Move only supported for modern cluster style installs");
20138                }
20139            }
20140
20141            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20142                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20143                        "Package already moved to " + volumeUuid);
20144            }
20145            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20146                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20147                        "Device admin cannot be moved");
20148            }
20149
20150            if (mFrozenPackages.contains(packageName)) {
20151                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20152                        "Failed to move already frozen package");
20153            }
20154
20155            codeFile = new File(pkg.codePath);
20156            installerPackageName = ps.installerPackageName;
20157            packageAbiOverride = ps.cpuAbiOverrideString;
20158            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20159            seinfo = pkg.applicationInfo.seinfo;
20160            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20161            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20162            freezer = freezePackage(packageName, "movePackageInternal");
20163            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20164        }
20165
20166        final Bundle extras = new Bundle();
20167        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20168        extras.putString(Intent.EXTRA_TITLE, label);
20169        mMoveCallbacks.notifyCreated(moveId, extras);
20170
20171        int installFlags;
20172        final boolean moveCompleteApp;
20173        final File measurePath;
20174
20175        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20176            installFlags = INSTALL_INTERNAL;
20177            moveCompleteApp = !currentAsec;
20178            measurePath = Environment.getDataAppDirectory(volumeUuid);
20179        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20180            installFlags = INSTALL_EXTERNAL;
20181            moveCompleteApp = false;
20182            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20183        } else {
20184            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20185            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20186                    || !volume.isMountedWritable()) {
20187                freezer.close();
20188                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20189                        "Move location not mounted private volume");
20190            }
20191
20192            Preconditions.checkState(!currentAsec);
20193
20194            installFlags = INSTALL_INTERNAL;
20195            moveCompleteApp = true;
20196            measurePath = Environment.getDataAppDirectory(volumeUuid);
20197        }
20198
20199        final PackageStats stats = new PackageStats(null, -1);
20200        synchronized (mInstaller) {
20201            for (int userId : installedUserIds) {
20202                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20203                    freezer.close();
20204                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20205                            "Failed to measure package size");
20206                }
20207            }
20208        }
20209
20210        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20211                + stats.dataSize);
20212
20213        final long startFreeBytes = measurePath.getFreeSpace();
20214        final long sizeBytes;
20215        if (moveCompleteApp) {
20216            sizeBytes = stats.codeSize + stats.dataSize;
20217        } else {
20218            sizeBytes = stats.codeSize;
20219        }
20220
20221        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20222            freezer.close();
20223            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20224                    "Not enough free space to move");
20225        }
20226
20227        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20228
20229        final CountDownLatch installedLatch = new CountDownLatch(1);
20230        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20231            @Override
20232            public void onUserActionRequired(Intent intent) throws RemoteException {
20233                throw new IllegalStateException();
20234            }
20235
20236            @Override
20237            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20238                    Bundle extras) throws RemoteException {
20239                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20240                        + PackageManager.installStatusToString(returnCode, msg));
20241
20242                installedLatch.countDown();
20243                freezer.close();
20244
20245                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20246                switch (status) {
20247                    case PackageInstaller.STATUS_SUCCESS:
20248                        mMoveCallbacks.notifyStatusChanged(moveId,
20249                                PackageManager.MOVE_SUCCEEDED);
20250                        break;
20251                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20252                        mMoveCallbacks.notifyStatusChanged(moveId,
20253                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20254                        break;
20255                    default:
20256                        mMoveCallbacks.notifyStatusChanged(moveId,
20257                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20258                        break;
20259                }
20260            }
20261        };
20262
20263        final MoveInfo move;
20264        if (moveCompleteApp) {
20265            // Kick off a thread to report progress estimates
20266            new Thread() {
20267                @Override
20268                public void run() {
20269                    while (true) {
20270                        try {
20271                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20272                                break;
20273                            }
20274                        } catch (InterruptedException ignored) {
20275                        }
20276
20277                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20278                        final int progress = 10 + (int) MathUtils.constrain(
20279                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20280                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20281                    }
20282                }
20283            }.start();
20284
20285            final String dataAppName = codeFile.getName();
20286            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20287                    dataAppName, appId, seinfo, targetSdkVersion);
20288        } else {
20289            move = null;
20290        }
20291
20292        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20293
20294        final Message msg = mHandler.obtainMessage(INIT_COPY);
20295        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20296        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20297                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20298                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20299        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20300        msg.obj = params;
20301
20302        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20303                System.identityHashCode(msg.obj));
20304        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20305                System.identityHashCode(msg.obj));
20306
20307        mHandler.sendMessage(msg);
20308    }
20309
20310    @Override
20311    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20312        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20313
20314        final int realMoveId = mNextMoveId.getAndIncrement();
20315        final Bundle extras = new Bundle();
20316        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20317        mMoveCallbacks.notifyCreated(realMoveId, extras);
20318
20319        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20320            @Override
20321            public void onCreated(int moveId, Bundle extras) {
20322                // Ignored
20323            }
20324
20325            @Override
20326            public void onStatusChanged(int moveId, int status, long estMillis) {
20327                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20328            }
20329        };
20330
20331        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20332        storage.setPrimaryStorageUuid(volumeUuid, callback);
20333        return realMoveId;
20334    }
20335
20336    @Override
20337    public int getMoveStatus(int moveId) {
20338        mContext.enforceCallingOrSelfPermission(
20339                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20340        return mMoveCallbacks.mLastStatus.get(moveId);
20341    }
20342
20343    @Override
20344    public void registerMoveCallback(IPackageMoveObserver callback) {
20345        mContext.enforceCallingOrSelfPermission(
20346                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20347        mMoveCallbacks.register(callback);
20348    }
20349
20350    @Override
20351    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20352        mContext.enforceCallingOrSelfPermission(
20353                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20354        mMoveCallbacks.unregister(callback);
20355    }
20356
20357    @Override
20358    public boolean setInstallLocation(int loc) {
20359        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20360                null);
20361        if (getInstallLocation() == loc) {
20362            return true;
20363        }
20364        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20365                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20366            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20367                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20368            return true;
20369        }
20370        return false;
20371   }
20372
20373    @Override
20374    public int getInstallLocation() {
20375        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20376                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20377                PackageHelper.APP_INSTALL_AUTO);
20378    }
20379
20380    /** Called by UserManagerService */
20381    void cleanUpUser(UserManagerService userManager, int userHandle) {
20382        synchronized (mPackages) {
20383            mDirtyUsers.remove(userHandle);
20384            mUserNeedsBadging.delete(userHandle);
20385            mSettings.removeUserLPw(userHandle);
20386            mPendingBroadcasts.remove(userHandle);
20387            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20388            removeUnusedPackagesLPw(userManager, userHandle);
20389        }
20390    }
20391
20392    /**
20393     * We're removing userHandle and would like to remove any downloaded packages
20394     * that are no longer in use by any other user.
20395     * @param userHandle the user being removed
20396     */
20397    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20398        final boolean DEBUG_CLEAN_APKS = false;
20399        int [] users = userManager.getUserIds();
20400        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20401        while (psit.hasNext()) {
20402            PackageSetting ps = psit.next();
20403            if (ps.pkg == null) {
20404                continue;
20405            }
20406            final String packageName = ps.pkg.packageName;
20407            // Skip over if system app
20408            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20409                continue;
20410            }
20411            if (DEBUG_CLEAN_APKS) {
20412                Slog.i(TAG, "Checking package " + packageName);
20413            }
20414            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20415            if (keep) {
20416                if (DEBUG_CLEAN_APKS) {
20417                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20418                }
20419            } else {
20420                for (int i = 0; i < users.length; i++) {
20421                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20422                        keep = true;
20423                        if (DEBUG_CLEAN_APKS) {
20424                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20425                                    + users[i]);
20426                        }
20427                        break;
20428                    }
20429                }
20430            }
20431            if (!keep) {
20432                if (DEBUG_CLEAN_APKS) {
20433                    Slog.i(TAG, "  Removing package " + packageName);
20434                }
20435                mHandler.post(new Runnable() {
20436                    public void run() {
20437                        deletePackageX(packageName, userHandle, 0);
20438                    } //end run
20439                });
20440            }
20441        }
20442    }
20443
20444    /** Called by UserManagerService */
20445    void createNewUser(int userId) {
20446        synchronized (mInstallLock) {
20447            mSettings.createNewUserLI(this, mInstaller, userId);
20448        }
20449        synchronized (mPackages) {
20450            scheduleWritePackageRestrictionsLocked(userId);
20451            scheduleWritePackageListLocked(userId);
20452            applyFactoryDefaultBrowserLPw(userId);
20453            primeDomainVerificationsLPw(userId);
20454        }
20455    }
20456
20457    void onNewUserCreated(final int userId) {
20458        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20459        // If permission review for legacy apps is required, we represent
20460        // dagerous permissions for such apps as always granted runtime
20461        // permissions to keep per user flag state whether review is needed.
20462        // Hence, if a new user is added we have to propagate dangerous
20463        // permission grants for these legacy apps.
20464        if (mPermissionReviewRequired) {
20465            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20466                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20467        }
20468    }
20469
20470    @Override
20471    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20472        mContext.enforceCallingOrSelfPermission(
20473                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20474                "Only package verification agents can read the verifier device identity");
20475
20476        synchronized (mPackages) {
20477            return mSettings.getVerifierDeviceIdentityLPw();
20478        }
20479    }
20480
20481    @Override
20482    public void setPermissionEnforced(String permission, boolean enforced) {
20483        // TODO: Now that we no longer change GID for storage, this should to away.
20484        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20485                "setPermissionEnforced");
20486        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20487            synchronized (mPackages) {
20488                if (mSettings.mReadExternalStorageEnforced == null
20489                        || mSettings.mReadExternalStorageEnforced != enforced) {
20490                    mSettings.mReadExternalStorageEnforced = enforced;
20491                    mSettings.writeLPr();
20492                }
20493            }
20494            // kill any non-foreground processes so we restart them and
20495            // grant/revoke the GID.
20496            final IActivityManager am = ActivityManagerNative.getDefault();
20497            if (am != null) {
20498                final long token = Binder.clearCallingIdentity();
20499                try {
20500                    am.killProcessesBelowForeground("setPermissionEnforcement");
20501                } catch (RemoteException e) {
20502                } finally {
20503                    Binder.restoreCallingIdentity(token);
20504                }
20505            }
20506        } else {
20507            throw new IllegalArgumentException("No selective enforcement for " + permission);
20508        }
20509    }
20510
20511    @Override
20512    @Deprecated
20513    public boolean isPermissionEnforced(String permission) {
20514        return true;
20515    }
20516
20517    @Override
20518    public boolean isStorageLow() {
20519        final long token = Binder.clearCallingIdentity();
20520        try {
20521            final DeviceStorageMonitorInternal
20522                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20523            if (dsm != null) {
20524                return dsm.isMemoryLow();
20525            } else {
20526                return false;
20527            }
20528        } finally {
20529            Binder.restoreCallingIdentity(token);
20530        }
20531    }
20532
20533    @Override
20534    public IPackageInstaller getPackageInstaller() {
20535        return mInstallerService;
20536    }
20537
20538    private boolean userNeedsBadging(int userId) {
20539        int index = mUserNeedsBadging.indexOfKey(userId);
20540        if (index < 0) {
20541            final UserInfo userInfo;
20542            final long token = Binder.clearCallingIdentity();
20543            try {
20544                userInfo = sUserManager.getUserInfo(userId);
20545            } finally {
20546                Binder.restoreCallingIdentity(token);
20547            }
20548            final boolean b;
20549            if (userInfo != null && userInfo.isManagedProfile()) {
20550                b = true;
20551            } else {
20552                b = false;
20553            }
20554            mUserNeedsBadging.put(userId, b);
20555            return b;
20556        }
20557        return mUserNeedsBadging.valueAt(index);
20558    }
20559
20560    @Override
20561    public KeySet getKeySetByAlias(String packageName, String alias) {
20562        if (packageName == null || alias == null) {
20563            return null;
20564        }
20565        synchronized(mPackages) {
20566            final PackageParser.Package pkg = mPackages.get(packageName);
20567            if (pkg == null) {
20568                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20569                throw new IllegalArgumentException("Unknown package: " + packageName);
20570            }
20571            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20572            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20573        }
20574    }
20575
20576    @Override
20577    public KeySet getSigningKeySet(String packageName) {
20578        if (packageName == null) {
20579            return null;
20580        }
20581        synchronized(mPackages) {
20582            final PackageParser.Package pkg = mPackages.get(packageName);
20583            if (pkg == null) {
20584                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20585                throw new IllegalArgumentException("Unknown package: " + packageName);
20586            }
20587            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20588                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20589                throw new SecurityException("May not access signing KeySet of other apps.");
20590            }
20591            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20592            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20593        }
20594    }
20595
20596    @Override
20597    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20598        if (packageName == null || ks == null) {
20599            return false;
20600        }
20601        synchronized(mPackages) {
20602            final PackageParser.Package pkg = mPackages.get(packageName);
20603            if (pkg == null) {
20604                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20605                throw new IllegalArgumentException("Unknown package: " + packageName);
20606            }
20607            IBinder ksh = ks.getToken();
20608            if (ksh instanceof KeySetHandle) {
20609                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20610                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20611            }
20612            return false;
20613        }
20614    }
20615
20616    @Override
20617    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20618        if (packageName == null || ks == null) {
20619            return false;
20620        }
20621        synchronized(mPackages) {
20622            final PackageParser.Package pkg = mPackages.get(packageName);
20623            if (pkg == null) {
20624                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20625                throw new IllegalArgumentException("Unknown package: " + packageName);
20626            }
20627            IBinder ksh = ks.getToken();
20628            if (ksh instanceof KeySetHandle) {
20629                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20630                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20631            }
20632            return false;
20633        }
20634    }
20635
20636    private void deletePackageIfUnusedLPr(final String packageName) {
20637        PackageSetting ps = mSettings.mPackages.get(packageName);
20638        if (ps == null) {
20639            return;
20640        }
20641        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20642            // TODO Implement atomic delete if package is unused
20643            // It is currently possible that the package will be deleted even if it is installed
20644            // after this method returns.
20645            mHandler.post(new Runnable() {
20646                public void run() {
20647                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20648                }
20649            });
20650        }
20651    }
20652
20653    /**
20654     * Check and throw if the given before/after packages would be considered a
20655     * downgrade.
20656     */
20657    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20658            throws PackageManagerException {
20659        if (after.versionCode < before.mVersionCode) {
20660            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20661                    "Update version code " + after.versionCode + " is older than current "
20662                    + before.mVersionCode);
20663        } else if (after.versionCode == before.mVersionCode) {
20664            if (after.baseRevisionCode < before.baseRevisionCode) {
20665                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20666                        "Update base revision code " + after.baseRevisionCode
20667                        + " is older than current " + before.baseRevisionCode);
20668            }
20669
20670            if (!ArrayUtils.isEmpty(after.splitNames)) {
20671                for (int i = 0; i < after.splitNames.length; i++) {
20672                    final String splitName = after.splitNames[i];
20673                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20674                    if (j != -1) {
20675                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20676                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20677                                    "Update split " + splitName + " revision code "
20678                                    + after.splitRevisionCodes[i] + " is older than current "
20679                                    + before.splitRevisionCodes[j]);
20680                        }
20681                    }
20682                }
20683            }
20684        }
20685    }
20686
20687    private static class MoveCallbacks extends Handler {
20688        private static final int MSG_CREATED = 1;
20689        private static final int MSG_STATUS_CHANGED = 2;
20690
20691        private final RemoteCallbackList<IPackageMoveObserver>
20692                mCallbacks = new RemoteCallbackList<>();
20693
20694        private final SparseIntArray mLastStatus = new SparseIntArray();
20695
20696        public MoveCallbacks(Looper looper) {
20697            super(looper);
20698        }
20699
20700        public void register(IPackageMoveObserver callback) {
20701            mCallbacks.register(callback);
20702        }
20703
20704        public void unregister(IPackageMoveObserver callback) {
20705            mCallbacks.unregister(callback);
20706        }
20707
20708        @Override
20709        public void handleMessage(Message msg) {
20710            final SomeArgs args = (SomeArgs) msg.obj;
20711            final int n = mCallbacks.beginBroadcast();
20712            for (int i = 0; i < n; i++) {
20713                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20714                try {
20715                    invokeCallback(callback, msg.what, args);
20716                } catch (RemoteException ignored) {
20717                }
20718            }
20719            mCallbacks.finishBroadcast();
20720            args.recycle();
20721        }
20722
20723        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20724                throws RemoteException {
20725            switch (what) {
20726                case MSG_CREATED: {
20727                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20728                    break;
20729                }
20730                case MSG_STATUS_CHANGED: {
20731                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20732                    break;
20733                }
20734            }
20735        }
20736
20737        private void notifyCreated(int moveId, Bundle extras) {
20738            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20739
20740            final SomeArgs args = SomeArgs.obtain();
20741            args.argi1 = moveId;
20742            args.arg2 = extras;
20743            obtainMessage(MSG_CREATED, args).sendToTarget();
20744        }
20745
20746        private void notifyStatusChanged(int moveId, int status) {
20747            notifyStatusChanged(moveId, status, -1);
20748        }
20749
20750        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20751            Slog.v(TAG, "Move " + moveId + " status " + status);
20752
20753            final SomeArgs args = SomeArgs.obtain();
20754            args.argi1 = moveId;
20755            args.argi2 = status;
20756            args.arg3 = estMillis;
20757            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20758
20759            synchronized (mLastStatus) {
20760                mLastStatus.put(moveId, status);
20761            }
20762        }
20763    }
20764
20765    private final static class OnPermissionChangeListeners extends Handler {
20766        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20767
20768        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20769                new RemoteCallbackList<>();
20770
20771        public OnPermissionChangeListeners(Looper looper) {
20772            super(looper);
20773        }
20774
20775        @Override
20776        public void handleMessage(Message msg) {
20777            switch (msg.what) {
20778                case MSG_ON_PERMISSIONS_CHANGED: {
20779                    final int uid = msg.arg1;
20780                    handleOnPermissionsChanged(uid);
20781                } break;
20782            }
20783        }
20784
20785        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20786            mPermissionListeners.register(listener);
20787
20788        }
20789
20790        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20791            mPermissionListeners.unregister(listener);
20792        }
20793
20794        public void onPermissionsChanged(int uid) {
20795            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20796                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20797            }
20798        }
20799
20800        private void handleOnPermissionsChanged(int uid) {
20801            final int count = mPermissionListeners.beginBroadcast();
20802            try {
20803                for (int i = 0; i < count; i++) {
20804                    IOnPermissionsChangeListener callback = mPermissionListeners
20805                            .getBroadcastItem(i);
20806                    try {
20807                        callback.onPermissionsChanged(uid);
20808                    } catch (RemoteException e) {
20809                        Log.e(TAG, "Permission listener is dead", e);
20810                    }
20811                }
20812            } finally {
20813                mPermissionListeners.finishBroadcast();
20814            }
20815        }
20816    }
20817
20818    private class PackageManagerInternalImpl extends PackageManagerInternal {
20819        @Override
20820        public void setLocationPackagesProvider(PackagesProvider provider) {
20821            synchronized (mPackages) {
20822                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20823            }
20824        }
20825
20826        @Override
20827        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20828            synchronized (mPackages) {
20829                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20830            }
20831        }
20832
20833        @Override
20834        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20835            synchronized (mPackages) {
20836                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20837            }
20838        }
20839
20840        @Override
20841        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20842            synchronized (mPackages) {
20843                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20844            }
20845        }
20846
20847        @Override
20848        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20849            synchronized (mPackages) {
20850                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20851            }
20852        }
20853
20854        @Override
20855        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20856            synchronized (mPackages) {
20857                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20858            }
20859        }
20860
20861        @Override
20862        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20863            synchronized (mPackages) {
20864                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20865                        packageName, userId);
20866            }
20867        }
20868
20869        @Override
20870        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20871            synchronized (mPackages) {
20872                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20873                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20874                        packageName, userId);
20875            }
20876        }
20877
20878        @Override
20879        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20880            synchronized (mPackages) {
20881                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20882                        packageName, userId);
20883            }
20884        }
20885
20886        @Override
20887        public void setKeepUninstalledPackages(final List<String> packageList) {
20888            Preconditions.checkNotNull(packageList);
20889            List<String> removedFromList = null;
20890            synchronized (mPackages) {
20891                if (mKeepUninstalledPackages != null) {
20892                    final int packagesCount = mKeepUninstalledPackages.size();
20893                    for (int i = 0; i < packagesCount; i++) {
20894                        String oldPackage = mKeepUninstalledPackages.get(i);
20895                        if (packageList != null && packageList.contains(oldPackage)) {
20896                            continue;
20897                        }
20898                        if (removedFromList == null) {
20899                            removedFromList = new ArrayList<>();
20900                        }
20901                        removedFromList.add(oldPackage);
20902                    }
20903                }
20904                mKeepUninstalledPackages = new ArrayList<>(packageList);
20905                if (removedFromList != null) {
20906                    final int removedCount = removedFromList.size();
20907                    for (int i = 0; i < removedCount; i++) {
20908                        deletePackageIfUnusedLPr(removedFromList.get(i));
20909                    }
20910                }
20911            }
20912        }
20913
20914        @Override
20915        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20916            synchronized (mPackages) {
20917                // If we do not support permission review, done.
20918                if (!mPermissionReviewRequired) {
20919                    return false;
20920                }
20921
20922                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20923                if (packageSetting == null) {
20924                    return false;
20925                }
20926
20927                // Permission review applies only to apps not supporting the new permission model.
20928                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20929                    return false;
20930                }
20931
20932                // Legacy apps have the permission and get user consent on launch.
20933                PermissionsState permissionsState = packageSetting.getPermissionsState();
20934                return permissionsState.isPermissionReviewRequired(userId);
20935            }
20936        }
20937
20938        @Override
20939        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20940            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20941        }
20942
20943        @Override
20944        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20945                int userId) {
20946            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20947        }
20948
20949        @Override
20950        public void setDeviceAndProfileOwnerPackages(
20951                int deviceOwnerUserId, String deviceOwnerPackage,
20952                SparseArray<String> profileOwnerPackages) {
20953            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20954                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20955        }
20956
20957        @Override
20958        public boolean isPackageDataProtected(int userId, String packageName) {
20959            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20960        }
20961    }
20962
20963    @Override
20964    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20965        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20966        synchronized (mPackages) {
20967            final long identity = Binder.clearCallingIdentity();
20968            try {
20969                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20970                        packageNames, userId);
20971            } finally {
20972                Binder.restoreCallingIdentity(identity);
20973            }
20974        }
20975    }
20976
20977    private static void enforceSystemOrPhoneCaller(String tag) {
20978        int callingUid = Binder.getCallingUid();
20979        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20980            throw new SecurityException(
20981                    "Cannot call " + tag + " from UID " + callingUid);
20982        }
20983    }
20984
20985    boolean isHistoricalPackageUsageAvailable() {
20986        return mPackageUsage.isHistoricalPackageUsageAvailable();
20987    }
20988
20989    /**
20990     * Return a <b>copy</b> of the collection of packages known to the package manager.
20991     * @return A copy of the values of mPackages.
20992     */
20993    Collection<PackageParser.Package> getPackages() {
20994        synchronized (mPackages) {
20995            return new ArrayList<>(mPackages.values());
20996        }
20997    }
20998
20999    /**
21000     * Logs process start information (including base APK hash) to the security log.
21001     * @hide
21002     */
21003    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21004            String apkFile, int pid) {
21005        if (!SecurityLog.isLoggingEnabled()) {
21006            return;
21007        }
21008        Bundle data = new Bundle();
21009        data.putLong("startTimestamp", System.currentTimeMillis());
21010        data.putString("processName", processName);
21011        data.putInt("uid", uid);
21012        data.putString("seinfo", seinfo);
21013        data.putString("apkFile", apkFile);
21014        data.putInt("pid", pid);
21015        Message msg = mProcessLoggingHandler.obtainMessage(
21016                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21017        msg.setData(data);
21018        mProcessLoggingHandler.sendMessage(msg);
21019    }
21020
21021    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21022        return mCompilerStats.getPackageStats(pkgName);
21023    }
21024
21025    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21026        return getOrCreateCompilerPackageStats(pkg.packageName);
21027    }
21028
21029    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21030        return mCompilerStats.getOrCreatePackageStats(pkgName);
21031    }
21032
21033    public void deleteCompilerPackageStats(String pkgName) {
21034        mCompilerStats.deletePackageStats(pkgName);
21035    }
21036}
21037